From c93f968c1af0b541ca683c0d1a2d3fe48131b416 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 01:23:13 +0000 Subject: [PATCH] chore: bump the k8s group across 1 directory with 5 updates Bumps the k8s group with 2 updates in the /constraint directory: [k8s.io/apiextensions-apiserver](https://github.com/kubernetes/apiextensions-apiserver) and [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime). Updates `k8s.io/apiextensions-apiserver` from 0.36.4 to 0.37.0 - [Release notes](https://github.com/kubernetes/apiextensions-apiserver/releases) - [Commits](https://github.com/kubernetes/apiextensions-apiserver/compare/v0.36.4...v0.37.0) Updates `k8s.io/apimachinery` from 0.36.4 to 0.37.0 - [Commits](https://github.com/kubernetes/apimachinery/compare/v0.36.4...v0.37.0) Updates `k8s.io/client-go` from 0.36.4 to 0.37.0 - [Changelog](https://github.com/kubernetes/client-go/blob/master/CHANGELOG.md) - [Commits](https://github.com/kubernetes/client-go/compare/v0.36.4...v0.37.0) Updates `k8s.io/utils` from 0.0.0-20260210185600-b8788abfbbc2 to 0.0.0-20260626114624-be93311217bd - [Commits](https://github.com/kubernetes/utils/commits) Updates `sigs.k8s.io/controller-runtime` from 0.24.1 to 0.25.0 - [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases) - [Changelog](https://github.com/kubernetes-sigs/controller-runtime/blob/main/RELEASE.md) - [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.24.1...v0.25.0) --- updated-dependencies: - dependency-name: k8s.io/apiextensions-apiserver dependency-version: 0.37.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s - dependency-name: k8s.io/apimachinery dependency-version: 0.37.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s - dependency-name: k8s.io/client-go dependency-version: 0.37.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s - dependency-name: k8s.io/utils dependency-version: 0.0.0-20260626114624-be93311217bd dependency-type: direct:production update-type: version-update:semver-patch dependency-group: k8s - dependency-name: sigs.k8s.io/controller-runtime dependency-version: 0.25.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s ... Signed-off-by: dependabot[bot] --- constraint/go.mod | 48 +- constraint/go.sum | 132 +- .../fxamacker/cbor/v2/.golangci.yml | 176 +- .../github.com/fxamacker/cbor/v2/README.md | 11 +- .../github.com/fxamacker/cbor/v2/cache.go | 257 +- .../github.com/fxamacker/cbor/v2/decode.go | 440 +- .../fxamacker/cbor/v2/decode_map_utils.go | 98 + .../github.com/fxamacker/cbor/v2/diagnose.go | 25 +- .../github.com/fxamacker/cbor/v2/encode.go | 55 +- .../fxamacker/cbor/v2/simplevalue.go | 2 +- .../github.com/fxamacker/cbor/v2/stream.go | 48 +- .../fxamacker/cbor/v2/structfields.go | 65 +- .../github.com/fxamacker/cbor/v2/valid.go | 20 +- .../go-openapi/jsonpointer/.gitignore | 6 +- .../go-openapi/jsonpointer/.golangci.yml | 115 +- .../go-openapi/jsonpointer/CODE_OF_CONDUCT.md | 6 +- .../go-openapi/jsonpointer/CONTRIBUTORS.md | 25 + .../github.com/go-openapi/jsonpointer/LICENSE | 1 - .../github.com/go-openapi/jsonpointer/NOTICE | 39 + .../go-openapi/jsonpointer/README.md | 180 +- .../go-openapi/jsonpointer/SECURITY.md | 37 + .../go-openapi/jsonpointer/errors.go | 60 + .../go-openapi/jsonpointer/ifaces.go | 50 + .../go-openapi/jsonpointer/jsonname/doc.go | 5 + .../jsonpointer/jsonname/go_name_provider.go | 288 + .../go-openapi/jsonpointer/jsonname/ifaces.go | 16 + .../jsonpointer/jsonname/name_provider.go | 140 + .../go-openapi/jsonpointer/options.go | 85 + .../go-openapi/jsonpointer/pointer.go | 844 +- .../go-openapi/jsonreference/.editorconfig | 26 + .../go-openapi/jsonreference/.gitignore | 6 +- .../go-openapi/jsonreference/.golangci.yml | 103 +- .../jsonreference/CODE_OF_CONDUCT.md | 6 +- .../go-openapi/jsonreference/CONTRIBUTORS.md | 21 + .../go-openapi/jsonreference/NOTICE | 39 + .../go-openapi/jsonreference/README.md | 122 +- .../go-openapi/jsonreference/SECURITY.md | 37 + .../jsonreference/internal/normalize_url.go | 11 +- .../go-openapi/jsonreference/reference.go | 112 +- .../github.com/go-openapi/swag/.codecov.yml | 4 + .../github.com/go-openapi/swag/.gitignore | 2 + .../github.com/go-openapi/swag/.golangci.yml | 125 +- .../github.com/go-openapi/swag/.mockery.yml | 30 + .../go-openapi/swag/CODE_OF_CONDUCT.md | 6 +- .../go-openapi/swag/CONTRIBUTORS.md | 36 + .../github.com/go-openapi/swag/README.md | 230 +- .../github.com/go-openapi/swag/SECURITY.md | 37 + .../go-openapi/swag/cmdutils/LICENSE | 202 + .../go-openapi/swag/cmdutils/cmd_utils.go | 13 + .../go-openapi/swag/cmdutils/doc.go | 5 + .../go-openapi/swag/cmdutils_iface.go | 11 + .../github.com/go-openapi/swag/conv/LICENSE | 202 + .../go-openapi/swag/conv/convert.go | 161 + .../go-openapi/swag/conv/convert_types.go | 72 + .../github.com/go-openapi/swag/conv/doc.go | 15 + .../github.com/go-openapi/swag/conv/format.go | 28 + .../github.com/go-openapi/swag/conv/sizeof.go | 20 + .../go-openapi/swag/conv/type_constraints.go | 29 + .../github.com/go-openapi/swag/conv_iface.go | 486 + .../github.com/go-openapi/swag/convert.go | 208 - .../go-openapi/swag/convert_types.go | 730 -- .../vendor/github.com/go-openapi/swag/doc.go | 70 +- .../vendor/github.com/go-openapi/swag/file.go | 33 - .../go-openapi/swag/fileutils/LICENSE | 202 + .../go-openapi/swag/fileutils/doc.go | 10 + .../go-openapi/swag/fileutils/file.go | 22 + .../go-openapi/swag/{ => fileutils}/path.go | 29 +- .../go-openapi/swag/fileutils_iface.go | 33 + .../vendor/github.com/go-openapi/swag/go.work | 21 + .../github.com/go-openapi/swag/go.work.sum | 7 + .../go-openapi/swag/initialism_index.go | 202 - .../vendor/github.com/go-openapi/swag/json.go | 312 - .../go-openapi/swag/jsonname_iface.go | 24 + .../go-openapi/swag/jsonutils/LICENSE | 202 + .../go-openapi/swag/jsonutils/README.md | 109 + .../go-openapi/swag/jsonutils/adapters/doc.go | 8 + .../swag/jsonutils/adapters/ifaces/doc.go | 5 + .../swag/jsonutils/adapters/ifaces/ifaces.go | 84 + .../adapters/ifaces/registry_iface.go | 91 + .../swag/jsonutils/adapters/registry.go | 229 + .../jsonutils/adapters/stdlib/json/adapter.go | 133 + .../jsonutils/adapters/stdlib/json/doc.go | 5 + .../jsonutils/adapters/stdlib/json/lexer.go | 356 + .../jsonutils/adapters/stdlib/json/options.go | 52 + .../adapters/stdlib/json/ordered_map.go | 289 + .../jsonutils/adapters/stdlib/json/pool.go | 42 + .../adapters/stdlib/json/register.go | 34 + .../jsonutils/adapters/stdlib/json/writer.go | 88 + .../go-openapi/swag/jsonutils/concat.go | 92 + .../go-openapi/swag/jsonutils/doc.go | 7 + .../go-openapi/swag/jsonutils/json.go | 116 + .../go-openapi/swag/jsonutils/ordered_map.go | 114 + .../go-openapi/swag/jsonutils_iface.go | 65 + .../go-openapi/swag/loading/LICENSE | 202 + .../github.com/go-openapi/swag/loading/doc.go | 29 + .../go-openapi/swag/loading/errors.go | 15 + .../go-openapi/swag/loading/json.go | 25 + .../go-openapi/swag/{ => loading}/loading.go | 120 +- .../go-openapi/swag/loading/options.go | 170 + .../go-openapi/swag/loading/yaml.go | 37 + .../go-openapi/swag/loading_iface.go | 93 + .../swag/{ => mangling}/BENCHMARK.md | 48 +- .../go-openapi/swag/mangling/LICENSE | 202 + .../go-openapi/swag/mangling/doc.go | 25 + .../swag/mangling/initialism_index.go | 270 + .../go-openapi/swag/mangling/name_lexem.go | 186 + .../go-openapi/swag/mangling/name_mangler.go | 370 + .../go-openapi/swag/mangling/options.go | 150 + .../go-openapi/swag/mangling/pools.go | 123 + .../go-openapi/swag/mangling/split.go | 341 + .../swag/{ => mangling}/string_bytes.go | 5 +- .../go-openapi/swag/mangling/util.go | 118 + .../go-openapi/swag/mangling_iface.go | 69 + .../github.com/go-openapi/swag/name_lexem.go | 93 - .../vendor/github.com/go-openapi/swag/net.go | 38 - .../go-openapi/swag/netutils/LICENSE | 202 + .../go-openapi/swag/netutils/doc.go | 5 + .../go-openapi/swag/netutils/net.go | 31 + .../go-openapi/swag/netutils_iface.go | 13 + .../github.com/go-openapi/swag/pools/LICENSE | 202 + .../go-openapi/swag/pools/README.md | 1 + .../github.com/go-openapi/swag/pools/debug.go | 17 + .../go-openapi/swag/pools/debug_off.go | 51 + .../go-openapi/swag/pools/debug_on.go | 237 + .../github.com/go-openapi/swag/pools/doc.go | 26 + .../github.com/go-openapi/swag/pools/pools.go | 410 + .../github.com/go-openapi/swag/split.go | 508 - .../go-openapi/swag/stringutils/LICENSE | 202 + .../swag/stringutils/collection_formats.go | 74 + .../go-openapi/swag/stringutils/doc.go | 5 + .../go-openapi/swag/stringutils/strings.go | 23 + .../go-openapi/swag/stringutils_iface.go | 34 + .../go-openapi/swag/typeutils/LICENSE | 202 + .../go-openapi/swag/typeutils/doc.go | 5 + .../go-openapi/swag/typeutils/types.go | 80 + .../go-openapi/swag/typeutils_iface.go | 12 + .../vendor/github.com/go-openapi/swag/util.go | 364 - .../vendor/github.com/go-openapi/swag/yaml.go | 481 - .../go-openapi/swag/yamlutils/LICENSE | 202 + .../go-openapi/swag/yamlutils/doc.go | 13 + .../go-openapi/swag/yamlutils/errors.go | 15 + .../go-openapi/swag/yamlutils/ordered_map.go | 335 + .../go-openapi/swag/yamlutils/yaml.go | 328 + .../go-openapi/swag/yamlutils_iface.go | 20 + .../github.com/google/cel-go/cel/prompt.go | 466 +- .../github.com/google/cel-go/ext/lists.go | 3 + .../github.com/josharian/intern/README.md | 5 - .../github.com/josharian/intern/intern.go | 44 - .../github.com/josharian/intern/license.md | 21 - .../vendor/github.com/mailru/easyjson/LICENSE | 7 - .../github.com/mailru/easyjson/buffer/pool.go | 278 - .../mailru/easyjson/jlexer/bytestostr.go | 24 - .../easyjson/jlexer/bytestostr_nounsafe.go | 13 - .../mailru/easyjson/jlexer/error.go | 15 - .../mailru/easyjson/jlexer/lexer.go | 1244 --- .../mailru/easyjson/jwriter/writer.go | 405 - .../otel/semconv/v1.17.0/README.md | 3 - .../otel/semconv/v1.17.0/doc.go | 9 - .../otel/semconv/v1.17.0/event.go | 188 - .../otel/semconv/v1.17.0/exception.go | 9 - .../otel/semconv/v1.17.0/http.go | 10 - .../otel/semconv/v1.17.0/resource.go | 1999 ---- .../otel/semconv/v1.17.0/schema.go | 9 - .../otel/semconv/v1.17.0/trace.go | 3364 ------- constraint/vendor/gopkg.in/yaml.v3/LICENSE | 50 - constraint/vendor/gopkg.in/yaml.v3/README.md | 150 - constraint/vendor/gopkg.in/yaml.v3/apic.go | 747 -- constraint/vendor/gopkg.in/yaml.v3/decode.go | 1000 -- .../vendor/gopkg.in/yaml.v3/emitterc.go | 2020 ---- constraint/vendor/gopkg.in/yaml.v3/encode.go | 577 -- constraint/vendor/gopkg.in/yaml.v3/parserc.go | 1258 --- constraint/vendor/gopkg.in/yaml.v3/readerc.go | 434 - constraint/vendor/gopkg.in/yaml.v3/resolve.go | 326 - .../vendor/gopkg.in/yaml.v3/scannerc.go | 3038 ------ constraint/vendor/gopkg.in/yaml.v3/sorter.go | 134 - constraint/vendor/gopkg.in/yaml.v3/writerc.go | 48 - constraint/vendor/gopkg.in/yaml.v3/yaml.go | 698 -- constraint/vendor/gopkg.in/yaml.v3/yamlh.go | 807 -- .../vendor/gopkg.in/yaml.v3/yamlprivateh.go | 198 - .../vendor/k8s.io/api/admission/v1/types.go | 2 +- .../admissionregistration/v1/generated.proto | 8 +- .../api/admissionregistration/v1/types.go | 36 +- .../v1alpha1/generated.proto | 8 +- .../admissionregistration/v1alpha1/types.go | 26 +- .../v1beta1/generated.proto | 8 +- .../admissionregistration/v1beta1/types.go | 34 +- .../api/apidiscovery/v2/generated.proto | 18 + .../k8s.io/api/apidiscovery/v2/types.go | 22 +- .../api/apidiscovery/v2beta1/generated.pb.go | 1537 --- .../api/apidiscovery/v2beta1/generated.proto | 156 - .../k8s.io/api/apidiscovery/v2beta1/types.go | 163 - .../v2beta1/zz_generated.deepcopy.go | 190 - .../zz_generated.prerelease-lifecycle.go | 58 - .../v1alpha1/generated.proto | 1 + .../api/apiserverinternal/v1alpha1/types.go | 5 +- .../vendor/k8s.io/api/apps/v1/generated.proto | 50 +- constraint/vendor/k8s.io/api/apps/v1/types.go | 98 +- .../k8s.io/api/apps/v1beta1/generated.proto | 48 +- .../vendor/k8s.io/api/apps/v1beta1/types.go | 77 +- .../v1beta1/types_swagger_doc_generated.go | 2 +- .../k8s.io/api/apps/v1beta2/generated.proto | 56 +- .../vendor/k8s.io/api/apps/v1beta2/types.go | 91 +- .../api/authentication/v1/generated.pb.go | 309 + .../api/authentication/v1/generated.proto | 25 +- .../k8s.io/api/authentication/v1/types.go | 58 +- .../v1/types_swagger_doc_generated.go | 3 +- .../v1/zz_generated.deepcopy.go | 35 + .../authentication/v1alpha1/generated.proto | 2 + .../api/authentication/v1alpha1/types.go | 4 +- .../authentication/v1beta1/generated.proto | 4 + .../api/authentication/v1beta1/types.go | 8 +- .../api/authorization/v1/generated.proto | 16 + .../k8s.io/api/authorization/v1/types.go | 24 +- .../api/authorization/v1beta1/generated.proto | 16 + .../k8s.io/api/authorization/v1beta1/types.go | 24 +- .../k8s.io/api/autoscaling/v1/generated.pb.go | 29 + .../k8s.io/api/autoscaling/v1/generated.proto | 30 +- .../vendor/k8s.io/api/autoscaling/v1/types.go | 36 +- .../v1/types_swagger_doc_generated.go | 7 +- .../autoscaling/v1/zz_generated.deepcopy.go | 5 + .../k8s.io/api/autoscaling/v2/generated.pb.go | 29 + .../k8s.io/api/autoscaling/v2/generated.proto | 37 +- .../vendor/k8s.io/api/autoscaling/v2/types.go | 41 +- .../v2/types_swagger_doc_generated.go | 11 +- .../autoscaling/v2/zz_generated.deepcopy.go | 5 + .../k8s.io/api/batch/v1/generated.pb.go | 368 + .../k8s.io/api/batch/v1/generated.proto | 84 +- .../vendor/k8s.io/api/batch/v1/types.go | 94 +- .../batch/v1/types_swagger_doc_generated.go | 15 +- .../api/batch/v1/zz_generated.deepcopy.go | 44 + .../api/batch/v1/zz_generated.model_name.go | 5 + .../k8s.io/api/batch/v1beta1/generated.proto | 4 +- .../vendor/k8s.io/api/batch/v1beta1/types.go | 8 +- .../api/certificates/v1/generated.pb.go | 2772 ++++- .../api/certificates/v1/generated.proto | 293 +- .../k8s.io/api/certificates/v1/register.go | 4 + .../k8s.io/api/certificates/v1/types.go | 340 +- .../v1/types_swagger_doc_generated.go | 82 + .../certificates/v1/zz_generated.deepcopy.go | 206 + .../v1/zz_generated.model_name.go | 35 + .../v1/zz_generated.prerelease-lifecycle.go | 24 + .../api/certificates/v1alpha1/generated.proto | 4 +- .../k8s.io/api/certificates/v1alpha1/types.go | 8 +- .../v1alpha1/types_swagger_doc_generated.go | 2 +- .../api/certificates/v1beta1/generated.proto | 20 +- .../k8s.io/api/certificates/v1beta1/types.go | 38 +- .../v1beta1/types_swagger_doc_generated.go | 2 +- .../zz_generated.prerelease-lifecycle.go | 32 +- .../api/coordination/v1/generated.proto | 5 +- .../k8s.io/api/coordination/v1/types.go | 9 +- .../v1/types_swagger_doc_generated.go | 6 +- .../api/coordination/v1alpha2/generated.proto | 13 +- .../k8s.io/api/coordination/v1alpha2/types.go | 17 +- .../v1alpha2/types_swagger_doc_generated.go | 14 +- .../api/coordination/v1beta1/generated.proto | 18 +- .../k8s.io/api/coordination/v1beta1/types.go | 26 +- .../v1beta1/types_swagger_doc_generated.go | 20 +- .../vendor/k8s.io/api/core/v1/generated.pb.go | 2761 ++++- .../vendor/k8s.io/api/core/v1/generated.proto | 460 +- .../vendor/k8s.io/api/core/v1/register.go | 1 - constraint/vendor/k8s.io/api/core/v1/types.go | 638 +- .../core/v1/types_swagger_doc_generated.go | 139 +- .../api/core/v1/zz_generated.deepcopy.go | 288 +- .../api/core/v1/zz_generated.model_name.go | 40 +- .../v1/zz_generated.prerelease-lifecycle.go | 6 - .../k8s.io/api/discovery/v1/generated.proto | 10 +- .../vendor/k8s.io/api/discovery/v1/types.go | 16 +- .../api/discovery/v1beta1/generated.proto | 10 +- .../k8s.io/api/discovery/v1beta1/types.go | 16 +- .../k8s.io/api/events/v1/generated.proto | 4 +- .../vendor/k8s.io/api/events/v1/types.go | 8 +- .../events/v1/types_swagger_doc_generated.go | 4 +- .../k8s.io/api/events/v1beta1/generated.proto | 4 +- .../vendor/k8s.io/api/events/v1beta1/types.go | 8 +- .../v1beta1/types_swagger_doc_generated.go | 4 +- .../k8s.io/api/extensions/v1beta1/doc.go | 5 +- .../api/extensions/v1beta1/generated.proto | 20 +- .../k8s.io/api/extensions/v1beta1/types.go | 46 +- .../v1beta1/zz_generated.validations.go | 279 - .../k8s.io/api/flowcontrol/v1/generated.proto | 62 +- .../vendor/k8s.io/api/flowcontrol/v1/types.go | 70 +- .../v1/types_swagger_doc_generated.go | 4 +- .../api/flowcontrol/v1beta1/generated.proto | 62 +- .../k8s.io/api/flowcontrol/v1beta1/types.go | 70 +- .../v1beta1/types_swagger_doc_generated.go | 4 +- .../api/flowcontrol/v1beta2/generated.proto | 62 +- .../k8s.io/api/flowcontrol/v1beta2/types.go | 70 +- .../v1beta2/types_swagger_doc_generated.go | 4 +- .../api/flowcontrol/v1beta3/generated.proto | 62 +- .../k8s.io/api/flowcontrol/v1beta3/types.go | 70 +- .../v1beta3/types_swagger_doc_generated.go | 4 +- .../v1alpha2 => lifecycle/v1alpha1}/doc.go | 7 +- .../v1alpha1}/generated.pb.go | 2265 ++--- .../api/lifecycle/v1alpha1/generated.proto | 529 + .../k8s.io/api/lifecycle/v1alpha1/register.go | 55 + .../k8s.io/api/lifecycle/v1alpha1/types.go | 680 ++ .../v1alpha1/types_swagger_doc_generated.go | 188 + .../v1alpha1/zz_generated.deepcopy.go | 406 + .../v1alpha1/zz_generated.model_name.go | 97 + .../zz_generated.prerelease-lifecycle.go | 94 + .../k8s.io/api/networking/v1/generated.proto | 52 +- .../vendor/k8s.io/api/networking/v1/types.go | 74 +- .../v1/types_swagger_doc_generated.go | 25 +- .../api/networking/v1beta1/generated.proto | 38 +- .../k8s.io/api/networking/v1beta1/types.go | 56 +- .../v1beta1/types_swagger_doc_generated.go | 23 +- .../vendor/k8s.io/api/node/v1/generated.proto | 9 +- constraint/vendor/k8s.io/api/node/v1/types.go | 13 +- .../node/v1/types_swagger_doc_generated.go | 2 +- .../k8s.io/api/node/v1alpha1/generated.proto | 9 +- .../vendor/k8s.io/api/node/v1alpha1/types.go | 13 +- .../v1alpha1/types_swagger_doc_generated.go | 2 +- .../k8s.io/api/node/v1beta1/generated.proto | 9 +- .../vendor/k8s.io/api/node/v1beta1/types.go | 13 +- .../v1beta1/types_swagger_doc_generated.go | 2 +- .../k8s.io/api/policy/v1/generated.proto | 23 +- .../vendor/k8s.io/api/policy/v1/types.go | 29 +- .../policy/v1/types_swagger_doc_generated.go | 18 +- .../k8s.io/api/policy/v1beta1/generated.proto | 23 +- .../vendor/k8s.io/api/policy/v1beta1/types.go | 29 +- .../v1beta1/types_swagger_doc_generated.go | 18 +- .../vendor/k8s.io/api/rbac/v1/generated.proto | 64 +- constraint/vendor/k8s.io/api/rbac/v1/types.go | 80 +- .../rbac/v1/types_swagger_doc_generated.go | 48 +- .../k8s.io/api/rbac/v1alpha1/generated.proto | 64 +- .../vendor/k8s.io/api/rbac/v1alpha1/types.go | 80 +- .../v1alpha1/types_swagger_doc_generated.go | 48 +- .../k8s.io/api/rbac/v1beta1/generated.proto | 64 +- .../vendor/k8s.io/api/rbac/v1beta1/types.go | 80 +- .../v1beta1/types_swagger_doc_generated.go | 48 +- .../vendor/k8s.io/api/resource/v1/doc.go | 4 + .../k8s.io/api/resource/v1/generated.pb.go | 7416 +++++++++----- .../k8s.io/api/resource/v1/generated.proto | 707 +- .../vendor/k8s.io/api/resource/v1/register.go | 2 + .../vendor/k8s.io/api/resource/v1/types.go | 821 +- .../v1/types_swagger_doc_generated.go | 174 +- .../api/resource/v1/zz_generated.deepcopy.go | 258 +- .../resource/v1/zz_generated.model_name.go | 44 +- .../v1/zz_generated.prerelease-lifecycle.go | 12 + .../resource/v1/zz_generated.validations.go | 3348 +++++++ .../api/resource/v1alpha3/generated.pb.go | 941 +- .../api/resource/v1alpha3/generated.proto | 160 +- .../k8s.io/api/resource/v1alpha3/types.go | 170 +- .../v1alpha3/types_swagger_doc_generated.go | 48 +- .../v1alpha3/zz_generated.deepcopy.go | 107 + .../v1alpha3/zz_generated.model_name.go | 15 + .../api/resource/v1beta1/generated.pb.go | 1337 ++- .../api/resource/v1beta1/generated.proto | 595 +- .../k8s.io/api/resource/v1beta1/types.go | 668 +- .../v1beta1/types_swagger_doc_generated.go | 125 +- .../resource/v1beta1/zz_generated.deepcopy.go | 121 +- .../v1beta1/zz_generated.model_name.go | 19 +- .../api/resource/v1beta2/generated.pb.go | 1079 +- .../api/resource/v1beta2/generated.proto | 598 +- .../k8s.io/api/resource/v1beta2/types.go | 675 +- .../v1beta2/types_swagger_doc_generated.go | 123 +- .../resource/v1beta2/zz_generated.deepcopy.go | 121 +- .../v1beta2/zz_generated.model_name.go | 19 +- .../k8s.io/api/scheduling/v1/generated.proto | 2 +- .../vendor/k8s.io/api/scheduling/v1/types.go | 6 +- .../v1/types_swagger_doc_generated.go | 2 +- .../api/scheduling/v1alpha2/generated.proto | 550 - .../k8s.io/api/scheduling/v1alpha2/types.go | 601 -- .../v1alpha2/types_swagger_doc_generated.go | 217 - .../v1alpha2/zz_generated.deepcopy.go | 484 - .../v1alpha2/zz_generated.model_name.go | 112 - .../k8s.io/api/scheduling/v1alpha3/doc.go | 37 + .../api/scheduling/v1alpha3/generated.pb.go | 8927 +++++++++++++++++ .../api/scheduling/v1alpha3/generated.proto | 1353 +++ .../{v1alpha2 => v1alpha3}/register.go | 6 +- .../k8s.io/api/scheduling/v1alpha3/types.go | 1429 +++ .../v1alpha3/types_swagger_doc_generated.go | 498 + .../v1alpha3/zz_generated.deepcopy.go | 1172 +++ .../v1alpha3/zz_generated.model_name.go | 257 + .../v1alpha3/zz_generated.validations.go | 3368 +++++++ .../api/scheduling/v1beta1/generated.pb.go | 5901 ++++++++++- .../api/scheduling/v1beta1/generated.proto | 794 +- .../k8s.io/api/scheduling/v1beta1/register.go | 4 + .../k8s.io/api/scheduling/v1beta1/types.go | 872 +- .../v1beta1/types_swagger_doc_generated.go | 289 +- .../v1beta1/zz_generated.deepcopy.go | 709 +- .../v1beta1/zz_generated.model_name.go | 140 + .../zz_generated.prerelease-lifecycle.go | 72 + .../k8s.io/api/storage/v1/generated.pb.go | 789 +- .../k8s.io/api/storage/v1/generated.proto | 104 +- .../vendor/k8s.io/api/storage/v1/types.go | 134 +- .../storage/v1/types_swagger_doc_generated.go | 51 +- .../api/storage/v1/zz_generated.deepcopy.go | 74 + .../api/storage/v1/zz_generated.model_name.go | 15 + .../api/storage/v1alpha1/generated.proto | 16 +- .../k8s.io/api/storage/v1alpha1/types.go | 28 +- .../v1alpha1/types_swagger_doc_generated.go | 9 +- .../api/storage/v1beta1/generated.pb.go | 789 +- .../api/storage/v1beta1/generated.proto | 103 +- .../k8s.io/api/storage/v1beta1/types.go | 133 +- .../v1beta1/types_swagger_doc_generated.go | 51 +- .../storage/v1beta1/zz_generated.deepcopy.go | 74 + .../v1beta1/zz_generated.model_name.go | 15 + .../v2beta1 => storagemigration/v1}/doc.go | 8 +- .../api/storagemigration/v1/generated.pb.go | 904 ++ .../api/storagemigration/v1/generated.proto | 86 + .../v1}/register.go | 26 +- .../k8s.io/api/storagemigration/v1/types.go | 95 + .../v1/types_swagger_doc_generated.go | 70 + .../v1/zz_generated.deepcopy.go | 128 + .../v1}/zz_generated.model_name.go | 23 +- .../v1/zz_generated.prerelease-lifecycle.go | 34 + .../storagemigration/v1beta1/generated.proto | 4 + .../api/storagemigration/v1beta1/types.go | 12 +- .../zz_generated.prerelease-lifecycle.go | 24 +- .../pkg/apis/apiextensions/v1/types.go | 6 +- .../v1/zz_generated.conversion.go | 96 +- .../pkg/apis/apiextensions/v1beta1/types.go | 6 +- .../v1beta1/zz_generated.conversion.go | 96 +- .../apiextensions/validation/validation.go | 14 +- .../pkg/apiserver/schema/cel/model/schemas.go | 23 +- .../apiserver/schema/defaulting/validation.go | 4 +- .../apiserver/schema/objectmeta/validation.go | 22 +- .../pkg/apiserver/validation/metrics.go | 12 +- .../v1/customresourcedefinition.go | 45 +- .../v1beta1/customresourcedefinition.go | 45 +- .../applyconfiguration/internal/internal.go | 1250 +++ .../client/clientset/clientset/clientset.go | 4 +- .../apimachinery/pkg/api/meta/interfaces.go | 109 +- .../k8s.io/apimachinery/pkg/api/meta/meta.go | 4 + .../pkg/api/meta/multirestmapper.go | 132 +- .../apimachinery/pkg/api/meta/priority.go | 130 +- .../apimachinery/pkg/api/meta/restmapper.go | 56 +- .../pkg/api/operation/operation.go | 32 +- .../apimachinery/pkg/api/resource/quantity.go | 11 + .../pkg/api/validate/content/kube.go | 16 + .../pkg/api/validate/dependentrequired.go | 83 + .../pkg/api/validate/discriminator.go | 3 + .../apimachinery/pkg/api/validate/each.go | 174 +- .../apimachinery/pkg/api/validate/enum.go | 35 +- .../apimachinery/pkg/api/validate/errors.go | 96 + .../apimachinery/pkg/api/validate/item.go | 87 +- .../apimachinery/pkg/api/validate/limits.go | 20 + .../pkg/api/validate/monotonic.go | 43 + .../apimachinery/pkg/api/validate/options.go | 11 +- .../apimachinery/pkg/api/validate/strfmt.go | 22 + .../apimachinery/pkg/api/validate/subfield.go | 3 + .../apimachinery/pkg/api/validate/update.go | 154 +- .../pkg/api/validation/objectmeta.go | 58 +- .../pkg/apis/meta/v1/generated.proto | 27 + .../apimachinery/pkg/apis/meta/v1/types.go | 63 +- .../pkg/apis/meta/v1/unstructured/helpers.go | 1 + .../pkg/apis/meta/v1/validation/doc.go | 21 + .../pkg/apis/meta/v1/validation/validation.go | 74 +- .../v1/validation/zz_generated.validations.go | 638 ++ .../pkg/apis/meta/v1beta1/types.go | 2 +- .../pkg/conversion/queryparams/convert.go | 4 +- .../apimachinery/pkg/labels/selector.go | 9 +- .../k8s.io/apimachinery/pkg/runtime/codec.go | 2 + .../apimachinery/pkg/runtime/conversion.go | 13 - .../apimachinery/pkg/runtime/converter.go | 34 +- .../apimachinery/pkg/runtime/fieldinfo_126.go | 26 + .../apimachinery/pkg/runtime/fieldinfo_127.go | 33 + .../apimachinery/pkg/runtime/generated.proto | 6 +- .../k8s.io/apimachinery/pkg/runtime/helper.go | 20 +- .../k8s.io/apimachinery/pkg/runtime/scheme.go | 12 +- .../pkg/runtime/serializer/cbor/cbor.go | 31 +- .../runtime/serializer/cbor/collections.go | 328 + .../serializer/cbor/internal/modes/encode.go | 10 +- .../runtime/serializer/json/collections.go | 103 +- .../pkg/runtime/serializer/json/json.go | 1 + .../serializer/protobuf/collections.go | 13 +- .../runtime/serializer/protobuf/protobuf.go | 17 +- .../serializer/versioning/versioning.go | 2 + .../pkg/runtime/swagger_doc_generator.go | 32 +- .../k8s.io/apimachinery/pkg/runtime/types.go | 8 +- .../apimachinery/pkg/util/intstr/intstr.go | 1 + .../managedfields/internal/fieldmanager.go | 32 +- .../managedfields/internal/typeconverter.go | 18 + .../internal/versionconverter.go | 17 +- .../util/validation/field/error_matcher.go | 90 +- .../pkg/util/validation/field/errors.go | 20 + .../apimachinery/pkg/util/validation/ip.go | 2 + .../apiserver/pkg/apis/apiserver/v1/types.go | 10 +- .../apiserver/v1/zz_generated.conversion.go | 132 +- .../pkg/apis/apiserver/v1alpha1/types.go | 12 +- .../v1alpha1/zz_generated.conversion.go | 118 +- .../pkg/apis/apiserver/v1beta1/types.go | 10 +- .../v1beta1/zz_generated.conversion.go | 110 +- .../apiserver/pkg/apis/audit/v1/types.go | 8 +- .../apis/audit/v1/zz_generated.conversion.go | 50 +- .../pkg/authentication/serviceaccount/util.go | 56 +- .../authorization/authorizer/conditions.go | 307 + .../authorization/authorizer/conditionsmap.go | 236 + .../authorizer/conditionsunion.go | 204 + .../pkg/authorization/authorizer/evaluate.go | 280 + .../authorization/authorizer/interfaces.go | 157 +- .../apiserver/pkg/cel/common/valuesreflect.go | 405 +- .../pkg/cel/common/valuesschemalesstyped.go | 565 ++ .../pkg/cel/common/valuesunstructured.go | 92 +- .../apiserver/pkg/cel/environment/base.go | 42 +- .../k8s.io/apiserver/pkg/cel/library/authz.go | 36 +- .../k8s.io/apiserver/pkg/cel/library/cost.go | 11 +- .../k8s.io/apiserver/pkg/cel/library/lists.go | 145 +- .../apiserver/pkg/cel/library/quantity.go | 8 +- .../pkg/endpoints/request/requestinfo.go | 26 +- .../apiserver/pkg/features/kube_features.go | 175 +- .../pkg/util/webhook/authentication.go | 10 +- .../apiserver/pkg/util/webhook/client.go | 76 +- .../apiserver/pkg/util/webhook/metrics.go | 4 +- .../v1/mutatingadmissionpolicy.go | 2 +- .../v1/mutatingadmissionpolicybinding.go | 2 +- .../v1/mutatingwebhookconfiguration.go | 2 +- .../v1/namedrulewithoperations.go | 2 +- .../v1/rulewithoperations.go | 2 +- .../v1/validatingadmissionpolicy.go | 2 +- .../v1/validatingadmissionpolicybinding.go | 2 +- .../v1/validatingwebhookconfiguration.go | 2 +- .../v1alpha1/mutatingadmissionpolicy.go | 2 +- .../mutatingadmissionpolicybinding.go | 2 +- .../v1alpha1/namedrulewithoperations.go | 2 +- .../v1alpha1/validatingadmissionpolicy.go | 2 +- .../validatingadmissionpolicybinding.go | 2 +- .../v1beta1/mutatingadmissionpolicy.go | 2 +- .../v1beta1/mutatingadmissionpolicybinding.go | 2 +- .../v1beta1/mutatingwebhookconfiguration.go | 2 +- .../v1beta1/namedrulewithoperations.go | 2 +- .../v1beta1/validatingadmissionpolicy.go | 2 +- .../validatingadmissionpolicybinding.go | 2 +- .../v1beta1/validatingwebhookconfiguration.go | 2 +- .../v1alpha1/storageversion.go | 2 +- .../apps/v1/controllerrevision.go | 2 +- .../applyconfigurations/apps/v1/daemonset.go | 2 +- .../applyconfigurations/apps/v1/deployment.go | 2 +- .../applyconfigurations/apps/v1/replicaset.go | 2 +- .../apps/v1/statefulset.go | 2 +- .../apps/v1beta1/controllerrevision.go | 2 +- .../apps/v1beta1/deployment.go | 2 +- .../apps/v1beta1/statefulset.go | 2 +- .../apps/v1beta1/statefulsetspec.go | 2 +- .../apps/v1beta2/controllerrevision.go | 2 +- .../apps/v1beta2/daemonset.go | 2 +- .../apps/v1beta2/deployment.go | 2 +- .../apps/v1beta2/replicaset.go | 2 +- .../applyconfigurations/apps/v1beta2/scale.go | 2 +- .../apps/v1beta2/statefulset.go | 2 +- .../autoscaling/v1/horizontalpodautoscaler.go | 4 +- .../v1/horizontalpodautoscalerspec.go | 2 +- .../autoscaling/v1/scale.go | 4 +- .../autoscaling/v2/horizontalpodautoscaler.go | 2 +- .../v2/horizontalpodautoscalercondition.go | 12 + .../autoscaling/v2/hpascalingrules.go | 6 +- .../autoscaling/v2/metricstatus.go | 2 +- .../autoscaling/v2/metricvaluestatus.go | 2 +- .../autoscaling/v2/objectmetricstatus.go | 2 +- .../applyconfigurations/batch/v1/cronjob.go | 2 +- .../applyconfigurations/batch/v1/job.go | 2 +- .../batch/v1/jobschedulingconfiguration.go | 98 + .../applyconfigurations/batch/v1/jobspec.go | 17 + .../applyconfigurations/batch/v1/jobstatus.go | 3 - .../batch/v1beta1/cronjob.go | 2 +- .../v1/certificatesigningrequest.go | 2 +- .../certificates/v1/clustertrustbundle.go | 288 + .../certificates/v1/clustertrustbundlespec.go | 79 + .../certificates/v1/podcertificaterequest.go | 295 + .../v1/podcertificaterequestspec.go | 189 + .../v1/podcertificaterequeststatus.go | 133 + .../v1alpha1/clustertrustbundle.go | 4 +- .../v1beta1/certificatesigningrequest.go | 2 +- .../v1beta1/clustertrustbundle.go | 4 +- .../v1beta1/podcertificaterequest.go | 2 +- .../coordination/v1/lease.go | 3 +- .../coordination/v1/leasespec.go | 4 +- .../coordination/v1alpha2/leasecandidate.go | 3 +- .../v1alpha2/leasecandidatespec.go | 12 +- .../coordination/v1beta1/lease.go | 3 +- .../coordination/v1beta1/leasecandidate.go | 3 +- .../v1beta1/leasecandidatespec.go | 12 +- .../coordination/v1beta1/leasespec.go | 4 +- .../core/v1/clustertrustbundleprojection.go | 12 + .../core/v1/componentstatus.go | 2 +- .../applyconfigurations/core/v1/configmap.go | 4 +- .../core/v1/configmapenvsource.go | 3 +- .../core/v1/configmapkeyselector.go | 5 +- .../core/v1/configmapprojection.go | 2 +- .../core/v1/configmapvolumesource.go | 14 +- .../core/v1/downwardapivolumefile.go | 12 + .../core/v1/downwardapivolumesource.go | 12 + .../core/v1/emptydirvolumesource.go | 17 + .../applyconfigurations/core/v1/endpoints.go | 2 +- .../core/v1/ephemeralcontainer.go | 2 +- .../applyconfigurations/core/v1/event.go | 2 +- .../core/v1/evictionresponder.go | 70 + .../applyconfigurations/core/v1/grpcaction.go | 17 + .../core/v1/httpgetaction.go | 11 + .../applyconfigurations/core/v1/keytopath.go | 12 + .../applyconfigurations/core/v1/limitrange.go | 2 +- .../applyconfigurations/core/v1/namespace.go | 2 +- .../applyconfigurations/core/v1/node.go | 2 +- .../core/v1/nodeallocatablemappedresources.go | 59 + .../v1/nodeallocatableoverheadresources.go | 77 + .../v1/nodeallocatableresourceclaimstatus.go | 41 +- .../core/v1/nodepodpreemptionpolicy.go | 47 + .../applyconfigurations/core/v1/nodespec.go | 11 + .../core/v1/nodesysteminfo.go | 10 + .../core/v1/persistentvolume.go | 2 +- .../core/v1/persistentvolumeclaim.go | 2 +- .../core/v1/persistentvolumeclaimspec.go | 5 +- .../core/v1/persistentvolumeclaimstatus.go | 11 + .../core/v1/persistentvolumespec.go | 2 +- .../applyconfigurations/core/v1/pod.go | 2 +- .../core/v1/podcertificateprojection.go | 12 + .../core/v1/podsecuritycontext.go | 5 +- .../applyconfigurations/core/v1/podspec.go | 32 +- .../applyconfigurations/core/v1/podstatus.go | 16 + .../core/v1/podtemplate.go | 2 +- .../core/v1/podvolumehealth.go | 74 + .../applyconfigurations/core/v1/probe.go | 2 +- .../core/v1/projectedvolumesource.go | 12 + .../core/v1/replicationcontroller.go | 2 +- .../core/v1/resourcequota.go | 2 +- .../core/v1/resourcestatus.go | 9 +- .../applyconfigurations/core/v1/secret.go | 2 +- .../core/v1/secretenvsource.go | 2 +- .../core/v1/secretkeyselector.go | 2 +- .../core/v1/secretprojection.go | 2 +- .../core/v1/secretvolumesource.go | 12 + .../applyconfigurations/core/v1/service.go | 2 +- .../core/v1/serviceaccount.go | 2 +- .../core/v1/serviceaccounttokenprojection.go | 12 + .../applyconfigurations/core/v1/volume.go | 2 +- .../core/v1/volumehealthcondition.go | 73 + .../core/v1/volumehealthstatus.go | 64 + .../core/v1/volumemount.go | 20 +- .../discovery/v1/endpointslice.go | 2 +- .../discovery/v1beta1/endpointslice.go | 2 +- .../applyconfigurations/events/v1/event.go | 4 +- .../events/v1beta1/event.go | 4 +- .../extensions/v1beta1/daemonset.go | 2 +- .../extensions/v1beta1/deployment.go | 2 +- .../extensions/v1beta1/ingress.go | 2 +- .../extensions/v1beta1/ingressrule.go | 2 +- .../extensions/v1beta1/networkpolicy.go | 2 +- .../extensions/v1beta1/replicaset.go | 2 +- .../extensions/v1beta1/scale.go | 2 +- .../flowcontrol/v1/flowschema.go | 2 +- .../flowcontrol/v1/flowschemacondition.go | 3 +- .../v1/prioritylevelconfiguration.go | 2 +- .../v1/prioritylevelconfigurationcondition.go | 3 +- .../flowcontrol/v1beta1/flowschema.go | 2 +- .../v1beta1/flowschemacondition.go | 3 +- .../v1beta1/prioritylevelconfiguration.go | 2 +- .../prioritylevelconfigurationcondition.go | 3 +- .../flowcontrol/v1beta2/flowschema.go | 2 +- .../v1beta2/flowschemacondition.go | 3 +- .../v1beta2/prioritylevelconfiguration.go | 2 +- .../prioritylevelconfigurationcondition.go | 3 +- .../flowcontrol/v1beta3/flowschema.go | 2 +- .../v1beta3/flowschemacondition.go | 3 +- .../v1beta3/prioritylevelconfiguration.go | 2 +- .../prioritylevelconfigurationcondition.go | 3 +- .../applyconfigurations/internal/internal.go | 1988 +++- .../lifecycle/v1alpha1/eviction.go | 327 + .../v1alpha1/evictionpodreference.go | 60 + .../lifecycle/v1alpha1/evictionrequest.go | 310 + .../v1alpha1/evictionrequestpodreference.go | 60 + .../lifecycle/v1alpha1/evictionrequestspec.go | 79 + .../v1alpha1/evictionrequeststatus.go | 75 + .../v1alpha1/evictionrequesttarget.go | 43 + .../lifecycle/v1alpha1/evictionspec.go | 43 + .../lifecycle/v1alpha1/evictionstatus.go | 147 + .../lifecycle/v1alpha1/evictiontarget.go | 43 + .../lifecycle/v1alpha1/requester.go | 68 + .../lifecycle/v1alpha1/responderstatus.go | 118 + .../lifecycle/v1alpha1/targetresponder.go | 102 + .../applyconfigurations/meta/v1/condition.go | 3 + .../meta/v1/deleteoptions.go | 2 +- .../networking/v1/ingress.go | 4 +- .../networking/v1/ingressclass.go | 4 +- .../networking/v1/ingressrule.go | 2 +- .../networking/v1/ingressrulevalue.go | 1 + .../networking/v1/ipaddress.go | 4 +- .../networking/v1/ipaddressspec.go | 2 +- .../networking/v1/networkpolicy.go | 4 +- .../networking/v1/parentreference.go | 8 +- .../networking/v1/servicecidr.go | 4 +- .../networking/v1/servicecidrspec.go | 2 +- .../networking/v1beta1/ingress.go | 4 +- .../networking/v1beta1/ingressclass.go | 4 +- .../networking/v1beta1/ingressrule.go | 2 +- .../networking/v1beta1/ingressrulevalue.go | 1 + .../networking/v1beta1/ipaddress.go | 4 +- .../networking/v1beta1/ipaddressspec.go | 2 +- .../networking/v1beta1/parentreference.go | 8 +- .../networking/v1beta1/servicecidr.go | 4 +- .../networking/v1beta1/servicecidrspec.go | 2 +- .../node/v1/runtimeclass.go | 3 +- .../node/v1alpha1/runtimeclass.go | 3 +- .../node/v1beta1/runtimeclass.go | 3 +- .../applyconfigurations/policy/v1/eviction.go | 6 +- .../policy/v1/poddisruptionbudget.go | 8 +- .../policy/v1/poddisruptionbudgetspec.go | 8 +- .../policy/v1beta1/eviction.go | 6 +- .../policy/v1beta1/poddisruptionbudget.go | 8 +- .../policy/v1beta1/poddisruptionbudgetspec.go | 8 +- .../rbac/v1/aggregationrule.go | 2 +- .../rbac/v1/clusterrole.go | 8 +- .../rbac/v1/clusterrolebinding.go | 8 +- .../applyconfigurations/rbac/v1/policyrule.go | 10 +- .../applyconfigurations/rbac/v1/role.go | 6 +- .../rbac/v1/rolebinding.go | 8 +- .../applyconfigurations/rbac/v1/roleref.go | 6 +- .../applyconfigurations/rbac/v1/subject.go | 8 +- .../rbac/v1alpha1/aggregationrule.go | 2 +- .../rbac/v1alpha1/clusterrole.go | 8 +- .../rbac/v1alpha1/clusterrolebinding.go | 8 +- .../rbac/v1alpha1/policyrule.go | 10 +- .../applyconfigurations/rbac/v1alpha1/role.go | 6 +- .../rbac/v1alpha1/rolebinding.go | 8 +- .../rbac/v1alpha1/roleref.go | 6 +- .../rbac/v1alpha1/subject.go | 8 +- .../rbac/v1beta1/aggregationrule.go | 2 +- .../rbac/v1beta1/clusterrole.go | 8 +- .../rbac/v1beta1/clusterrolebinding.go | 8 +- .../rbac/v1beta1/policyrule.go | 10 +- .../applyconfigurations/rbac/v1beta1/role.go | 6 +- .../rbac/v1beta1/rolebinding.go | 8 +- .../rbac/v1beta1/roleref.go | 6 +- .../rbac/v1beta1/subject.go | 8 +- .../resource/v1/capacityrequestpolicyrange.go | 7 + .../resource/v1/celdeviceselector.go | 11 +- .../applyconfigurations/resource/v1/device.go | 18 +- .../v1/deviceallocationconfiguration.go | 2 +- .../resource/v1/deviceclaimconfiguration.go | 2 +- .../resource/v1/deviceclass.go | 2 +- .../resource/v1/deviceclassconfiguration.go | 2 +- .../resource/v1/deviceclassspec.go | 2 - .../resource/v1/devicecounterconsumption.go | 30 + .../resource/v1/devicederivedattribute.go | 95 + .../v1/devicerequestallocationresult.go | 16 + .../resource/v1/devicesubrequest.go | 34 + .../resource/v1/devicetaintrule.go | 294 + .../resource/v1/devicetaintrulespec.go | 55 + .../resource/v1/devicetaintrulestatus.go | 70 + .../resource/v1/devicetaintselector.go | 76 + .../resource/v1/exactdevicerequest.go | 34 + .../resource/v1/nodeallocatablemapping.go | 90 + .../resource/v1/nodeallocatableoverhead.go | 67 + .../resource/v1/nodeallocatableresource.go | 65 + .../v1/nodeallocatableresourcemapping.go | 84 - .../resource/v1/resourceclaim.go | 2 +- .../resource/v1/resourceclaimtemplate.go | 2 +- .../resource/v1/resourcepool.go | 2 + .../resource/v1/resourceslice.go | 2 +- .../resource/v1/resourceslicespec.go | 41 + .../resource/v1alpha3/devicetaintrule.go | 2 +- .../resource/v1alpha3/partitiontypestatus.go | 77 + .../resource/v1alpha3/poolstatus.go | 34 + .../v1alpha3/resourcepoolstatusrequest.go | 2 +- .../v1alpha3/resourcepoolstatusrequestspec.go | 21 + .../v1alpha3/shareablecapacitystatus.go | 77 + .../v1alpha3/shareablesummarystatus.go | 71 + .../resource/v1beta1/basicdevice.go | 18 +- .../v1beta1/capacityrequestpolicyrange.go | 7 + .../resource/v1beta1/celdeviceselector.go | 11 +- .../v1beta1/deviceallocationconfiguration.go | 2 +- .../v1beta1/deviceclaimconfiguration.go | 2 +- .../resource/v1beta1/deviceclass.go | 2 +- .../v1beta1/deviceclassconfiguration.go | 2 +- .../resource/v1beta1/deviceclassspec.go | 2 - .../v1beta1/devicecounterconsumption.go | 30 + .../v1beta1/devicederivedattribute.go | 95 + .../resource/v1beta1/devicerequest.go | 34 + .../v1beta1/devicerequestallocationresult.go | 16 + .../resource/v1beta1/devicesubrequest.go | 34 + .../v1beta1/nodeallocatablemapping.go | 90 + .../v1beta1/nodeallocatableoverhead.go | 67 + .../v1beta1/nodeallocatableresource.go | 65 + .../v1beta1/nodeallocatableresourcemapping.go | 84 - .../resource/v1beta1/resourceclaim.go | 2 +- .../resource/v1beta1/resourceclaimtemplate.go | 2 +- .../resource/v1beta1/resourcepool.go | 2 + .../resource/v1beta1/resourceslice.go | 2 +- .../resource/v1beta1/resourceslicespec.go | 41 + .../v1beta2/capacityrequestpolicyrange.go | 7 + .../resource/v1beta2/celdeviceselector.go | 11 +- .../resource/v1beta2/device.go | 18 +- .../v1beta2/deviceallocationconfiguration.go | 2 +- .../v1beta2/deviceclaimconfiguration.go | 2 +- .../resource/v1beta2/deviceclass.go | 2 +- .../v1beta2/deviceclassconfiguration.go | 2 +- .../resource/v1beta2/deviceclassspec.go | 2 - .../v1beta2/devicecounterconsumption.go | 30 + .../v1beta2/devicederivedattribute.go | 95 + .../v1beta2/devicerequestallocationresult.go | 16 + .../resource/v1beta2/devicesubrequest.go | 34 + .../resource/v1beta2/devicetaintrule.go | 2 +- .../resource/v1beta2/exactdevicerequest.go | 34 + .../v1beta2/nodeallocatablemapping.go | 90 + .../v1beta2/nodeallocatableoverhead.go | 67 + .../v1beta2/nodeallocatableresource.go | 65 + .../v1beta2/nodeallocatableresourcemapping.go | 84 - .../resource/v1beta2/resourceclaim.go | 2 +- .../resource/v1beta2/resourceclaimtemplate.go | 2 +- .../resource/v1beta2/resourcepool.go | 2 + .../resource/v1beta2/resourceslice.go | 2 +- .../resource/v1beta2/resourceslicespec.go | 41 + .../scheduling/v1/priorityclass.go | 4 +- .../v1alpha2/podgrouptemplatereference.go | 44 - .../workloadpodgrouptemplatereference.go | 52 - .../v1alpha3/compositedisruptionmode.go | 57 + .../v1alpha3/compositegangschedulingpolicy.go | 45 + .../scheduling/v1alpha3/compositepodgroup.go | 296 + .../compositepodgroupschedulingconstraints.go | 48 + .../compositepodgroupschedulingpolicy.go | 59 + .../v1alpha3/compositepodgroupspec.go | 144 + .../v1alpha3/compositepodgroupstatus.go | 72 + .../v1alpha3/compositepodgrouptemplate.go | 157 + .../scheduling/v1alpha3/disruptionmode.go | 57 + .../v1alpha3/gangschedulingpolicy.go | 52 + .../{v1alpha2 => v1alpha3}/podgroup.go | 24 +- .../podgroupresourceclaim.go | 8 +- .../podgroupresourceclaimstatus.go | 6 +- .../podgroupschedulingconstraints.go | 4 +- .../podgroupschedulingpolicy.go | 23 +- .../scheduling/v1alpha3/podgroupspec.go | 168 + .../scheduling/v1alpha3/podgroupstatus.go | 83 + .../scheduling/v1alpha3/podgrouptemplate.go | 143 + .../topologyconstraint.go | 4 +- .../typedlocalobjectreference.go | 8 +- .../{v1alpha2 => v1alpha3}/workload.go | 20 +- .../workloadpodgroupdisruptionmode.go | 78 + .../workloadpodgroupgangschedulingpolicy.go | 48 + .../v1alpha3/workloadpodgroupresourceclaim.go | 98 + .../workloadpodgroupschedulingconstraints.go | 70 + .../workloadpodgroupschedulingpolicy.go | 84 + .../scheduling/v1alpha3/workloadreference.go | 58 + .../scheduling/v1alpha3/workloadspec.go | 82 + .../v1beta1/compositedisruptionmode.go | 57 + .../v1beta1/compositegangschedulingpolicy.go | 45 + .../compositepodgroupschedulingconstraints.go | 48 + .../compositepodgroupschedulingpolicy.go | 59 + .../v1beta1/compositepodgrouptemplate.go | 157 + .../scheduling/v1beta1/disruptionmode.go | 57 + .../gangschedulingpolicy.go | 14 +- .../scheduling/v1beta1/podgroup.go | 296 + .../v1beta1/podgroupresourceclaim.go | 89 + .../v1beta1/podgroupresourceclaimstatus.go | 59 + .../v1beta1/podgroupschedulingconstraints.go | 48 + .../v1beta1/podgroupschedulingpolicy.go | 64 + .../{v1alpha2 => v1beta1}/podgroupspec.go | 77 +- .../{v1alpha2 => v1beta1}/podgroupstatus.go | 12 +- .../{v1alpha2 => v1beta1}/podgrouptemplate.go | 59 +- .../scheduling/v1beta1/priorityclass.go | 4 +- .../scheduling/v1beta1/topologyconstraint.go | 45 + .../v1beta1/typedlocalobjectreference.go | 67 + .../scheduling/v1beta1/workload.go | 280 + .../scheduling/v1beta1/workloadreference.go | 58 + .../{v1alpha2 => v1beta1}/workloadspec.go | 29 +- .../storage/v1/csidriver.go | 4 +- .../storage/v1/csidriverspec.go | 4 +- .../applyconfigurations/storage/v1/csinode.go | 20 +- .../storage/v1/csinodestatus.go | 47 + .../storage/v1/csistoragecapacity.go | 4 +- .../storage/v1/storageclass.go | 4 +- .../storage/v1/storagehealth.go | 58 + .../storage/v1/storagehealthcondition.go | 102 + .../storage/v1/volumeattachment.go | 4 +- .../storage/v1/volumeattributesclass.go | 6 +- .../storage/v1alpha1/csistoragecapacity.go | 4 +- .../storage/v1alpha1/volumeattachment.go | 4 +- .../storage/v1alpha1/volumeattributesclass.go | 6 +- .../storage/v1beta1/csidriver.go | 4 +- .../storage/v1beta1/csidriverspec.go | 4 +- .../storage/v1beta1/csinode.go | 19 +- .../storage/v1beta1/csinodestatus.go | 47 + .../storage/v1beta1/csistoragecapacity.go | 4 +- .../storage/v1beta1/storageclass.go | 4 +- .../storage/v1beta1/storagehealth.go | 58 + .../storage/v1beta1/storagehealthcondition.go | 102 + .../storage/v1beta1/volumeattachment.go | 4 +- .../storage/v1beta1/volumeattributesclass.go | 6 +- .../v1/storageversionmigration.go | 292 + .../v1/storageversionmigrationspec.go | 48 + .../v1/storageversionmigrationstatus.go | 63 + .../v1beta1/storageversionmigration.go | 2 +- .../discovery/aggregated_discovery.go | 122 - .../client-go/discovery/discovery_client.go | 620 +- .../k8s.io/client-go/discovery/helper.go | 2 +- .../vendor/k8s.io/client-go/dynamic/simple.go | 3 +- .../admissionregistration/v1/interface.go | 36 +- .../v1/mutatingadmissionpolicy.go | 104 +- .../v1/mutatingadmissionpolicybinding.go | 104 +- .../v1/mutatingwebhookconfiguration.go | 104 +- .../v1/validatingadmissionpolicy.go | 104 +- .../v1/validatingadmissionpolicybinding.go | 104 +- .../v1/validatingwebhookconfiguration.go | 104 +- .../v1alpha1/interface.go | 24 +- .../v1alpha1/mutatingadmissionpolicy.go | 104 +- .../mutatingadmissionpolicybinding.go | 104 +- .../v1alpha1/validatingadmissionpolicy.go | 104 +- .../validatingadmissionpolicybinding.go | 104 +- .../v1beta1/interface.go | 36 +- .../v1beta1/mutatingadmissionpolicy.go | 104 +- .../v1beta1/mutatingadmissionpolicybinding.go | 104 +- .../v1beta1/mutatingwebhookconfiguration.go | 104 +- .../v1beta1/validatingadmissionpolicy.go | 104 +- .../validatingadmissionpolicybinding.go | 104 +- .../v1beta1/validatingwebhookconfiguration.go | 104 +- .../apiserverinternal/v1alpha1/interface.go | 6 +- .../v1alpha1/storageversion.go | 104 +- .../informers/apps/v1/controllerrevision.go | 104 +- .../client-go/informers/apps/v1/daemonset.go | 104 +- .../client-go/informers/apps/v1/deployment.go | 104 +- .../client-go/informers/apps/v1/interface.go | 30 +- .../client-go/informers/apps/v1/replicaset.go | 104 +- .../informers/apps/v1/statefulset.go | 104 +- .../apps/v1beta1/controllerrevision.go | 104 +- .../informers/apps/v1beta1/deployment.go | 104 +- .../informers/apps/v1beta1/interface.go | 18 +- .../informers/apps/v1beta1/statefulset.go | 104 +- .../apps/v1beta2/controllerrevision.go | 104 +- .../informers/apps/v1beta2/daemonset.go | 104 +- .../informers/apps/v1beta2/deployment.go | 104 +- .../informers/apps/v1beta2/interface.go | 30 +- .../informers/apps/v1beta2/replicaset.go | 104 +- .../informers/apps/v1beta2/statefulset.go | 104 +- .../autoscaling/v1/horizontalpodautoscaler.go | 104 +- .../informers/autoscaling/v1/interface.go | 6 +- .../autoscaling/v2/horizontalpodautoscaler.go | 104 +- .../informers/autoscaling/v2/interface.go | 6 +- .../client-go/informers/batch/v1/cronjob.go | 104 +- .../client-go/informers/batch/v1/interface.go | 12 +- .../client-go/informers/batch/v1/job.go | 104 +- .../informers/batch/v1beta1/cronjob.go | 104 +- .../informers/batch/v1beta1/interface.go | 6 +- .../v1/certificatesigningrequest.go | 104 +- .../certificates/v1/clustertrustbundle.go | 207 + .../informers/certificates/v1/interface.go | 20 +- .../certificates/v1/podcertificaterequest.go | 208 + .../v1alpha1/clustertrustbundle.go | 104 +- .../certificates/v1alpha1/interface.go | 6 +- .../v1beta1/certificatesigningrequest.go | 104 +- .../v1beta1/clustertrustbundle.go | 104 +- .../certificates/v1beta1/interface.go | 18 +- .../v1beta1/podcertificaterequest.go | 104 +- .../informers/coordination/v1/interface.go | 6 +- .../informers/coordination/v1/lease.go | 104 +- .../coordination/v1alpha2/interface.go | 6 +- .../coordination/v1alpha2/leasecandidate.go | 104 +- .../coordination/v1beta1/interface.go | 12 +- .../informers/coordination/v1beta1/lease.go | 104 +- .../coordination/v1beta1/leasecandidate.go | 104 +- .../informers/core/v1/componentstatus.go | 104 +- .../client-go/informers/core/v1/configmap.go | 104 +- .../client-go/informers/core/v1/endpoints.go | 104 +- .../client-go/informers/core/v1/event.go | 104 +- .../client-go/informers/core/v1/interface.go | 96 +- .../client-go/informers/core/v1/limitrange.go | 104 +- .../client-go/informers/core/v1/namespace.go | 104 +- .../client-go/informers/core/v1/node.go | 104 +- .../informers/core/v1/persistentvolume.go | 104 +- .../core/v1/persistentvolumeclaim.go | 104 +- .../k8s.io/client-go/informers/core/v1/pod.go | 104 +- .../informers/core/v1/podtemplate.go | 104 +- .../core/v1/replicationcontroller.go | 104 +- .../informers/core/v1/resourcequota.go | 104 +- .../client-go/informers/core/v1/secret.go | 104 +- .../client-go/informers/core/v1/service.go | 104 +- .../informers/core/v1/serviceaccount.go | 104 +- .../informers/discovery/v1/endpointslice.go | 104 +- .../informers/discovery/v1/interface.go | 6 +- .../discovery/v1beta1/endpointslice.go | 104 +- .../informers/discovery/v1beta1/interface.go | 6 +- .../client-go/informers/events/v1/event.go | 104 +- .../informers/events/v1/interface.go | 6 +- .../informers/events/v1beta1/event.go | 104 +- .../informers/events/v1beta1/interface.go | 6 +- .../informers/extensions/v1beta1/daemonset.go | 104 +- .../extensions/v1beta1/deployment.go | 104 +- .../informers/extensions/v1beta1/ingress.go | 104 +- .../informers/extensions/v1beta1/interface.go | 30 +- .../extensions/v1beta1/networkpolicy.go | 104 +- .../extensions/v1beta1/replicaset.go | 104 +- .../k8s.io/client-go/informers/factory.go | 10 +- .../informers/flowcontrol/v1/flowschema.go | 104 +- .../informers/flowcontrol/v1/interface.go | 12 +- .../v1/prioritylevelconfiguration.go | 104 +- .../flowcontrol/v1beta1/flowschema.go | 104 +- .../flowcontrol/v1beta1/interface.go | 12 +- .../v1beta1/prioritylevelconfiguration.go | 104 +- .../flowcontrol/v1beta2/flowschema.go | 104 +- .../flowcontrol/v1beta2/interface.go | 12 +- .../v1beta2/prioritylevelconfiguration.go | 104 +- .../flowcontrol/v1beta3/flowschema.go | 104 +- .../flowcontrol/v1beta3/interface.go | 12 +- .../v1beta3/prioritylevelconfiguration.go | 104 +- .../k8s.io/client-go/informers/generic.go | 36 +- .../informers/lifecycle/interface.go | 46 + .../informers/lifecycle/v1alpha1/eviction.go | 208 + .../lifecycle/v1alpha1/evictionrequest.go | 208 + .../informers/lifecycle/v1alpha1/interface.go | 52 + .../informers/networking/v1/ingress.go | 104 +- .../informers/networking/v1/ingressclass.go | 104 +- .../informers/networking/v1/interface.go | 30 +- .../informers/networking/v1/ipaddress.go | 104 +- .../informers/networking/v1/networkpolicy.go | 104 +- .../informers/networking/v1/servicecidr.go | 104 +- .../informers/networking/v1beta1/ingress.go | 104 +- .../networking/v1beta1/ingressclass.go | 104 +- .../informers/networking/v1beta1/interface.go | 24 +- .../informers/networking/v1beta1/ipaddress.go | 104 +- .../networking/v1beta1/servicecidr.go | 104 +- .../client-go/informers/node/v1/interface.go | 6 +- .../informers/node/v1/runtimeclass.go | 104 +- .../informers/node/v1alpha1/interface.go | 6 +- .../informers/node/v1alpha1/runtimeclass.go | 104 +- .../informers/node/v1beta1/interface.go | 6 +- .../informers/node/v1beta1/runtimeclass.go | 104 +- .../informers/policy/v1/interface.go | 6 +- .../policy/v1/poddisruptionbudget.go | 104 +- .../informers/policy/v1beta1/interface.go | 6 +- .../policy/v1beta1/poddisruptionbudget.go | 104 +- .../informers/rbac/v1/clusterrole.go | 104 +- .../informers/rbac/v1/clusterrolebinding.go | 104 +- .../client-go/informers/rbac/v1/interface.go | 24 +- .../client-go/informers/rbac/v1/role.go | 104 +- .../informers/rbac/v1/rolebinding.go | 104 +- .../informers/rbac/v1alpha1/clusterrole.go | 104 +- .../rbac/v1alpha1/clusterrolebinding.go | 104 +- .../informers/rbac/v1alpha1/interface.go | 24 +- .../client-go/informers/rbac/v1alpha1/role.go | 104 +- .../informers/rbac/v1alpha1/rolebinding.go | 104 +- .../informers/rbac/v1beta1/clusterrole.go | 104 +- .../rbac/v1beta1/clusterrolebinding.go | 104 +- .../informers/rbac/v1beta1/interface.go | 24 +- .../client-go/informers/rbac/v1beta1/role.go | 104 +- .../informers/rbac/v1beta1/rolebinding.go | 104 +- .../informers/resource/v1/deviceclass.go | 104 +- .../informers/resource/v1/devicetaintrule.go | 207 + .../informers/resource/v1/interface.go | 31 +- .../informers/resource/v1/resourceclaim.go | 104 +- .../resource/v1/resourceclaimtemplate.go | 104 +- .../informers/resource/v1/resourceslice.go | 104 +- .../resource/v1alpha3/devicetaintrule.go | 104 +- .../informers/resource/v1alpha3/interface.go | 12 +- .../v1alpha3/resourcepoolstatusrequest.go | 104 +- .../informers/resource/v1beta1/deviceclass.go | 104 +- .../informers/resource/v1beta1/interface.go | 24 +- .../resource/v1beta1/resourceclaim.go | 104 +- .../resource/v1beta1/resourceclaimtemplate.go | 104 +- .../resource/v1beta1/resourceslice.go | 104 +- .../informers/resource/v1beta2/deviceclass.go | 104 +- .../resource/v1beta2/devicetaintrule.go | 104 +- .../informers/resource/v1beta2/interface.go | 30 +- .../resource/v1beta2/resourceclaim.go | 104 +- .../resource/v1beta2/resourceclaimtemplate.go | 104 +- .../resource/v1beta2/resourceslice.go | 104 +- .../informers/scheduling/interface.go | 12 +- .../informers/scheduling/v1/interface.go | 6 +- .../informers/scheduling/v1/priorityclass.go | 104 +- .../informers/scheduling/v1alpha2/podgroup.go | 116 - .../informers/scheduling/v1alpha2/workload.go | 116 - .../scheduling/v1alpha3/compositepodgroup.go | 208 + .../{v1alpha2 => v1alpha3}/interface.go | 21 +- .../informers/scheduling/v1alpha3/podgroup.go | 208 + .../informers/scheduling/v1alpha3/workload.go | 208 + .../informers/scheduling/v1beta1/interface.go | 20 +- .../informers/scheduling/v1beta1/podgroup.go | 208 + .../scheduling/v1beta1/priorityclass.go | 104 +- .../informers/scheduling/v1beta1/workload.go | 208 + .../informers/storage/v1/csidriver.go | 104 +- .../client-go/informers/storage/v1/csinode.go | 104 +- .../storage/v1/csistoragecapacity.go | 104 +- .../informers/storage/v1/interface.go | 36 +- .../informers/storage/v1/storageclass.go | 104 +- .../informers/storage/v1/volumeattachment.go | 104 +- .../storage/v1/volumeattributesclass.go | 104 +- .../storage/v1alpha1/csistoragecapacity.go | 104 +- .../informers/storage/v1alpha1/interface.go | 18 +- .../storage/v1alpha1/volumeattachment.go | 104 +- .../storage/v1alpha1/volumeattributesclass.go | 104 +- .../informers/storage/v1beta1/csidriver.go | 104 +- .../informers/storage/v1beta1/csinode.go | 104 +- .../storage/v1beta1/csistoragecapacity.go | 104 +- .../informers/storage/v1beta1/interface.go | 36 +- .../informers/storage/v1beta1/storageclass.go | 104 +- .../storage/v1beta1/volumeattachment.go | 104 +- .../storage/v1beta1/volumeattributesclass.go | 104 +- .../informers/storagemigration/interface.go | 8 + .../storagemigration/v1/interface.go | 45 + .../v1/storageversionmigration.go | 207 + .../storagemigration/v1beta1/interface.go | 6 +- .../v1beta1/storageversionmigration.go | 104 +- .../k8s.io/client-go/kubernetes/clientset.go | 46 +- .../client-go/kubernetes/scheme/register.go | 8 +- .../certificates/v1/certificates_client.go | 10 + .../certificates/v1/clustertrustbundle.go | 71 + .../certificates/v1/generated_expansion.go | 4 + .../certificates/v1/podcertificaterequest.go | 75 + .../v1alpha2 => lifecycle/v1alpha1}/doc.go | 2 +- .../typed/lifecycle/v1alpha1/eviction.go | 75 + .../lifecycle/v1alpha1/evictionrequest.go | 75 + .../lifecycle/v1alpha1/generated_expansion.go | 23 + .../lifecycle/v1alpha1/lifecycle_client.go | 106 + .../typed/resource/v1/devicetaintrule.go | 75 + .../typed/resource/v1/generated_expansion.go | 2 + .../typed/resource/v1/resource_client.go | 5 + .../scheduling/v1alpha3/compositepodgroup.go | 75 + .../typed/scheduling/v1alpha3/doc.go | 20 + .../generated_expansion.go | 4 +- .../{v1alpha2 => v1alpha3}/podgroup.go | 34 +- .../scheduling_client.go | 43 +- .../{v1alpha2 => v1alpha3}/workload.go | 30 +- .../scheduling/v1beta1/generated_expansion.go | 4 + .../typed/scheduling/v1beta1/podgroup.go | 75 + .../scheduling/v1beta1/scheduling_client.go | 10 + .../typed/scheduling/v1beta1/workload.go | 71 + .../kubernetes/typed/storage/v1/csinode.go | 4 + .../typed/storage/v1beta1/csinode.go | 4 + .../typed/storagemigration/v1/doc.go | 20 + .../v1/generated_expansion.go} | 10 +- .../v1/storagemigration_client.go | 101 + .../v1/storageversionmigration.go | 79 + .../certificates/v1/clustertrustbundle.go | 48 + .../certificates/v1/expansion_generated.go | 12 + .../certificates/v1/podcertificaterequest.go | 70 + .../listers/lifecycle/v1alpha1/eviction.go | 70 + .../lifecycle/v1alpha1/evictionrequest.go | 70 + .../lifecycle/v1alpha1/expansion_generated.go | 35 + .../listers/resource/v1/devicetaintrule.go | 48 + .../resource/v1/expansion_generated.go | 4 + .../scheduling/v1alpha3/compositepodgroup.go | 70 + .../expansion_generated.go | 10 +- .../{v1alpha2 => v1alpha3}/podgroup.go | 18 +- .../{v1alpha2 => v1alpha3}/workload.go | 18 +- .../scheduling/v1beta1/expansion_generated.go | 16 + .../listers/scheduling/v1beta1/podgroup.go | 70 + .../listers/scheduling/v1beta1/workload.go | 70 + .../v1/expansion_generated.go | 23 + .../v1/storageversionmigration.go | 48 + .../vendor/k8s.io/client-go/openapi/OWNERS | 3 + .../vendor/k8s.io/client-go/openapi/client.go | 60 +- .../k8s.io/client-go/openapi/groupversion.go | 46 +- .../pkg/apis/clientauthentication/v1/types.go | 2 +- .../v1/zz_generated.conversion.go | 11 +- .../clientauthentication/v1beta1/types.go | 2 +- .../v1beta1/zz_generated.conversion.go | 11 +- .../plugin/pkg/client/auth/exec/exec.go | 1 + .../vendor/k8s.io/client-go/rest/OWNERS | 1 - .../vendor/k8s.io/client-go/rest/client.go | 3 + .../vendor/k8s.io/client-go/rest/config.go | 3 + .../vendor/k8s.io/client-go/rest/request.go | 4 +- .../vendor/k8s.io/client-go/rest/transport.go | 2 + .../restmapper/category_expansion.go | 105 +- .../k8s.io/client-go/restmapper/discovery.go | 241 +- .../k8s.io/client-go/restmapper/shortcut.go | 115 +- .../k8s.io/client-go/tools/cache/OWNERS | 4 +- .../client-go/tools/cache/controller.go | 216 + .../k8s.io/client-go/tools/cache/index.go | 34 + .../{fifo_metrics.go => informer_metrics.go} | 2 +- .../client-go/tools/cache/mutation_cache.go | 252 +- .../k8s.io/client-go/tools/cache/reflector.go | 2 +- .../client-go/tools/cache/shared_informer.go | 157 +- .../k8s.io/client-go/tools/cache/store.go | 3 + .../client-go/tools/clientcmd/api/v1/doc.go | 1 + .../api/v1/zz_generated.conversion.go | 12 +- .../client-go/tools/clientcmd/loader.go | 9 +- .../client-go/tools/leaderelection/OWNERS | 3 +- .../tools/leaderelection/leaderelection.go | 20 +- .../leaderelection/resourcelock/multilock.go | 7 +- .../k8s.io/client-go/tools/metrics/metrics.go | 43 +- .../k8s.io/client-go/tools/pager/pager.go | 2 +- .../vendor/k8s.io/client-go/transport/OWNERS | 1 - .../k8s.io/client-go/transport/transport.go | 2 + .../data_consistency_detector.go | 17 +- .../vendor/k8s.io/client-go/util/retry/OWNERS | 4 - .../k8s.io/client-go/util/retry/util.go | 2 +- .../metrics/api/v1/zz_generated.model_name.go | 27 + .../k8s.io/component-base/tracing/utils.go | 6 +- .../k8s.io/component-base/version/base.go | 2 +- .../pkg/internal/serialization.go | 2 +- .../go-json-experiment/json/README.md | 246 +- .../go-json-experiment/json/arshal.go | 521 +- .../go-json-experiment/json/arshal_any.go | 281 +- .../go-json-experiment/json/arshal_default.go | 1467 ++- .../go-json-experiment/json/arshal_funcs.go | 207 +- .../go-json-experiment/json/arshal_inlined.go | 121 +- .../go-json-experiment/json/arshal_methods.go | 326 +- .../go-json-experiment/json/arshal_time.go | 844 +- .../go-json-experiment/json/decode.go | 1655 --- .../go-json-experiment/json/doc.go | 226 +- .../go-json-experiment/json/encode.go | 1170 --- .../go-json-experiment/json/errors.go | 407 +- .../go-json-experiment/json/fields.go | 501 +- .../go-json-experiment/json/intern.go | 6 +- .../json/internal/internal.go | 40 + .../json/internal/jsonflags/flags.go | 213 + .../json/internal/jsonopts/options.go | 200 + .../json/internal/jsonwire/decode.go | 627 ++ .../json/internal/jsonwire/encode.go | 288 + .../json/internal/jsonwire/wire.go | 215 + .../json/jsontext/decode.go | 1177 +++ .../go-json-experiment/json/jsontext/doc.go | 109 + .../json/jsontext/encode.go | 975 ++ .../json/jsontext/errors.go | 180 + .../json/jsontext/export.go | 75 + .../json/jsontext/options.go | 302 + .../json/{ => jsontext}/pools.go | 90 +- .../go-json-experiment/json/jsontext/quote.go | 39 + .../json/{ => jsontext}/state.go | 445 +- .../json/{ => jsontext}/token.go | 85 +- .../go-json-experiment/json/jsontext/value.go | 393 + .../go-json-experiment/json/migrate.sh | 48 + .../go-json-experiment/json/options.go | 287 + .../go-json-experiment/json/value.go | 381 - .../kube-openapi/pkg/schemaconv/openapi.go | 11 +- .../pkg/schemaconv/proto_models.go | 10 +- .../k8s.io/kube-openapi/pkg/spec3/encoding.go | 13 +- .../k8s.io/kube-openapi/pkg/spec3/example.go | 13 +- .../pkg/spec3/external_documentation.go | 13 +- .../k8s.io/kube-openapi/pkg/spec3/header.go | 13 +- .../kube-openapi/pkg/spec3/media_type.go | 13 +- .../kube-openapi/pkg/spec3/operation.go | 13 +- .../kube-openapi/pkg/spec3/parameter.go | 13 +- .../k8s.io/kube-openapi/pkg/spec3/path.go | 25 +- .../kube-openapi/pkg/spec3/request_body.go | 13 +- .../k8s.io/kube-openapi/pkg/spec3/response.go | 47 +- .../kube-openapi/pkg/spec3/security_scheme.go | 7 +- .../k8s.io/kube-openapi/pkg/spec3/server.go | 25 +- .../k8s.io/kube-openapi/pkg/spec3/spec.go | 5 +- .../pkg/validation/spec/header.go | 13 +- .../kube-openapi/pkg/validation/spec/info.go | 13 +- .../kube-openapi/pkg/validation/spec/items.go | 13 +- .../pkg/validation/spec/operation.go | 13 +- .../pkg/validation/spec/parameter.go | 13 +- .../pkg/validation/spec/path_item.go | 15 +- .../kube-openapi/pkg/validation/spec/paths.go | 11 +- .../pkg/validation/spec/response.go | 15 +- .../pkg/validation/spec/responses.go | 17 +- .../pkg/validation/spec/schema.go | 13 +- .../pkg/validation/spec/security_scheme.go | 13 +- .../pkg/validation/spec/swagger.go | 59 +- .../kube-openapi/pkg/validation/spec/tag.go | 13 +- .../pkg/validation/validate/result.go | 4 +- constraint/vendor/k8s.io/utils/ptr/OWNERS | 2 + constraint/vendor/k8s.io/utils/ptr/ptr.go | 2 +- constraint/vendor/modules.txt | 126 +- .../pkg/cache/cacheapi/cacheapi.go | 153 + .../controller-runtime/pkg/client/client.go | 87 +- .../pkg/client/config/config.go | 6 +- .../pkg/client/consistency.go | 494 + .../pkg/client/interfaces.go | 15 +- .../consistencyhandler/consistencyhandler.go | 345 + .../internal/writebarrier/writebarrier.go | 195 + .../pkg/client/metadata_client.go | 18 - .../controller-runtime/pkg/client/object.go | 7 +- .../controller-runtime/pkg/client/options.go | 124 + .../pkg/client/typed_client.go | 25 +- .../pkg/client/unstructured_client.go | 15 +- .../controller-runtime/pkg/client/watch.go | 17 +- .../controller-runtime/pkg/envtest/webhook.go | 3 + .../pkg/internal/testing/process/process.go | 8 +- .../internal/testing/process/signal_other.go | 4 +- .../internal/testing/process/signal_unix.go | 2 +- .../testing/process/signal_windows.go | 28 + .../pkg/metrics/client_go_adapter.go | 270 +- .../pkg/metrics/leaderelection.go | 16 + .../v6/fieldpath/element.go | 28 +- .../v6/fieldpath/pathelementmap.go | 25 +- .../v6/fieldpath/serialize-pe.go | 18 +- .../v6/fieldpath/serialize.go | 11 + .../structured-merge-diff/v6/fieldpath/set.go | 24 +- .../v6/schema/elements.go | 4 + .../structured-merge-diff/v6/schema/equals.go | 3 + .../v6/schema/schemaschema.go | 3 + .../v6/value/allocator.go | 80 +- .../v6/value/jsontagutil.go | 7 +- .../v6/value/reflectcache.go | 77 +- .../structured-merge-diff/v6/value/value.go | 5 + 1275 files changed, 119729 insertions(+), 45981 deletions(-) create mode 100644 constraint/vendor/github.com/fxamacker/cbor/v2/decode_map_utils.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/NOTICE create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/SECURITY.md create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/errors.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/ifaces.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/ifaces.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonpointer/options.go create mode 100644 constraint/vendor/github.com/go-openapi/jsonreference/.editorconfig create mode 100644 constraint/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md create mode 100644 constraint/vendor/github.com/go-openapi/jsonreference/NOTICE create mode 100644 constraint/vendor/github.com/go-openapi/jsonreference/SECURITY.md create mode 100644 constraint/vendor/github.com/go-openapi/swag/.codecov.yml create mode 100644 constraint/vendor/github.com/go-openapi/swag/.mockery.yml create mode 100644 constraint/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md create mode 100644 constraint/vendor/github.com/go-openapi/swag/SECURITY.md create mode 100644 constraint/vendor/github.com/go-openapi/swag/cmdutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/cmdutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/cmdutils_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/convert.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/convert_types.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/format.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/sizeof.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv/type_constraints.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/conv_iface.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/convert.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/convert_types.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/file.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/fileutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/fileutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/fileutils/file.go rename constraint/vendor/github.com/go-openapi/swag/{ => fileutils}/path.go (58%) create mode 100644 constraint/vendor/github.com/go-openapi/swag/fileutils_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/go.work create mode 100644 constraint/vendor/github.com/go-openapi/swag/go.work.sum delete mode 100644 constraint/vendor/github.com/go-openapi/swag/initialism_index.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/json.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonname_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/README.md create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/concat.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/json.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/jsonutils_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/errors.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/json.go rename constraint/vendor/github.com/go-openapi/swag/{ => loading}/loading.go (53%) create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/options.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading/yaml.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/loading_iface.go rename constraint/vendor/github.com/go-openapi/swag/{ => mangling}/BENCHMARK.md (53%) create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/initialism_index.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/name_lexem.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/name_mangler.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/options.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/pools.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/split.go rename constraint/vendor/github.com/go-openapi/swag/{ => mangling}/string_bytes.go (60%) create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling/util.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/mangling_iface.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/name_lexem.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/net.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/netutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/netutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/netutils/net.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/netutils_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/README.md create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/debug.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/debug_off.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/debug_on.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/pools/pools.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/split.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/stringutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/stringutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/stringutils/strings.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/stringutils_iface.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/typeutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/typeutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/typeutils/types.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/typeutils_iface.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/util.go delete mode 100644 constraint/vendor/github.com/go-openapi/swag/yaml.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils/LICENSE create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils/doc.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils/errors.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils/yaml.go create mode 100644 constraint/vendor/github.com/go-openapi/swag/yamlutils_iface.go delete mode 100644 constraint/vendor/github.com/josharian/intern/README.md delete mode 100644 constraint/vendor/github.com/josharian/intern/intern.go delete mode 100644 constraint/vendor/github.com/josharian/intern/license.md delete mode 100644 constraint/vendor/github.com/mailru/easyjson/LICENSE delete mode 100644 constraint/vendor/github.com/mailru/easyjson/buffer/pool.go delete mode 100644 constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go delete mode 100644 constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go delete mode 100644 constraint/vendor/github.com/mailru/easyjson/jlexer/error.go delete mode 100644 constraint/vendor/github.com/mailru/easyjson/jlexer/lexer.go delete mode 100644 constraint/vendor/github.com/mailru/easyjson/jwriter/writer.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/README.md delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/doc.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/event.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/exception.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/http.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/resource.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/schema.go delete mode 100644 constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/trace.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/LICENSE delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/README.md delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/apic.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/decode.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/emitterc.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/encode.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/parserc.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/readerc.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/resolve.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/scannerc.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/sorter.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/writerc.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/yaml.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/yamlh.go delete mode 100644 constraint/vendor/gopkg.in/yaml.v3/yamlprivateh.go delete mode 100644 constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.pb.go delete mode 100644 constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.proto delete mode 100644 constraint/vendor/k8s.io/api/apidiscovery/v2beta1/types.go delete mode 100644 constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.deepcopy.go delete mode 100644 constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.prerelease-lifecycle.go delete mode 100644 constraint/vendor/k8s.io/api/extensions/v1beta1/zz_generated.validations.go rename constraint/vendor/k8s.io/api/{scheduling/v1alpha2 => lifecycle/v1alpha1}/doc.go (81%) rename constraint/vendor/k8s.io/api/{scheduling/v1alpha2 => lifecycle/v1alpha1}/generated.pb.go (61%) create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.proto create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/register.go create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types.go create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types_swagger_doc_generated.go create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.deepcopy.go create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.model_name.go create mode 100644 constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.prerelease-lifecycle.go create mode 100644 constraint/vendor/k8s.io/api/resource/v1/zz_generated.validations.go delete mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.proto delete mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha2/types.go delete mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha2/types_swagger_doc_generated.go delete mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.deepcopy.go delete mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.model_name.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/doc.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.pb.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.proto rename constraint/vendor/k8s.io/api/scheduling/{v1alpha2 => v1alpha3}/register.go (95%) create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/types.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/types_swagger_doc_generated.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.deepcopy.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.model_name.go create mode 100644 constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.validations.go rename constraint/vendor/k8s.io/api/{apidiscovery/v2beta1 => storagemigration/v1}/doc.go (81%) create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/generated.pb.go create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/generated.proto rename constraint/vendor/k8s.io/api/{apidiscovery/v2beta1 => storagemigration/v1}/register.go (77%) create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/types.go create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/types_swagger_doc_generated.go create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.deepcopy.go rename constraint/vendor/k8s.io/api/{apidiscovery/v2beta1 => storagemigration/v1}/zz_generated.model_name.go (57%) create mode 100644 constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.prerelease-lifecycle.go create mode 100644 constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/api/validate/dependentrequired.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/api/validate/errors.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/api/validate/monotonic.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/doc.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/zz_generated.validations.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_126.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_127.go create mode 100644 constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/collections.go create mode 100644 constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditions.go create mode 100644 constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsmap.go create mode 100644 constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsunion.go create mode 100644 constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/evaluate.go create mode 100644 constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesschemalesstyped.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobschedulingconfiguration.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundle.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundlespec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequest.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequestspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequeststatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/evictionresponder.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatablemappedresources.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableoverheadresources.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodepodpreemptionpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podvolumehealth.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthcondition.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/eviction.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionpodreference.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequest.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestpodreference.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequeststatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequesttarget.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictiontarget.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/requester.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/responderstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/targetresponder.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicederivedattribute.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrule.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulespec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulestatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintselector.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatablemapping.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableoverhead.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresource.go delete mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresourcemapping.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/partitiontypestatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablecapacitystatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablesummarystatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicederivedattribute.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatablemapping.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableoverhead.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresource.go delete mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresourcemapping.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicederivedattribute.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatablemapping.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableoverhead.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresource.go delete mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresourcemapping.go delete mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplatereference.go delete mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadpodgrouptemplatereference.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositedisruptionmode.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositegangschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingconstraints.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgrouptemplate.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/disruptionmode.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/gangschedulingpolicy.go rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/podgroup.go (95%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/podgroupresourceclaim.go (95%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/podgroupresourceclaimstatus.go (94%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/podgroupschedulingconstraints.go (96%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/podgroupschedulingpolicy.go (67%) create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgrouptemplate.go rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/topologyconstraint.go (95%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/typedlocalobjectreference.go (94%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1alpha3}/workload.go (96%) create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupdisruptionmode.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupgangschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupresourceclaim.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingconstraints.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadreference.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositedisruptionmode.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositegangschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingconstraints.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingpolicy.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgrouptemplate.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/disruptionmode.go rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1beta1}/gangschedulingpolicy.go (71%) create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaim.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaimstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingconstraints.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingpolicy.go rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1beta1}/podgroupspec.go (65%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1beta1}/podgroupstatus.go (87%) rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1beta1}/podgrouptemplate.go (76%) create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/topologyconstraint.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/typedlocalobjectreference.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadreference.go rename constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/{v1alpha2 => v1beta1}/workloadspec.go (63%) create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinodestatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealth.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealthcondition.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodestatus.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealth.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealthcondition.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigration.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationspec.go create mode 100644 constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationstatus.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/certificates/v1/clustertrustbundle.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/certificates/v1/podcertificaterequest.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/lifecycle/interface.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/eviction.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/evictionrequest.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/interface.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/resource/v1/devicetaintrule.go delete mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/podgroup.go delete mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/compositepodgroup.go rename constraint/vendor/k8s.io/client-go/informers/scheduling/{v1alpha2 => v1alpha3}/interface.go (70%) create mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/podgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/podgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/interface.go create mode 100644 constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/storageversionmigration.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/clustertrustbundle.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/podcertificaterequest.go rename constraint/vendor/k8s.io/client-go/kubernetes/typed/{scheduling/v1alpha2 => lifecycle/v1alpha1}/doc.go (97%) create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/eviction.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/evictionrequest.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/generated_expansion.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/lifecycle_client.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/devicetaintrule.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/compositepodgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/doc.go rename constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/{v1alpha2 => v1alpha3}/generated_expansion.go (91%) rename constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/{v1alpha2 => v1alpha3}/podgroup.go (59%) rename constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/{v1alpha2 => v1alpha3}/scheduling_client.go (65%) rename constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/{v1alpha2 => v1alpha3}/workload.go (62%) create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/podgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/doc.go rename constraint/vendor/{gopkg.in/yaml.v3/NOTICE => k8s.io/client-go/kubernetes/typed/storagemigration/v1/generated_expansion.go} (77%) create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storagemigration_client.go create mode 100644 constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storageversionmigration.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/certificates/v1/clustertrustbundle.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/certificates/v1/podcertificaterequest.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/eviction.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/evictionrequest.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/expansion_generated.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/resource/v1/devicetaintrule.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/compositepodgroup.go rename constraint/vendor/k8s.io/client-go/listers/scheduling/{v1alpha2 => v1alpha3}/expansion_generated.go (77%) rename constraint/vendor/k8s.io/client-go/listers/scheduling/{v1alpha2 => v1alpha3}/podgroup.go (80%) rename constraint/vendor/k8s.io/client-go/listers/scheduling/{v1alpha2 => v1alpha3}/workload.go (80%) create mode 100644 constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/podgroup.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/workload.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/expansion_generated.go create mode 100644 constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/storageversionmigration.go rename constraint/vendor/k8s.io/client-go/tools/cache/{fifo_metrics.go => informer_metrics.go} (98%) delete mode 100644 constraint/vendor/k8s.io/client-go/util/retry/OWNERS create mode 100644 constraint/vendor/k8s.io/component-base/metrics/api/v1/zz_generated.model_name.go delete mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go delete mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/internal.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags/flags.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts/options.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/decode.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/encode.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/wire.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/decode.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/doc.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/encode.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/errors.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/export.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/options.go rename constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/{ => jsontext}/pools.go (64%) create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/quote.go rename constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/{ => jsontext}/state.go (63%) rename constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/{ => jsontext}/token.go (87%) create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/value.go create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/migrate.sh create mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/options.go delete mode 100644 constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go create mode 100644 constraint/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go create mode 100644 constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go create mode 100644 constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go create mode 100644 constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go create mode 100644 constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go diff --git a/constraint/go.mod b/constraint/go.mod index 8fb2998f8..242899075 100644 --- a/constraint/go.mod +++ b/constraint/go.mod @@ -11,12 +11,12 @@ require ( github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 go.uber.org/goleak v1.3.0 - k8s.io/api v0.36.4 - k8s.io/apiextensions-apiserver v0.36.4 - k8s.io/apimachinery v0.36.4 - k8s.io/client-go v0.36.4 - k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 - sigs.k8s.io/controller-runtime v0.24.1 + k8s.io/api v0.37.0 + k8s.io/apiextensions-apiserver v0.37.0 + k8s.io/apimachinery v0.37.0 + k8s.io/client-go v0.37.0 + k8s.io/utils v0.0.0-20260626114624-be93311217bd + sigs.k8s.io/controller-runtime v0.25.0 sigs.k8s.io/yaml v1.6.0 ) @@ -33,20 +33,30 @@ require ( github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/fxamacker/cbor/v2 v2.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/jsonpointer v0.21.0 // indirect - github.com/go-openapi/jsonreference v0.20.2 // indirect - github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-openapi/jsonpointer v1.0.0 // indirect + github.com/go-openapi/jsonreference v1.0.0 // indirect + github.com/go-openapi/swag v0.27.1 // indirect + github.com/go-openapi/swag/cmdutils v0.27.1 // indirect + github.com/go-openapi/swag/conv v0.27.1 // indirect + github.com/go-openapi/swag/fileutils v0.27.1 // indirect + github.com/go-openapi/swag/jsonutils v0.27.1 // indirect + github.com/go-openapi/swag/loading v0.27.1 // indirect + github.com/go-openapi/swag/mangling v0.27.1 // indirect + github.com/go-openapi/swag/netutils v0.27.1 // indirect + github.com/go-openapi/swag/pools v0.27.1 // indirect + github.com/go-openapi/swag/stringutils v0.27.1 // indirect + github.com/go-openapi/swag/typeutils v0.27.1 // indirect + github.com/go-openapi/swag/yamlutils v0.27.1 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/goccy/go-json v0.10.6 // indirect - github.com/google/cel-go v0.29.0 // indirect + github.com/google/cel-go v0.29.2 // indirect github.com/google/gnostic-models v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.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/lestrrat-go/blackmagic v1.0.4 // indirect github.com/lestrrat-go/dsig v1.2.1 // indirect @@ -55,7 +65,6 @@ require ( github.com/lestrrat-go/httprc/v3 v3.0.5 // indirect github.com/lestrrat-go/jwx/v3 v3.1.1 // indirect github.com/lestrrat-go/option/v2 v2.0.0 // indirect - github.com/mailru/easyjson v0.7.7 // 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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect @@ -86,7 +95,7 @@ require ( go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.54.0 // indirect - golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 // indirect + golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect golang.org/x/net v0.57.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.22.0 // indirect @@ -100,13 +109,12 @@ require ( google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // 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/apiserver v0.36.4 // indirect - k8s.io/component-base v0.36.4 // indirect + k8s.io/apiserver v0.37.0 // indirect + k8s.io/component-base v0.37.0 // indirect k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a // indirect - sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 // indirect + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.3.3 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect ) diff --git a/constraint/go.sum b/constraint/go.sum index 75197d08e..68ccdcde7 100644 --- a/constraint/go.sum +++ b/constraint/go.sum @@ -21,7 +21,6 @@ github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03V github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -48,8 +47,8 @@ github.com/foxcpp/go-mockdns v1.2.0 h1:omK3OrHRD1IWJz1FuFBCFquhXslXoF17OvBS6JPzZ github.com/foxcpp/go-mockdns v1.2.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= -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/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= +github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -57,28 +56,52 @@ 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/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= -github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= -github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= -github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= -github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= +github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= +github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= +github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= +github.com/go-openapi/swag v0.27.1 h1:VotvOLWW8q/EAxB0YdsBBGC8XYyeL1YwBj2ungAGPNg= +github.com/go-openapi/swag v0.27.1/go.mod h1:GTkJPwHfhJp6MWr4/rCh64HVI3Ofu+tcsbfjfHmTxpE= +github.com/go-openapi/swag/cmdutils v0.27.1 h1:I7sYqaWVl5mq0NEmNQkAmFDyNin9ufvMX/p2zwtQaOE= +github.com/go-openapi/swag/cmdutils v0.27.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/conv v0.27.1 h1:8wi9ZG+olmY1wXphl93EWniPtbSPkXM/feH7FgjsvrU= +github.com/go-openapi/swag/conv v0.27.1/go.mod h1:QbqMivkpKhC3g1B1GGGOJ6ANewI3S62dbzYu3Duowqs= +github.com/go-openapi/swag/fileutils v0.27.1 h1:QQqBSoi5mW4XpU85nS0mLcA+zAE6vLzrb0QkmLKf9oM= +github.com/go-openapi/swag/fileutils v0.27.1/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= +github.com/go-openapi/swag/jsonutils v0.27.1 h1:SVgK3i4USzCU5mibOOS/l4ea2h9UQXy7J7RNLTjuXjU= +github.com/go-openapi/swag/jsonutils v0.27.1/go.mod h1:tdlEpZqdcQ17uj6J4YdK9vd8It5qWMwjWXOs0tjpRlk= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1 h1:mJu3COL9WEaZVp/Kf2PRMi7tPszPEJfSr/OO75ynCs8= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= +github.com/go-openapi/swag/loading v0.27.1 h1:/DxUgDXKbBX4bcn7r9uEXfJyzN5XpiJmZplzQTjrRCY= +github.com/go-openapi/swag/loading v0.27.1/go.mod h1:jvGh3iA2+zyUUycB5fgJWzeHnhrpvGnJJM0RVE9ZShE= +github.com/go-openapi/swag/mangling v0.27.1 h1:yC9D0HyUE8gbP+BfmGx9+AA89ikwZTMjESK3OnnoaqA= +github.com/go-openapi/swag/mangling v0.27.1/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= +github.com/go-openapi/swag/netutils v0.27.1 h1:mICMFoS82F5TZ4Zy3cqmcQk+BFeCp3Uyq3Np7GI0/qU= +github.com/go-openapi/swag/netutils v0.27.1/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= +github.com/go-openapi/swag/pools v0.27.1 h1:9LeadcMyb2GJCbXX5hVQDbZ2Lq9TL4dCs/nx1j5DO0E= +github.com/go-openapi/swag/pools v0.27.1/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= +github.com/go-openapi/swag/stringutils v0.27.1 h1:ZXePZ0r2p1qSjo8tD3Un4vFj8+FqlCkczxDrJIhYUp8= +github.com/go-openapi/swag/stringutils v0.27.1/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= +github.com/go-openapi/swag/typeutils v0.27.1 h1:KSTdFlfnse4r6dP9IrEnwMldjE+zs71UeEB3//PtVXc= +github.com/go-openapi/swag/typeutils v0.27.1/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= +github.com/go-openapi/swag/yamlutils v0.27.1 h1:ftxv6xvXb1E3zohUc+okZ9nSqNb9StQX/FXnKZ98sQA= +github.com/go-openapi/swag/yamlutils v0.27.1/go.mod h1:bnxFIB1qewGRiZHypXGZ3fNgf13/0HfRgnS/iZBDrOo= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= +github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= +github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= 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/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v1.2.5 h1:DrW6hGnjIhtvhOIiAKT6Psh/Kd/ldepEa81DKeiRJ5I= github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/cel-go v0.29.0 h1:fEG+Ja3YRwNOqnQxTyJwoByAUAvTuxUGiro/jhrm4F4= -github.com/google/cel-go v0.29.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= +github.com/google/cel-go v0.29.2 h1:ZtDxkeiMmz0mxbKDYiNkE5Lk7V5edMRcaaDf2jX002k= +github.com/google/cel-go v0.29.2/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q= github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= @@ -98,17 +121,12 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF2 github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= 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/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= @@ -127,8 +145,6 @@ github.com/lestrrat-go/jwx/v3 v3.1.1 h1:yd9AdPmZ4INnQ7k42IrzXYpnEG803+SrQ6hdMvzH github.com/lestrrat-go/jwx/v3 v3.1.1/go.mod h1:uw/MN2M/Xiu4FhwcIwH11Zsh9JWx9SWzgALl7/uIEkU= github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss= github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM= github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -171,14 +187,10 @@ github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tchap/go-patricia/v2 v2.3.3 h1:xfNEsODumaEcCcY3gI0hYPZ/PcpVv5ju6RMAhgwZDDc= @@ -197,16 +209,16 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/yashtewari/glob-intersection v0.2.0 h1:8iuHdN88yYuCzCdjt0gDe+6bAhUwBeEWqThExu54RFg= github.com/yashtewari/glob-intersection v0.2.0/go.mod h1:LK7pIC3piUjovexikBbJ26Yml7g8xa5bsjfx2v1fwok= -go.etcd.io/etcd/api/v3 v3.6.8 h1:gqb1VN92TAI6G2FiBvWcqKtHiIjr4SU2GdXxTwyexbM= -go.etcd.io/etcd/api/v3 v3.6.8/go.mod h1:qyQj1HZPUV3B5cbAL8scG62+fyz5dSxxu0w8pn28N6Q= -go.etcd.io/etcd/client/pkg/v3 v3.6.8 h1:Qs/5C0LNFiqXxYf2GU8MVjYUEXJ6sZaYOz0zEqQgy50= -go.etcd.io/etcd/client/pkg/v3 v3.6.8/go.mod h1:GsiTRUZE2318PggZkAo6sWb6l8JLVrnckTNfbG8PWtw= -go.etcd.io/etcd/client/v3 v3.6.8 h1:B3G76t1UykqAOrbio7s/EPatixQDkQBevN8/mwiplrY= -go.etcd.io/etcd/client/v3 v3.6.8/go.mod h1:MVG4BpSIuumPi+ELF7wYtySETmoTWBHVcDoHdVupwt8= +go.etcd.io/etcd/api/v3 v3.7.0 h1:WZlGK7pRtYGDB8ti8wkrQ5D2oWGMbtNL9VA5e+vF2Fg= +go.etcd.io/etcd/api/v3 v3.7.0/go.mod h1:EcTihnwAQ0BQNh5dfAdaFVFdchuo7EP0HlX7TV3jz/A= +go.etcd.io/etcd/client/pkg/v3 v3.7.0 h1:sW9njJzS3vXKcAJjjLQ4nk+avNUJ12Bcijcx8ehUskE= +go.etcd.io/etcd/client/pkg/v3 v3.7.0/go.mod h1:cnzZGIUzSfjEwLC6UBVsSXlEK1eepS/JUD7wE6PLRT0= +go.etcd.io/etcd/client/v3 v3.7.0 h1:5MHO37VbPB87VRPKUXEcicjeQWiTSjpPv3Ume8xPx20= +go.etcd.io/etcd/client/v3 v3.7.0/go.mod h1:DJ382WuwjmbowjPDyaaQ0idWXy4dh91XRhe4FOrb9vM= 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.65.0 h1:XmiuHzgJt067+a6kwyAzkhXooYVv3/TOw9cM2VfJgUM= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.65.0/go.mod h1:KDgtbWKTQs4bM+VPUr6WlL9m/WXcmkCcBlIzqxPGzmI= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= @@ -237,8 +249,8 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= -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/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= +golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= @@ -279,33 +291,33 @@ gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.36.4 h1:RxrvqCL6vgH5/+UnTeu1IIFqYmGfy0hnyrod1rn35Oo= -k8s.io/api v0.36.4/go.mod h1:S2B3orCFBDhrgyWbLeuKcT2QdHIpQesBkCYSlWtwUOw= -k8s.io/apiextensions-apiserver v0.36.4 h1:SfvCVt+4CqKWvzuVytYDT5g9hyb9MztoiYELIkPVrFc= -k8s.io/apiextensions-apiserver v0.36.4/go.mod h1:JT9V2Ju7ys1FY4zbSpmX9XOvKB3/BwsODc4hFQEa+Xo= -k8s.io/apimachinery v0.36.4 h1:PT2UzkupGuAx/+xT5XjiMJ1WGpY3fn9/hdAvjweRet4= -k8s.io/apimachinery v0.36.4/go.mod h1:p2I2dipt7JHG+quVwQ1d02d28O4GdDi77RByQ13MTpk= -k8s.io/apiserver v0.36.4 h1:AtKjaf2eUiX5G6TfF2IOlhuUuvMsHh49Ivr1+4fZ2gA= -k8s.io/apiserver v0.36.4/go.mod h1:RyiGghXP67hb0Ll+7iLJ6GGv2JpEzCn7ljbiA+L3cJ0= -k8s.io/client-go v0.36.4 h1:MDvfDNvMSt0Br94SK8neviVlwL9qifw9B26hJCpD1K0= -k8s.io/client-go v0.36.4/go.mod h1:pNK4WKELbwlEDvtbE8l22lEZL5THYF61H5EealokZmA= -k8s.io/component-base v0.36.4 h1:tz75yC2xgq3kd7vPdBtR8do5iMx0OHf6Zd1kuaxDB84= -k8s.io/component-base v0.36.4/go.mod h1:DCwb306U8ou89NNAp45Csuy8ok+1rp1ELDVPhzN5AWc= +k8s.io/api v0.37.0 h1:Z//Vj9N7RA/yS2sDmxyeo7h+RR4zbUrd2vrd3Z0TbB4= +k8s.io/api v0.37.0/go.mod h1:LKXgcJWMc+f4OLbP5SFR8rulEg07zZhpi/zMULiBImk= +k8s.io/apiextensions-apiserver v0.37.0 h1:zRMQ3+/LIE5oZ0tVvXwYHC+dIkSP5cjNWju7AZU1LOI= +k8s.io/apiextensions-apiserver v0.37.0/go.mod h1:HU0PfSBwchHL5iDau6jjt9zU6ryWkDDlaVUiq91NK80= +k8s.io/apimachinery v0.37.0 h1:Np2AbDtf8x6RDHiD8T9LbKJ9gaegeVNa8yNm5FuGKm0= +k8s.io/apimachinery v0.37.0/go.mod h1:RN3nhprFSCxOi5Selxd7oMTXOe/c+ZbcE7Im+TS2zkE= +k8s.io/apiserver v0.37.0 h1:TXg7OxsOWrAH8J4Zi/gBAZuMw1Dfdd+6cca2h4qjRqo= +k8s.io/apiserver v0.37.0/go.mod h1:OddHDF4gy9qyIb8o/3+qaeP6S0vEObWLgOygVqXksv0= +k8s.io/client-go v0.37.0 h1:nsN31fy8wBySuZ+QRnKmrjRSQLOG2rvoGN0tKd12zhQ= +k8s.io/client-go v0.37.0/go.mod h1:FcGqw+Ll/gNQiq+nPGY1Oyt9y7SgDh1d3MW3RFDEbn0= +k8s.io/component-base v0.37.0 h1:3SdSa4+itMdFTDFTeR8CxKGmSTSMXFlKL4ky8OqjguM= +k8s.io/component-base v0.37.0/go.mod h1:LjOebp4R9y6LODWZQv102ZQxGheLcDO2ZJLAw6bbh4I= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a h1:xCeOEAOoGYl2jnJoHkC3hkbPJgdATINPMAxaynU2Ovg= -k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 h1:AZYQSJemyQB5eRxqcPky+/7EdBj0xi3g0ZcxxJ7vbWU= -k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 h1:hSfpvjjTQXQY2Fol2CS0QHMNs/WI1MOSGzCm1KhM5ec= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= -sigs.k8s.io/controller-runtime v0.24.1 h1:miPEwrmirImAvgME1L9qebGHrOnGJoVmVdtOU9fRfo4= -sigs.k8s.io/controller-runtime v0.24.1/go.mod h1:vFkfY5fGt5xAC/sKb8IBFKgWPNKG9OUG29dR8Y2wImw= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= +k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7ZmzSpBGxduXgywWkJU9zHubgJG03MT+Y= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0/go.mod h1:tJo1aepTXyR+8Xs3sUsGBDk4Ub2AM5dPAPKJx0mpm5c= +sigs.k8s.io/controller-runtime v0.25.0 h1:44KgRUPew331KSJpNu8zJow3iTR5W0p/SfrHdw3lV40= +sigs.k8s.io/controller-runtime v0.25.0/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= 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.3 h1:u08YRbVUi59ri4YD6cg0UqNM4Dimn0sIl+wldcx5PYw= -sigs.k8s.io/structured-merge-diff/v6 v6.3.3/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/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/constraint/vendor/github.com/fxamacker/cbor/v2/.golangci.yml b/constraint/vendor/github.com/fxamacker/cbor/v2/.golangci.yml index 38cb9ae10..08081fbde 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/.golangci.yml +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/.golangci.yml @@ -1,104 +1,116 @@ -# Do not delete linter settings. Linters like gocritic can be enabled on the command line. - -linters-settings: - depguard: - rules: - prevent_unmaintained_packages: - list-mode: strict - files: - - $all - - "!$test" - allow: - - $gostd - - github.com/x448/float16 - deny: - - pkg: io/ioutil - desc: "replaced by io and os packages since Go 1.16: https://tip.golang.org/doc/go1.16#ioutil" - dupl: - threshold: 100 - funlen: - lines: 100 - statements: 50 - goconst: - ignore-tests: true - min-len: 2 - min-occurrences: 3 - gocritic: - enabled-tags: - - diagnostic - - experimental - - opinionated - - performance - - style - disabled-checks: - - commentedOutCode - - dupImport # https://github.com/go-critic/go-critic/issues/845 - - ifElseChain - - octalLiteral - - paramTypeCombine - - whyNoLint - gofmt: - simplify: false - goimports: - local-prefixes: github.com/fxamacker/cbor - golint: - min-confidence: 0 - govet: - check-shadowing: true - lll: - line-length: 140 - maligned: - suggest-new: true - misspell: - locale: US - staticcheck: - checks: ["all"] - +version: "2" linters: - disable-all: true + default: none enable: - asciicheck - bidichk - depguard - errcheck - - exportloopref + - forbidigo - goconst - gocritic - gocyclo - - gofmt - - goimports - goprintffuncname - gosec - - gosimple - govet - ineffassign - misspell - nilerr - revive - staticcheck - - stylecheck - - typecheck - unconvert - unused - + settings: + depguard: + rules: + prevent_unmaintained_packages: + list-mode: strict + files: + - $all + - '!$test' + allow: + - $gostd + - github.com/x448/float16 + deny: + - pkg: io/ioutil + desc: 'replaced by io and os packages since Go 1.16: https://tip.golang.org/doc/go1.16#ioutil' + dupl: + threshold: 100 + funlen: + lines: 100 + statements: 50 + goconst: + min-len: 2 + min-occurrences: 3 + gocritic: + disabled-checks: + - commentedOutCode + - dupImport + - ifElseChain + - octalLiteral + - paramTypeCombine + - whyNoLint + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + govet: + enable: + - shadow + lll: + line-length: 140 + misspell: + locale: US + staticcheck: + checks: + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - path: decode.go + text: string ` overflows ` has (\d+) occurrences, make it a constant + - path: decode.go + text: string ` \(range is \[` has (\d+) occurrences, make it a constant + - path: decode.go + text: string `, ` has (\d+) occurrences, make it a constant + - path: decode.go + text: string ` overflows Go's int64` has (\d+) occurrences, make it a constant + - path: decode.go + text: string `\]\)` has (\d+) occurrences, make it a constant + - path: valid.go + text: string ` for type ` has (\d+) occurrences, make it a constant + - path: valid.go + text: 'string `cbor: ` has (\d+) occurrences, make it a constant' + - linters: + - goconst + path: (.+)_test\.go + paths: + - third_party$ + - builtin$ + - examples$ issues: - # max-issues-per-linter default is 50. Set to 0 to disable limit. max-issues-per-linter: 0 - # max-same-issues default is 3. Set to 0 to disable limit. max-same-issues: 0 - - exclude-rules: - - path: decode.go - text: "string ` overflows ` has (\\d+) occurrences, make it a constant" - - path: decode.go - text: "string ` \\(range is \\[` has (\\d+) occurrences, make it a constant" - - path: decode.go - text: "string `, ` has (\\d+) occurrences, make it a constant" - - path: decode.go - text: "string ` overflows Go's int64` has (\\d+) occurrences, make it a constant" - - path: decode.go - text: "string `\\]\\)` has (\\d+) occurrences, make it a constant" - - path: valid.go - text: "string ` for type ` has (\\d+) occurrences, make it a constant" - - path: valid.go - text: "string `cbor: ` has (\\d+) occurrences, make it a constant" +formatters: + enable: + - gofmt + - goimports + settings: + gofmt: + simplify: false + goimports: + local-prefixes: + - github.com/fxamacker/cbor + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/README.md b/constraint/vendor/github.com/fxamacker/cbor/v2/README.md index d072b81c7..f9ae78ec9 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/README.md +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/README.md @@ -702,21 +702,20 @@ Default limits may need to be increased for systems handling very large data (e. ## Status -[v2.9.0](https://github.com/fxamacker/cbor/releases/tag/v2.9.0) (Jul 13, 2025) improved interoperability/transcoding between CBOR & JSON, refactored tests, and improved docs. -- Add opt-in support for `encoding.TextMarshaler` and `encoding.TextUnmarshaler` to encode and decode from CBOR text string. -- Add opt-in support for `json.Marshaler` and `json.Unmarshaler` via user-provided transcoding function. -- Update docs for TimeMode, Tag, RawTag, and add example for Embedded JSON Tag for CBOR. +v2.9.1 (Mar 29-30, 2026) includes important bugfixes, defensive checks, improved code quality, and more tests. Although not public, the fuzzer was also improved by adding more fuzz tests. -v2.9.0 passed fuzz tests and is production quality. +v2.9.1 passed fuzz tests and is production quality. The minimum version of Go required to build: - v2.8.0 and newer releases require go 1.20+. - v2.7.1 and older releases require go 1.17+. -For more details, see [release notes](https://github.com/fxamacker/cbor/releases). +For more details, see [v2.9.1 release notes](https://github.com/fxamacker/cbor/releases). ### Prior Releases +[v2.9.0](https://github.com/fxamacker/cbor/releases/tag/v2.9.0) (Jul 13, 2025) improved interoperability/transcoding between CBOR & JSON, refactored tests, and improved docs. It passed fuzz tests (billions of executions) and is production quality. + [v2.8.0](https://github.com/fxamacker/cbor/releases/tag/v2.8.0) (March 30, 2025) is a small release primarily to add `omitzero` option to struct field tags and fix bugs. It passed fuzz tests (billions of executions) and is production quality. [v2.7.0](https://github.com/fxamacker/cbor/releases/tag/v2.7.0) (June 23, 2024) adds features and improvements that help large projects (e.g. Kubernetes) use CBOR as an alternative to JSON and Protocol Buffers. Other improvements include speedups, improved memory use, bug fixes, new serialization options, etc. It passed fuzz tests (5+ billion executions) and is production quality. diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/cache.go b/constraint/vendor/github.com/fxamacker/cbor/v2/cache.go index 5051f110f..5743f3eb2 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/cache.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/cache.go @@ -92,94 +92,126 @@ func newTypeInfo(t reflect.Type) *typeInfo { } type decodingStructType struct { - fields fields - fieldIndicesByName map[string]int - err error - toArray bool + fields decodingFields + fieldIndicesByName map[string]int // Only populated if toArray is false + fieldIndicesByIntKey map[int64]int // Only populated if toArray is false + err error + toArray bool } -// The stdlib errors.Join was introduced in Go 1.20, and we still support Go 1.17, so instead, -// here's a very basic implementation of an aggregated error. -type multierror []error - -func (m multierror) Error() string { - var sb strings.Builder - for i, err := range m { - sb.WriteString(err.Error()) - if i < len(m)-1 { - sb.WriteString(", ") - } - } - return sb.String() -} - -func getDecodingStructType(t reflect.Type) *decodingStructType { +func getDecodingStructType(t reflect.Type) (*decodingStructType, error) { if v, _ := decodingStructTypeCache.Load(t); v != nil { - return v.(*decodingStructType) + structType := v.(*decodingStructType) + if structType.err != nil { + return nil, structType.err + } + return structType, nil } flds, structOptions := getFields(t) toArray := hasToArrayOption(structOptions) - var errs []error - for i := 0; i < len(flds); i++ { - if flds[i].keyAsInt { - nameAsInt, numErr := strconv.Atoi(flds[i].name) - if numErr != nil { - errs = append(errs, errors.New("cbor: failed to parse field name \""+flds[i].name+"\" to int ("+numErr.Error()+")")) - break + if toArray { + return getDecodingStructToArrayType(t, flds) + } + + fieldIndicesByName := make(map[string]int, len(flds)) + var fieldIndicesByIntKey map[int64]int + + decFlds := make(decodingFields, len(flds)) + for i, f := range flds { + // nameAsInt is set in getFields() except for fields with an unparsable tagged name. + // Atoi() is called here to catch and save parsing errors. + if f.keyAsInt && f.nameAsInt == 0 { + if _, numErr := strconv.Atoi(f.name); numErr != nil { + structType := &decodingStructType{ + err: errors.New("cbor: failed to parse field name \"" + f.name + "\" to int (" + numErr.Error() + ")"), + } + decodingStructTypeCache.Store(t, structType) + return nil, structType.err } - flds[i].nameAsInt = int64(nameAsInt) } - flds[i].typInfo = getTypeInfo(flds[i].typ) - } + if f.keyAsInt { + if fieldIndicesByIntKey == nil { + fieldIndicesByIntKey = make(map[int64]int, len(flds)) + } + // The duplication check is only a safeguard, since getFields() already deduplicates fields. + if _, ok := fieldIndicesByIntKey[f.nameAsInt]; ok { + structType := &decodingStructType{ + err: fmt.Errorf("cbor: two or more fields of %v have the same keyasint value %d", t, f.nameAsInt), + } + decodingStructTypeCache.Store(t, structType) + return nil, structType.err + } + fieldIndicesByIntKey[f.nameAsInt] = i + } else { + // The duplication check is only a safeguard, since getFields() already deduplicates fields. + if _, ok := fieldIndicesByName[f.name]; ok { + structType := &decodingStructType{ + err: fmt.Errorf("cbor: two or more fields of %v have the same name %q", t, f.name), + } + decodingStructTypeCache.Store(t, structType) + return nil, structType.err + } + fieldIndicesByName[f.name] = i + } - fieldIndicesByName := make(map[string]int, len(flds)) - for i, fld := range flds { - if _, ok := fieldIndicesByName[fld.name]; ok { - errs = append(errs, fmt.Errorf("cbor: two or more fields of %v have the same name %q", t, fld.name)) - continue + decFlds[i] = &decodingField{ + field: *f, + typInfo: getTypeInfo(f.typ), } - fieldIndicesByName[fld.name] = i } - var err error - { - var multi multierror - for _, each := range errs { - if each != nil { - multi = append(multi, each) + structType := &decodingStructType{ + fields: decFlds, + fieldIndicesByName: fieldIndicesByName, + fieldIndicesByIntKey: fieldIndicesByIntKey, + } + decodingStructTypeCache.Store(t, structType) + return structType, nil +} + +func getDecodingStructToArrayType(t reflect.Type, flds fields) (*decodingStructType, error) { + decFlds := make(decodingFields, len(flds)) + for i, f := range flds { + // nameAsInt is set in getFields() except for fields with an unparsable tagged name. + // Atoi() is called here to catch and save parsing errors. + if f.keyAsInt && f.nameAsInt == 0 { + if _, numErr := strconv.Atoi(f.name); numErr != nil { + structType := &decodingStructType{ + err: errors.New("cbor: failed to parse field name \"" + f.name + "\" to int (" + numErr.Error() + ")"), + } + decodingStructTypeCache.Store(t, structType) + return nil, structType.err } } - if len(multi) == 1 { - err = multi[0] - } else if len(multi) > 1 { - err = multi + + decFlds[i] = &decodingField{ + field: *f, + typInfo: getTypeInfo(f.typ), } } structType := &decodingStructType{ - fields: flds, - fieldIndicesByName: fieldIndicesByName, - err: err, - toArray: toArray, + fields: decFlds, + toArray: true, } decodingStructTypeCache.Store(t, structType) - return structType + return structType, nil } type encodingStructType struct { - fields fields - bytewiseFields fields - lengthFirstFields fields - omitEmptyFieldsIdx []int + fields encodingFields + bytewiseFields encodingFields // Only populated if toArray is false + lengthFirstFields encodingFields // Only populated if toArray is false + omitEmptyFieldsIdx []int // Only populated if toArray is false err error toArray bool } -func (st *encodingStructType) getFields(em *encMode) fields { +func (st *encodingStructType) getFields(em *encMode) encodingFields { switch em.sort { case SortNone, SortFastShuffle: return st.fields @@ -191,7 +223,7 @@ func (st *encodingStructType) getFields(em *encMode) fields { } type bytewiseFieldSorter struct { - fields fields + fields encodingFields } func (x *bytewiseFieldSorter) Len() int { @@ -203,11 +235,11 @@ func (x *bytewiseFieldSorter) Swap(i, j int) { } func (x *bytewiseFieldSorter) Less(i, j int) bool { - return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 + return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) < 0 } type lengthFirstFieldSorter struct { - fields fields + fields encodingFields } func (x *lengthFirstFieldSorter) Len() int { @@ -222,13 +254,16 @@ func (x *lengthFirstFieldSorter) Less(i, j int) bool { if len(x.fields[i].cborName) != len(x.fields[j].cborName) { return len(x.fields[i].cborName) < len(x.fields[j].cborName) } - return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) <= 0 + return bytes.Compare(x.fields[i].cborName, x.fields[j].cborName) < 0 } func getEncodingStructType(t reflect.Type) (*encodingStructType, error) { if v, _ := encodingStructTypeCache.Load(t); v != nil { structType := v.(*encodingStructType) - return structType, structType.err + if structType.err != nil { + return nil, structType.err + } + return structType, nil } flds, structOptions := getFields(t) @@ -237,111 +272,119 @@ func getEncodingStructType(t reflect.Type) (*encodingStructType, error) { return getEncodingStructToArrayType(t, flds) } - var err error var hasKeyAsInt bool var hasKeyAsStr bool var omitEmptyIdx []int + + encFlds := make(encodingFields, len(flds)) + e := getEncodeBuffer() - for i := 0; i < len(flds); i++ { + defer putEncodeBuffer(e) + + for i, f := range flds { + encFlds[i] = &encodingField{field: *f} + ef := encFlds[i] + // Get field's encodeFunc - flds[i].ef, flds[i].ief, flds[i].izf = getEncodeFunc(flds[i].typ) - if flds[i].ef == nil { - err = &UnsupportedTypeError{t} - break + ef.ef, ef.ief, ef.izf = getEncodeFunc(f.typ) + if ef.ef == nil { + structType := &encodingStructType{err: &UnsupportedTypeError{t}} + encodingStructTypeCache.Store(t, structType) + return nil, structType.err } // Encode field name - if flds[i].keyAsInt { - nameAsInt, numErr := strconv.Atoi(flds[i].name) - if numErr != nil { - err = errors.New("cbor: failed to parse field name \"" + flds[i].name + "\" to int (" + numErr.Error() + ")") - break + if f.keyAsInt { + if f.nameAsInt == 0 { + // nameAsInt is set in getFields() except for fields with an unparsable tagged name. + // Atoi() is called here to catch and save parsing errors. + if _, numErr := strconv.Atoi(f.name); numErr != nil { + structType := &encodingStructType{ + err: errors.New("cbor: failed to parse field name \"" + f.name + "\" to int (" + numErr.Error() + ")"), + } + encodingStructTypeCache.Store(t, structType) + return nil, structType.err + } } - flds[i].nameAsInt = int64(nameAsInt) + nameAsInt := f.nameAsInt if nameAsInt >= 0 { - encodeHead(e, byte(cborTypePositiveInt), uint64(nameAsInt)) + encodeHead(e, byte(cborTypePositiveInt), uint64(nameAsInt)) //nolint:gosec } else { n := nameAsInt*(-1) - 1 - encodeHead(e, byte(cborTypeNegativeInt), uint64(n)) + encodeHead(e, byte(cborTypeNegativeInt), uint64(n)) //nolint:gosec } - flds[i].cborName = make([]byte, e.Len()) - copy(flds[i].cborName, e.Bytes()) + ef.cborName = make([]byte, e.Len()) + copy(ef.cborName, e.Bytes()) e.Reset() hasKeyAsInt = true } else { - encodeHead(e, byte(cborTypeTextString), uint64(len(flds[i].name))) - flds[i].cborName = make([]byte, e.Len()+len(flds[i].name)) - n := copy(flds[i].cborName, e.Bytes()) - copy(flds[i].cborName[n:], flds[i].name) + encodeHead(e, byte(cborTypeTextString), uint64(len(f.name))) + ef.cborName = make([]byte, e.Len()+len(f.name)) + n := copy(ef.cborName, e.Bytes()) + copy(ef.cborName[n:], f.name) e.Reset() // If cborName contains a text string, then cborNameByteString contains a // string that has the byte string major type but is otherwise identical to // cborName. - flds[i].cborNameByteString = make([]byte, len(flds[i].cborName)) - copy(flds[i].cborNameByteString, flds[i].cborName) + ef.cborNameByteString = make([]byte, len(ef.cborName)) + copy(ef.cborNameByteString, ef.cborName) // Reset encoded CBOR type to byte string, preserving the "additional // information" bits: - flds[i].cborNameByteString[0] = byte(cborTypeByteString) | - getAdditionalInformation(flds[i].cborNameByteString[0]) + ef.cborNameByteString[0] = byte(cborTypeByteString) | + getAdditionalInformation(ef.cborNameByteString[0]) hasKeyAsStr = true } // Check if field can be omitted when empty - if flds[i].omitEmpty { + if f.omitEmpty { omitEmptyIdx = append(omitEmptyIdx, i) } } - putEncodeBuffer(e) - - if err != nil { - structType := &encodingStructType{err: err} - encodingStructTypeCache.Store(t, structType) - return structType, structType.err - } // Sort fields by canonical order - bytewiseFields := make(fields, len(flds)) - copy(bytewiseFields, flds) + bytewiseFields := make(encodingFields, len(encFlds)) + copy(bytewiseFields, encFlds) sort.Sort(&bytewiseFieldSorter{bytewiseFields}) lengthFirstFields := bytewiseFields if hasKeyAsInt && hasKeyAsStr { - lengthFirstFields = make(fields, len(flds)) - copy(lengthFirstFields, flds) + lengthFirstFields = make(encodingFields, len(encFlds)) + copy(lengthFirstFields, encFlds) sort.Sort(&lengthFirstFieldSorter{lengthFirstFields}) } structType := &encodingStructType{ - fields: flds, + fields: encFlds, bytewiseFields: bytewiseFields, lengthFirstFields: lengthFirstFields, omitEmptyFieldsIdx: omitEmptyIdx, } encodingStructTypeCache.Store(t, structType) - return structType, structType.err + return structType, nil } func getEncodingStructToArrayType(t reflect.Type, flds fields) (*encodingStructType, error) { - for i := 0; i < len(flds); i++ { - // Get field's encodeFunc - flds[i].ef, flds[i].ief, flds[i].izf = getEncodeFunc(flds[i].typ) - if flds[i].ef == nil { + encFlds := make(encodingFields, len(flds)) + for i, f := range flds { + encFlds[i] = &encodingField{field: *f} + encFlds[i].ef, encFlds[i].ief, encFlds[i].izf = getEncodeFunc(f.typ) + if encFlds[i].ef == nil { structType := &encodingStructType{err: &UnsupportedTypeError{t}} encodingStructTypeCache.Store(t, structType) - return structType, structType.err + return nil, structType.err } } structType := &encodingStructType{ - fields: flds, + fields: encFlds, toArray: true, } encodingStructTypeCache.Store(t, structType) - return structType, structType.err + return structType, nil } func getEncodeFunc(t reflect.Type) (encodeFunc, isEmptyFunc, isZeroFunc) { diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/decode.go b/constraint/vendor/github.com/fxamacker/cbor/v2/decode.go index f0bdc3b38..03fd7f8b0 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/decode.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/decode.go @@ -16,7 +16,6 @@ import ( "math/big" "reflect" "strconv" - "strings" "time" "unicode/utf8" @@ -326,14 +325,14 @@ func (dmkm DupMapKeyMode) valid() bool { return dmkm >= 0 && dmkm < maxDupMapKeyMode } -// IndefLengthMode specifies whether to allow indefinite length items. +// IndefLengthMode specifies whether to allow indefinite-length items. type IndefLengthMode int const ( - // IndefLengthAllowed allows indefinite length items. + // IndefLengthAllowed allows indefinite-length items. IndefLengthAllowed IndefLengthMode = iota - // IndefLengthForbidden disallows indefinite length items. + // IndefLengthForbidden disallows indefinite-length items. IndefLengthForbidden maxIndefLengthMode @@ -378,6 +377,7 @@ const ( // - int64 if value fits // - big.Int or *big.Int (see BigIntDecMode) if value < math.MinInt64 // - return UnmarshalTypeError if value > math.MaxInt64 + // // Deprecated: IntDecConvertSigned should not be used. // Please use other options, such as IntDecConvertSignedOrError, IntDecConvertSignedOrBigInt, IntDecConvertNone. IntDecConvertSigned @@ -811,7 +811,7 @@ type DecOptions struct { // Default is 128*1024=131072 and it can be set to [16, 2147483647] MaxMapPairs int - // IndefLength specifies whether to allow indefinite length CBOR items. + // IndefLength specifies whether to allow indefinite-length CBOR items. IndefLength IndefLengthMode // TagsMd specifies whether to allow CBOR tags (major type 6). @@ -1055,7 +1055,7 @@ func (opts DecOptions) decMode() (*decMode, error) { //nolint:gocritic // ignore } if !opts.ExtraReturnErrors.valid() { - return nil, errors.New("cbor: invalid ExtraReturnErrors " + strconv.Itoa(int(opts.ExtraReturnErrors))) + return nil, errors.New("cbor: invalid ExtraReturnErrors " + strconv.Itoa(int(opts.ExtraReturnErrors))) //nolint:gosec } if opts.DefaultMapType != nil && opts.DefaultMapType.Kind() != reflect.Map { @@ -1149,8 +1149,8 @@ func (opts DecOptions) decMode() (*decMode, error) { //nolint:gocritic // ignore unrecognizedTagToAny: opts.UnrecognizedTagToAny, timeTagToAny: opts.TimeTagToAny, simpleValues: simpleValues, - nanDec: opts.NaN, - infDec: opts.Inf, + nan: opts.NaN, + inf: opts.Inf, byteStringToTime: opts.ByteStringToTime, byteStringExpectedFormat: opts.ByteStringExpectedFormat, bignumTag: opts.BignumTag, @@ -1230,8 +1230,8 @@ type decMode struct { unrecognizedTagToAny UnrecognizedTagToAnyMode timeTagToAny TimeTagToAnyMode simpleValues *SimpleValueRegistry - nanDec NaNMode - infDec InfMode + nan NaNMode + inf InfMode byteStringToTime ByteStringToTimeMode byteStringExpectedFormat ByteStringExpectedFormatMode bignumTag BignumTagMode @@ -1272,8 +1272,8 @@ func (dm *decMode) DecOptions() DecOptions { UnrecognizedTagToAny: dm.unrecognizedTagToAny, TimeTagToAny: dm.timeTagToAny, SimpleValues: simpleValues, - NaN: dm.nanDec, - Inf: dm.infDec, + NaN: dm.nan, + Inf: dm.inf, ByteStringToTime: dm.byteStringToTime, ByteStringExpectedFormat: dm.byteStringExpectedFormat, BignumTag: dm.bignumTag, @@ -1583,11 +1583,11 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin _, ai, val := d.getHead() switch ai { case additionalInformationAsFloat16: - f := float64(float16.Frombits(uint16(val)).Float32()) + f := float64(float16.Frombits(uint16(val)).Float32()) //nolint:gosec return fillFloat(t, f, v) case additionalInformationAsFloat32: - f := float64(math.Float32frombits(uint32(val))) + f := float64(math.Float32frombits(uint32(val))) //nolint:gosec return fillFloat(t, f, v) case additionalInformationAsFloat64: @@ -1595,10 +1595,10 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin return fillFloat(t, f, v) default: // ai <= 24 - if d.dm.simpleValues.rejected[SimpleValue(val)] { + if d.dm.simpleValues.rejected[SimpleValue(val)] { //nolint:gosec return &UnacceptableDataItemError{ CBORType: t.String(), - Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized", + Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized", //nolint:gosec } } @@ -1677,20 +1677,23 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin return d.parseToValue(v, tInfo) case cborTypeArray: - if tInfo.nonPtrKind == reflect.Slice { + switch tInfo.nonPtrKind { + case reflect.Slice: return d.parseArrayToSlice(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Array { + case reflect.Array: return d.parseArrayToArray(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Struct { + case reflect.Struct: return d.parseArrayToStruct(v, tInfo) } + d.skip() return &UnmarshalTypeError{CBORType: t.String(), GoType: tInfo.nonPtrType.String()} case cborTypeMap: - if tInfo.nonPtrKind == reflect.Struct { + switch tInfo.nonPtrKind { + case reflect.Struct: return d.parseMapToStruct(v, tInfo) - } else if tInfo.nonPtrKind == reflect.Map { + case reflect.Map: return d.parseMapToMap(v, tInfo) } d.skip() @@ -1745,8 +1748,8 @@ func (d *decoder) parseToTime() (time.Time, bool, error) { // Read tag number _, _, tagNum := d.getHead() if tagNum != 0 && tagNum != 1 { - d.skip() // skip tag content - return time.Time{}, false, errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1") + d.skip() // skip tag content + return time.Time{}, false, errors.New("cbor: wrong tag number for time.Time, got " + strconv.Itoa(int(tagNum)) + ", expect 0 or 1") //nolint:gosec } } } else { @@ -1815,10 +1818,10 @@ func (d *decoder) parseToTime() (time.Time, bool, error) { var f float64 switch ai { case additionalInformationAsFloat16: - f = float64(float16.Frombits(uint16(val)).Float32()) + f = float64(float16.Frombits(uint16(val)).Float32()) //nolint:gosec case additionalInformationAsFloat32: - f = float64(math.Float32frombits(uint32(val))) + f = float64(math.Float32frombits(uint32(val))) //nolint:gosec case additionalInformationAsFloat64: f = math.Float64frombits(val) @@ -1832,6 +1835,13 @@ func (d *decoder) parseToTime() (time.Time, bool, error) { return time.Time{}, true, nil } seconds, fractional := math.Modf(f) + if seconds > math.MaxInt64 || seconds < math.MinInt64 { + return time.Time{}, false, &UnmarshalTypeError{ + CBORType: t.String(), + GoType: typeTime.String(), + errorMsg: fmt.Sprintf("%v overflows Go's int64", f), + } + } return time.Unix(int64(seconds), int64(fractional*1e9)), true, nil default: @@ -2145,14 +2155,14 @@ func (d *decoder) parse(skipSelfDescribedTag bool) (any, error) { //nolint:gocyc case cborTypePrimitives: _, ai, val := d.getHead() - if ai <= 24 && d.dm.simpleValues.rejected[SimpleValue(val)] { + if ai <= 24 && d.dm.simpleValues.rejected[SimpleValue(val)] { //nolint:gosec return nil, &UnacceptableDataItemError{ CBORType: t.String(), - Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized", + Message: "simple value " + strconv.FormatInt(int64(val), 10) + " is not recognized", //nolint:gosec } } if ai < 20 || ai == 24 { - return SimpleValue(val), nil + return SimpleValue(val), nil //nolint:gosec } switch ai { @@ -2165,11 +2175,11 @@ func (d *decoder) parse(skipSelfDescribedTag bool) (any, error) { //nolint:gocyc return nil, nil case additionalInformationAsFloat16: - f := float64(float16.Frombits(uint16(val)).Float32()) + f := float64(float16.Frombits(uint16(val)).Float32()) //nolint:gosec return f, nil case additionalInformationAsFloat32: - f := float64(math.Float32frombits(uint32(val))) + f := float64(math.Float32frombits(uint32(val))) //nolint:gosec return f, nil case additionalInformationAsFloat64: @@ -2202,16 +2212,16 @@ func (d *decoder) parse(skipSelfDescribedTag bool) (any, error) { //nolint:gocyc func (d *decoder) parseByteString() ([]byte, bool) { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() if !indefiniteLength { - b := d.data[d.off : d.off+int(val)] - d.off += int(val) + b := d.data[d.off : d.off+int(val)] //nolint:gosec + d.off += int(val) //nolint:gosec return b, false } - // Process indefinite length string chunks. + // Process indefinite-length string chunks. b := []byte{} for !d.foundBreak() { _, _, val = d.getHead() - b = append(b, d.data[d.off:d.off+int(val)]...) - d.off += int(val) + b = append(b, d.data[d.off:d.off+int(val)]...) //nolint:gosec + d.off += int(val) //nolint:gosec } return b, true } @@ -2300,19 +2310,19 @@ func (d *decoder) applyByteStringTextConversion( func (d *decoder) parseTextString() ([]byte, error) { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() if !indefiniteLength { - b := d.data[d.off : d.off+int(val)] - d.off += int(val) + b := d.data[d.off : d.off+int(val)] //nolint:gosec + d.off += int(val) //nolint:gosec if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(b) { return nil, &SemanticError{"cbor: invalid UTF-8 string"} } return b, nil } - // Process indefinite length string chunks. + // Process indefinite-length string chunks. b := []byte{} for !d.foundBreak() { _, _, val = d.getHead() - x := d.data[d.off : d.off+int(val)] - d.off += int(val) + x := d.data[d.off : d.off+int(val)] //nolint:gosec + d.off += int(val) //nolint:gosec if d.dm.utf8 == UTF8RejectInvalid && !utf8.Valid(x) { for !d.foundBreak() { d.skip() // Skip remaining chunk on error @@ -2327,7 +2337,7 @@ func (d *decoder) parseTextString() ([]byte, error) { func (d *decoder) parseArray() ([]any, error) { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec if !hasSize { count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance } @@ -2349,7 +2359,7 @@ func (d *decoder) parseArray() ([]any, error) { func (d *decoder) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec if !hasSize { count = d.numOfItemsUntilBreak() // peek ahead to get array size to preallocate slice for better performance } @@ -2371,7 +2381,7 @@ func (d *decoder) parseArrayToSlice(v reflect.Value, tInfo *typeInfo) error { func (d *decoder) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec gi := 0 vLen := v.Len() var err error @@ -2400,7 +2410,7 @@ func (d *decoder) parseArrayToArray(v reflect.Value, tInfo *typeInfo) error { func (d *decoder) parseMap() (any, error) { _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec m := make(map[any]any) var k, e any var err, lastErr error @@ -2465,7 +2475,7 @@ func (d *decoder) parseMap() (any, error) { func (d *decoder) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec if v.IsNil() { mapsize := count if !hasSize { @@ -2566,9 +2576,9 @@ func (d *decoder) parseMapToMap(v reflect.Value, tInfo *typeInfo) error { //noli } func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error { - structType := getDecodingStructType(tInfo.nonPtrType) - if structType.err != nil { - return structType.err + structType, structTypeErr := getDecodingStructType(tInfo.nonPtrType) + if structTypeErr != nil { + return structTypeErr } if !structType.toArray { @@ -2584,7 +2594,7 @@ func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error { start := d.off _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec if !hasSize { count = d.numOfItemsUntilBreak() // peek ahead to get array size } @@ -2637,11 +2647,72 @@ func (d *decoder) parseArrayToStruct(v reflect.Value, tInfo *typeInfo) error { return err } -// parseMapToStruct needs to be fast so gocyclo can be ignored for now. +// skipMapEntriesFromIndex skips remaining map entries starting from index i. +func (d *decoder) skipMapEntriesFromIndex(i, count int, hasSize bool) { + for ; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { + d.skip() + d.skip() + } +} + +// skipMapForDupKey skips the current map value and all remaining map entries, +// then returns a DupMapKeyError for the given key at map index i. +func (d *decoder) skipMapForDupKey(dupKey any, i, count int, hasSize bool) error { + // Skip the value of the duplicate key. + d.skip() + // Skip all remaining map entries. + d.skipMapEntriesFromIndex(i+1, count, hasSize) + return &DupMapKeyError{dupKey, i} +} + +// skipMapForUnknownField skips the current map value and all remaining map entries, +// then returns a UnknownFieldError for the given key at map index i. +func (d *decoder) skipMapForUnknownField(i, count int, hasSize bool) error { + // Skip the value of the unknown key. + d.skip() + // Skip all remaining map entries. + d.skipMapEntriesFromIndex(i+1, count, hasSize) + return &UnknownFieldError{i} +} + +// decodeToStructField decodes the next CBOR value into the struct field f in v. +// If the field cannot be resolved, the CBOR value is skipped. +func (d *decoder) decodeToStructField(v reflect.Value, f *decodingField, tInfo *typeInfo) error { + var fv reflect.Value + + if len(f.idx) == 1 { + fv = v.Field(f.idx[0]) + } else { + var err error + fv, err = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { + // Return a new value for embedded field null pointer to point to, or return error. + if !v.CanSet() { + return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String()) + } + v.Set(reflect.New(v.Type().Elem())) + return v, nil + }) + if !fv.IsValid() { + d.skip() + return err + } + } + + err := d.parseToValue(fv, f.typInfo) + if err != nil { + if typeError, ok := err.(*UnmarshalTypeError); ok { + typeError.StructFieldName = tInfo.nonPtrType.String() + "." + f.name + } + return err + } + + return nil +} + func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //nolint:gocyclo - structType := getDecodingStructType(tInfo.nonPtrType) - if structType.err != nil { - return structType.err + structType, structTypeErr := getDecodingStructType(tInfo.nonPtrType) + if structTypeErr != nil { + return structTypeErr } if structType.toArray { @@ -2654,14 +2725,12 @@ func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //n } } - var err, lastErr error - // Get CBOR map size _, _, val, indefiniteLength := d.getHeadWithIndefiniteLengthFlag() hasSize := !indefiniteLength - count := int(val) + count := int(val) //nolint:gosec - // Keeps track of matched struct fields + // Keep track of matched struct fields to detect duplicate map keys. var foundFldIdx []bool { const maxStackFields = 128 @@ -2675,99 +2744,80 @@ func (d *decoder) parseMapToStruct(v reflect.Value, tInfo *typeInfo) error { //n } } - // Keeps track of CBOR map keys to detect duplicate map key - keyCount := 0 - var mapKeys map[any]struct{} - - errOnUnknownField := (d.dm.extraReturnErrors & ExtraDecErrorUnknownField) > 0 + // Keep track of unmatched CBOR map keys to detect duplicate map keys. + var unmatchedMapKeys map[any]struct{} -MapEntryLoop: - for j := 0; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - var f *field + var err error - // If duplicate field detection is enabled and the key at index j did not match any - // field, k will hold the map key. - var k any + caseInsensitive := d.dm.fieldNameMatching == FieldNameMatchingPreferCaseSensitive + for i := 0; (hasSize && i < count) || (!hasSize && !d.foundBreak()); i++ { t := d.nextCBORType() - if t == cborTypeTextString || (t == cborTypeByteString && d.dm.fieldNameByteString == FieldNameByteStringAllowed) { + + // Reclassify disallowed byte string keys so they fall to the default case. + // keyType is only used for branch control. + keyType := t + if t == cborTypeByteString && d.dm.fieldNameByteString != FieldNameByteStringAllowed { + keyType = 0xff + } + + switch keyType { + case cborTypeTextString, cborTypeByteString: var keyBytes []byte if t == cborTypeTextString { - keyBytes, lastErr = d.parseTextString() - if lastErr != nil { + var parseErr error + keyBytes, parseErr = d.parseTextString() + if parseErr != nil { if err == nil { - err = lastErr + err = parseErr } - d.skip() // skip value + d.skip() // Skip value continue } } else { // cborTypeByteString keyBytes, _ = d.parseByteString() } - // Check for exact match on field name. - if i, ok := structType.fieldIndicesByName[string(keyBytes)]; ok { - fld := structType.fields[i] + // Find matching struct field (exact match, then case-insensitive fallback). + if fldIdx, ok := findStructFieldByKey(structType, keyBytes, caseInsensitive); ok { + fld := structType.fields[fldIdx] - if !foundFldIdx[i] { - f = fld - foundFldIdx[i] = true - } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - err = &DupMapKeyError{fld.name, j} - d.skip() // skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() + switch checkDupField(d.dm, foundFldIdx, fldIdx) { + case mapActionParseValueAndContinue: + if fieldErr := d.decodeToStructField(v, fld, tInfo); fieldErr != nil && err == nil { + err = fieldErr } - return err - } else { - // discard repeated match + continue + case mapActionSkipAllAndReturnError: + return d.skipMapForDupKey(string(keyBytes), i, count, hasSize) + case mapActionSkipValueAndContinue: d.skip() - continue MapEntryLoop + continue } } - // Find field with case-insensitive match - if f == nil && d.dm.fieldNameMatching == FieldNameMatchingPreferCaseSensitive { - keyLen := len(keyBytes) - keyString := string(keyBytes) - for i := 0; i < len(structType.fields); i++ { - fld := structType.fields[i] - if len(fld.name) == keyLen && strings.EqualFold(fld.name, keyString) { - if !foundFldIdx[i] { - f = fld - foundFldIdx[i] = true - } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - err = &DupMapKeyError{keyString, j} - d.skip() // skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } else { - // discard repeated match - d.skip() - continue MapEntryLoop - } - break - } - } + // No matching struct field found. + if unmatchedErr := handleUnmatchedMapKey(d, string(keyBytes), i, count, hasSize, &unmatchedMapKeys); unmatchedErr != nil { + return unmatchedErr } - if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil { - k = string(keyBytes) - } - } else if t <= cborTypeNegativeInt { // uint/int + case cborTypePositiveInt, cborTypeNegativeInt: var nameAsInt int64 if t == cborTypePositiveInt { _, _, val := d.getHead() - nameAsInt = int64(val) + if val > math.MaxInt64 { + if err == nil { + err = &UnmarshalTypeError{ + CBORType: t.String(), + GoType: reflect.TypeOf(int64(0)).String(), + errorMsg: strconv.FormatUint(val, 10) + " overflows Go's int64", + } + } + d.skip() // skip value + continue + } + nameAsInt = int64(val) //nolint:gosec } else { _, _, val := d.getHead() if val > math.MaxInt64 { @@ -2781,39 +2831,35 @@ MapEntryLoop: d.skip() // skip value continue } - nameAsInt = int64(-1) ^ int64(val) - } - - // Find field - for i := 0; i < len(structType.fields); i++ { - fld := structType.fields[i] - if fld.keyAsInt && fld.nameAsInt == nameAsInt { - if !foundFldIdx[i] { - f = fld - foundFldIdx[i] = true - } else if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - err = &DupMapKeyError{nameAsInt, j} - d.skip() // skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } else { - // discard repeated match - d.skip() - continue MapEntryLoop + nameAsInt = int64(-1) ^ int64(val) //nolint:gosec + } + + // Find field by integer key + if fldIdx, ok := structType.fieldIndicesByIntKey[nameAsInt]; ok { + fld := structType.fields[fldIdx] + + switch checkDupField(d.dm, foundFldIdx, fldIdx) { + case mapActionParseValueAndContinue: + if fieldErr := d.decodeToStructField(v, fld, tInfo); fieldErr != nil && err == nil { + err = fieldErr } - break + continue + case mapActionSkipAllAndReturnError: + return d.skipMapForDupKey(nameAsInt, i, count, hasSize) + case mapActionSkipValueAndContinue: + d.skip() + continue } } - if d.dm.dupMapKey == DupMapKeyEnforcedAPF && f == nil { - k = nameAsInt + // No matching struct field found. + if unmatchedErr := handleUnmatchedMapKey(d, nameAsInt, i, count, hasSize, &unmatchedMapKeys); unmatchedErr != nil { + return unmatchedErr } - } else { + + default: + // CBOR map keys that can't be matched to any struct field. + if err == nil { err = &UnmarshalTypeError{ CBORType: t.String(), @@ -2821,97 +2867,31 @@ MapEntryLoop: errorMsg: "map key is of type " + t.String() + " and cannot be used to match struct field name", } } + + var otherKey any if d.dm.dupMapKey == DupMapKeyEnforcedAPF { // parse key - k, lastErr = d.parse(true) - if lastErr != nil { + var parseErr error + otherKey, parseErr = d.parse(true) + if parseErr != nil { d.skip() // skip value continue } // Detect if CBOR map key can be used as Go map key. - if !isHashableValue(reflect.ValueOf(k)) { + if !isHashableValue(reflect.ValueOf(otherKey)) { d.skip() // skip value continue } } else { d.skip() // skip key } - } - - if f == nil { - if errOnUnknownField { - err = &UnknownFieldError{j} - d.skip() // Skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } - - // Two map keys that match the same struct field are immediately considered - // duplicates. This check detects duplicates between two map keys that do - // not match a struct field. If unknown field errors are enabled, then this - // check is never reached. - if d.dm.dupMapKey == DupMapKeyEnforcedAPF { - if mapKeys == nil { - mapKeys = make(map[any]struct{}, 1) - } - mapKeys[k] = struct{}{} - newKeyCount := len(mapKeys) - if newKeyCount == keyCount { - err = &DupMapKeyError{k, j} - d.skip() // skip value - j++ - // skip the rest of the map - for ; (hasSize && j < count) || (!hasSize && !d.foundBreak()); j++ { - d.skip() - d.skip() - } - return err - } - keyCount = newKeyCount - } - - d.skip() // Skip value - continue - } - - // Get field value by index - var fv reflect.Value - if len(f.idx) == 1 { - fv = v.Field(f.idx[0]) - } else { - fv, lastErr = getFieldValue(v, f.idx, func(v reflect.Value) (reflect.Value, error) { - // Return a new value for embedded field null pointer to point to, or return error. - if !v.CanSet() { - return reflect.Value{}, errors.New("cbor: cannot set embedded pointer to unexported struct: " + v.Type().String()) - } - v.Set(reflect.New(v.Type().Elem())) - return v, nil - }) - if lastErr != nil && err == nil { - err = lastErr - } - if !fv.IsValid() { - d.skip() - continue - } - } - if lastErr = d.parseToValue(fv, f.typInfo); lastErr != nil { - if err == nil { - if typeError, ok := lastErr.(*UnmarshalTypeError); ok { - typeError.StructFieldName = tInfo.nonPtrType.String() + "." + f.name - err = typeError - } else { - err = lastErr - } + if unmatchedErr := handleUnmatchedMapKey(d, otherKey, i, count, hasSize, &unmatchedMapKeys); unmatchedErr != nil { + return unmatchedErr } } } + return err } @@ -2958,15 +2938,15 @@ func (d *decoder) skip() { switch t { case cborTypeByteString, cborTypeTextString: - d.off += int(val) + d.off += int(val) //nolint:gosec case cborTypeArray: - for i := 0; i < int(val); i++ { + for i := 0; i < int(val); i++ { //nolint:gosec d.skip() } case cborTypeMap: - for i := 0; i < int(val)*2; i++ { + for i := 0; i < int(val)*2; i++ { //nolint:gosec d.skip() } diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/decode_map_utils.go b/constraint/vendor/github.com/fxamacker/cbor/v2/decode_map_utils.go new file mode 100644 index 000000000..3c8c423ad --- /dev/null +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/decode_map_utils.go @@ -0,0 +1,98 @@ +// Copyright (c) Faye Amacker. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +package cbor + +import "strings" + +// mapAction represents the next action during decoding a CBOR map to a Go struct. +type mapAction int + +const ( + mapActionParseValueAndContinue mapAction = iota // The caller should process the map value. + mapActionSkipValueAndContinue // The caller should skip the map value. + mapActionSkipAllAndReturnError // The caller should skip the rest of the map and return an error. +) + +// checkDupField checks if a struct field at index i has already been matched and returns the next action. +// If not matched, it marks the field as matched and returns mapActionParseValueAndContinue. +// If matched and DupMapKeyEnforcedAPF is specified in the given dm, it returns mapActionSkipAllAndReturnError. +// If matched and DupMapKeyEnforcedAPF is not specified in the given dm, it returns mapActionSkipValueAndContinue. +func checkDupField(dm *decMode, foundFldIdx []bool, i int) mapAction { + if !foundFldIdx[i] { + foundFldIdx[i] = true + return mapActionParseValueAndContinue + } + if dm.dupMapKey == DupMapKeyEnforcedAPF { + return mapActionSkipAllAndReturnError + } + return mapActionSkipValueAndContinue +} + +// findStructFieldByKey finds a struct field matching keyBytes by name. +// It tries an exact match first. If no exact match is found and +// caseInsensitive is true, it falls back to a case-insensitive search. +// findStructFieldByKey returns the field index and true, or -1 and false. +func findStructFieldByKey( + structType *decodingStructType, + keyBytes []byte, + caseInsensitive bool, +) (int, bool) { + if fldIdx, ok := structType.fieldIndicesByName[string(keyBytes)]; ok { + return fldIdx, true + } + if caseInsensitive { + return findFieldCaseInsensitive(structType.fields, string(keyBytes)) + } + return -1, false +} + +// findFieldCaseInsensitive returns the index of the first field whose name +// case-insensitively matches key, or -1 and false if no field matches. +func findFieldCaseInsensitive(flds decodingFields, key string) (int, bool) { + keyLen := len(key) + for i, f := range flds { + if f.keyAsInt { + continue + } + if len(f.name) == keyLen && strings.EqualFold(f.name, key) { + return i, true + } + } + return -1, false +} + +// handleUnmatchedMapKey handles a map entry whose key does not match any struct +// field. It can return UnknownFieldError or DupMapKeyError. +// handleUnmatchedMapKey consumes the CBOR value, so the caller doesn't need to skip any values. +// If an error is returned, the caller should abort parsing the map and return the error. +// If no error is returned, the caller should continue to process the next map pair. +func handleUnmatchedMapKey( + d *decoder, + key any, + i int, + count int, + hasSize bool, + // *map[any]struct{} is used here because we use lazy initialization for uks + uks *map[any]struct{}, //nolint:gocritic +) error { + errOnUnknownField := (d.dm.extraReturnErrors & ExtraDecErrorUnknownField) > 0 + + if errOnUnknownField { + return d.skipMapForUnknownField(i, count, hasSize) + } + + if d.dm.dupMapKey == DupMapKeyEnforcedAPF { + if *uks == nil { + *uks = make(map[any]struct{}) + } + if _, dup := (*uks)[key]; dup { + return d.skipMapForDupKey(key, i, count, hasSize) + } + (*uks)[key] = struct{}{} + } + + // Skip value. + d.skip() + return nil +} diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/diagnose.go b/constraint/vendor/github.com/fxamacker/cbor/v2/diagnose.go index 44afb8660..42a67ad11 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/diagnose.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/diagnose.go @@ -51,11 +51,8 @@ const ( maxByteStringEncoding ) -func (bse ByteStringEncoding) valid() error { - if bse >= maxByteStringEncoding { - return errors.New("cbor: invalid ByteStringEncoding " + strconv.Itoa(int(bse))) - } - return nil +func (bse ByteStringEncoding) valid() bool { + return bse < maxByteStringEncoding } // DiagOptions specifies Diag options. @@ -104,8 +101,8 @@ func (opts DiagOptions) DiagMode() (DiagMode, error) { } func (opts DiagOptions) diagMode() (*diagMode, error) { - if err := opts.ByteStringEncoding.valid(); err != nil { - return nil, err + if !opts.ByteStringEncoding.valid() { + return nil, errors.New("cbor: invalid ByteStringEncoding " + strconv.Itoa(int(opts.ByteStringEncoding))) } decMode, err := DecOptions{ @@ -360,7 +357,7 @@ func (di *diagnose) item() error { //nolint:gocyclo case cborTypeArray: _, _, val := di.d.getHead() - count := int(val) + count := int(val) //nolint:gosec di.w.WriteByte('[') for i := 0; i < count; i++ { @@ -376,7 +373,7 @@ func (di *diagnose) item() error { //nolint:gocyclo case cborTypeMap: _, _, val := di.d.getHead() - count := int(val) + count := int(val) //nolint:gosec di.w.WriteByte('{') for i := 0; i < count; i++ { @@ -477,8 +474,8 @@ func (di *diagnose) item() error { //nolint:gocyclo func (di *diagnose) writeU16(val rune) { di.w.WriteString("\\u") var in [2]byte - in[0] = byte(val >> 8) - in[1] = byte(val) + in[0] = byte(val >> 8) //nolint:gosec + in[1] = byte(val) //nolint:gosec sz := hex.EncodedLen(len(in)) di.w.Grow(sz) dst := di.w.Bytes()[di.w.Len() : di.w.Len()+sz] @@ -608,7 +605,7 @@ func (di *diagnose) encodeTextString(val string, quote byte) error { c, size := utf8.DecodeRuneInString(val[i:]) switch { - case c == utf8.RuneError: + case c == utf8.RuneError && size == 1: return &SemanticError{"cbor: invalid UTF-8 string"} case c < utf16SurrSelf: @@ -631,7 +628,7 @@ func (di *diagnose) encodeFloat(ai byte, val uint64) error { f64 := float64(0) switch ai { case additionalInformationAsFloat16: - f16 := float16.Frombits(uint16(val)) + f16 := float16.Frombits(uint16(val)) //nolint:gosec switch { case f16.IsNaN(): di.w.WriteString("NaN") @@ -647,7 +644,7 @@ func (di *diagnose) encodeFloat(ai byte, val uint64) error { } case additionalInformationAsFloat32: - f32 := math.Float32frombits(uint32(val)) + f32 := math.Float32frombits(uint32(val)) //nolint:gosec switch { case f32 != f32: di.w.WriteString("NaN") diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/encode.go b/constraint/vendor/github.com/fxamacker/cbor/v2/encode.go index c550617c3..e65a29d8a 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/encode.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/encode.go @@ -30,7 +30,7 @@ import ( // If value implements the Marshaler interface, Marshal calls its // MarshalCBOR method. // -// If value implements encoding.BinaryMarshaler, Marhsal calls its +// If value implements encoding.BinaryMarshaler, Marshal calls its // MarshalBinary method and encode it as CBOR byte string. // // Boolean values encode as CBOR booleans (type 7). @@ -343,7 +343,7 @@ const ( // non-UTC timezone then a "localtime - UTC" numeric offset will be included as specified in RFC3339. // NOTE: User applications can avoid including the RFC3339 numeric offset by: // - providing a time.Time value set to UTC, or - // - using the TimeUnix, TimeUnixMicro, or TimeUnixDynamic option instead of TimeRFC3339. + // - using the TimeUnix, TimeUnixMicro, TimeUnixDynamic, or TimeRFC3339NanoUTC option. TimeRFC3339 // TimeRFC3339Nano causes time.Time to encode to a CBOR time (tag 0) with a text string content @@ -351,9 +351,13 @@ const ( // non-UTC timezone then a "localtime - UTC" numeric offset will be included as specified in RFC3339. // NOTE: User applications can avoid including the RFC3339 numeric offset by: // - providing a time.Time value set to UTC, or - // - using the TimeUnix, TimeUnixMicro, or TimeUnixDynamic option instead of TimeRFC3339Nano. + // - using the TimeUnix, TimeUnixMicro, TimeUnixDynamic, or TimeRFC3339NanoUTC option. TimeRFC3339Nano + // TimeRFC3339NanoUTC causes time.Time to encode to a CBOR time (tag 0) with a text string content + // representing UTC time using nanosecond precision in RFC3339 format. + TimeRFC3339NanoUTC + maxTimeMode ) @@ -436,7 +440,7 @@ const ( // FieldNameToTextString encodes struct fields to CBOR text string (major type 3). FieldNameToTextString FieldNameMode = iota - // FieldNameToTextString encodes struct fields to CBOR byte string (major type 2). + // FieldNameToByteString encodes struct fields to CBOR byte string (major type 2). FieldNameToByteString maxFieldNameMode @@ -567,7 +571,7 @@ type EncOptions struct { // RFC3339 format gets tag number 0, and numeric epoch time tag number 1. TimeTag EncTagMode - // IndefLength specifies whether to allow indefinite length CBOR items. + // IndefLength specifies whether to allow indefinite-length CBOR items. IndefLength IndefLengthMode // NilContainers specifies how to encode nil slices and maps. @@ -1132,10 +1136,11 @@ func encodeFloat(e *bytes.Buffer, em *encMode, v reflect.Value) error { if fopt == ShortestFloat16 { var f16 float16.Float16 p := float16.PrecisionFromfloat32(f32) - if p == float16.PrecisionExact { + switch p { + case float16.PrecisionExact: // Roundtrip float32->float16->float32 test isn't needed. f16 = float16.Fromfloat32(f32) - } else if p == float16.PrecisionUnknown { + case float16.PrecisionUnknown: // Try roundtrip float32->float16->float32 to determine if float32 can fit into float16. f16 = float16.Fromfloat32(f32) if f16.Float32() == f32 { @@ -1293,10 +1298,10 @@ func encodeByteString(e *bytes.Buffer, em *encMode, v reflect.Value) error { if slen == 0 { return e.WriteByte(byte(cborTypeByteString)) } - encodeHead(e, byte(cborTypeByteString), uint64(slen)) + encodeHead(e, byte(cborTypeByteString), uint64(slen)) //nolint:gosec if vk == reflect.Array { for i := 0; i < slen; i++ { - e.WriteByte(byte(v.Index(i).Uint())) + e.WriteByte(byte(v.Index(i).Uint())) //nolint:gosec } return nil } @@ -1333,7 +1338,7 @@ func (ae arrayEncodeFunc) encode(e *bytes.Buffer, em *encMode, v reflect.Value) if alen == 0 { return e.WriteByte(byte(cborTypeArray)) } - encodeHead(e, byte(cborTypeArray), uint64(alen)) + encodeHead(e, byte(cborTypeArray), uint64(alen)) //nolint:gosec for i := 0; i < alen; i++ { if err := ae.f(e, em, v.Index(i)); err != nil { return err @@ -1364,7 +1369,7 @@ func (me mapEncodeFunc) encode(e *bytes.Buffer, em *encMode, v reflect.Value) er return e.WriteByte(byte(cborTypeMap)) } - encodeHead(e, byte(cborTypeMap), uint64(mlen)) + encodeHead(e, byte(cborTypeMap), uint64(mlen)) //nolint:gosec if em.sort == SortNone || em.sort == SortFastShuffle || mlen <= 1 { return me.e(e, em, v, nil) } @@ -1427,7 +1432,7 @@ func (x *bytewiseKeyValueSorter) Swap(i, j int) { func (x *bytewiseKeyValueSorter) Less(i, j int) bool { kvi, kvj := x.kvs[i], x.kvs[j] - return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) <= 0 + return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) < 0 } type lengthFirstKeyValueSorter struct { @@ -1448,7 +1453,7 @@ func (x *lengthFirstKeyValueSorter) Less(i, j int) bool { if keyLengthDifference := (kvi.valueOffset - kvi.offset) - (kvj.valueOffset - kvj.offset); keyLengthDifference != 0 { return keyLengthDifference < 0 } - return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) <= 0 + return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) < 0 } var keyValuePool = sync.Pool{} @@ -1535,8 +1540,8 @@ func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) { // Head is rewritten later if actual encoded field count is different from struct field count. encodedHeadLen := encodeHead(e, byte(cborTypeMap), uint64(len(flds))) - kvbegin := e.Len() - kvcount := 0 + kvBeginOffset := e.Len() + kvCount := 0 for offset := 0; offset < len(flds); offset++ { f := flds[(start+offset)%len(flds)] @@ -1582,10 +1587,10 @@ func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) { return err } - kvcount++ + kvCount++ } - if len(flds) == kvcount { + if len(flds) == kvCount { // Encoded element count in head is the same as actual element count. return nil } @@ -1593,8 +1598,8 @@ func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) { // Overwrite the bytes that were reserved for the head before encoding the map entries. var actualHeadLen int { - headbuf := *bytes.NewBuffer(e.Bytes()[kvbegin-encodedHeadLen : kvbegin-encodedHeadLen : kvbegin]) - actualHeadLen = encodeHead(&headbuf, byte(cborTypeMap), uint64(kvcount)) + headbuf := *bytes.NewBuffer(e.Bytes()[kvBeginOffset-encodedHeadLen : kvBeginOffset-encodedHeadLen : kvBeginOffset]) + actualHeadLen = encodeHead(&headbuf, byte(cborTypeMap), uint64(kvCount)) } if actualHeadLen == encodedHeadLen { @@ -1607,8 +1612,8 @@ func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) { // encoded. The encoded entries are offset to the right by the number of excess reserved // bytes. Shift the entries left to remove the gap. excessReservedBytes := encodedHeadLen - actualHeadLen - dst := e.Bytes()[kvbegin-excessReservedBytes : e.Len()-excessReservedBytes] - src := e.Bytes()[kvbegin:e.Len()] + dst := e.Bytes()[kvBeginOffset-excessReservedBytes : e.Len()-excessReservedBytes] + src := e.Bytes()[kvBeginOffset:e.Len()] copy(dst, src) // After shifting, the excess bytes are at the end of the output buffer and they are @@ -1633,7 +1638,7 @@ func encodeTime(e *bytes.Buffer, em *encMode, v reflect.Value) error { } if em.timeTag == EncTagRequired { tagNumber := 1 - if em.time == TimeRFC3339 || em.time == TimeRFC3339Nano { + if em.time == TimeRFC3339 || em.time == TimeRFC3339Nano || em.time == TimeRFC3339NanoUTC { tagNumber = 0 } encodeHead(e, byte(cborTypeTag), uint64(tagNumber)) @@ -1650,7 +1655,7 @@ func encodeTime(e *bytes.Buffer, em *encMode, v reflect.Value) error { case TimeUnixDynamic: t = t.UTC().Round(time.Microsecond) - secs, nsecs := t.Unix(), uint64(t.Nanosecond()) + secs, nsecs := t.Unix(), uint64(t.Nanosecond()) //nolint:gosec if nsecs == 0 { return encodeInt(e, em, reflect.ValueOf(secs)) } @@ -1661,6 +1666,10 @@ func encodeTime(e *bytes.Buffer, em *encMode, v reflect.Value) error { s := t.Format(time.RFC3339) return encodeString(e, em, reflect.ValueOf(s)) + case TimeRFC3339NanoUTC: + s := t.UTC().Format(time.RFC3339Nano) + return encodeString(e, em, reflect.ValueOf(s)) + default: // TimeRFC3339Nano s := t.Format(time.RFC3339Nano) return encodeString(e, em, reflect.ValueOf(s)) diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/simplevalue.go b/constraint/vendor/github.com/fxamacker/cbor/v2/simplevalue.go index 30f72814f..9912e855c 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/simplevalue.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/simplevalue.go @@ -93,6 +93,6 @@ func (sv *SimpleValue) unmarshalCBOR(data []byte) error { // It is safe to cast val to uint8 here because // - data is already verified to be well-formed CBOR simple value and // - val is <= math.MaxUint8. - *sv = SimpleValue(val) + *sv = SimpleValue(val) //nolint:gosec return nil } diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/stream.go b/constraint/vendor/github.com/fxamacker/cbor/v2/stream.go index 7ac6d7d67..da4c8f210 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/stream.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/stream.go @@ -171,14 +171,20 @@ func NewEncoder(w io.Writer) *Encoder { // Encode writes the CBOR encoding of v. func (enc *Encoder) Encode(v any) error { - if len(enc.indefTypes) > 0 && v != nil { - indefType := enc.indefTypes[len(enc.indefTypes)-1] - if indefType == cborTypeTextString { + if len(enc.indefTypes) > 0 { + switch enc.indefTypes[len(enc.indefTypes)-1] { + case cborTypeTextString: + if v == nil { + return errors.New("cbor: cannot encode nil for indefinite-length text string") + } k := reflect.TypeOf(v).Kind() if k != reflect.String { return errors.New("cbor: cannot encode item type " + k.String() + " for indefinite-length text string") } - } else if indefType == cborTypeByteString { + case cborTypeByteString: + if v == nil { + return errors.New("cbor: cannot encode nil for indefinite-length byte string") + } t := reflect.TypeOf(v) k := t.Kind() if (k != reflect.Array && k != reflect.Slice) || t.Elem().Kind() != reflect.Uint8 { @@ -198,35 +204,35 @@ func (enc *Encoder) Encode(v any) error { return err } -// StartIndefiniteByteString starts byte string encoding of indefinite length. +// StartIndefiniteByteString starts indefinite-length byte string encoding. // Subsequent calls of (*Encoder).Encode() encodes definite length byte strings // ("chunks") as one contiguous string until EndIndefinite is called. func (enc *Encoder) StartIndefiniteByteString() error { return enc.startIndefinite(cborTypeByteString) } -// StartIndefiniteTextString starts text string encoding of indefinite length. +// StartIndefiniteTextString starts indefinite-length text string encoding. // Subsequent calls of (*Encoder).Encode() encodes definite length text strings // ("chunks") as one contiguous string until EndIndefinite is called. func (enc *Encoder) StartIndefiniteTextString() error { return enc.startIndefinite(cborTypeTextString) } -// StartIndefiniteArray starts array encoding of indefinite length. +// StartIndefiniteArray starts indefinite-length array encoding. // Subsequent calls of (*Encoder).Encode() encodes elements of the array // until EndIndefinite is called. func (enc *Encoder) StartIndefiniteArray() error { return enc.startIndefinite(cborTypeArray) } -// StartIndefiniteMap starts array encoding of indefinite length. +// StartIndefiniteMap starts indefinite-length map encoding. // Subsequent calls of (*Encoder).Encode() encodes elements of the map // until EndIndefinite is called. func (enc *Encoder) StartIndefiniteMap() error { return enc.startIndefinite(cborTypeMap) } -// EndIndefinite closes last opened indefinite length value. +// EndIndefinite closes last opened indefinite-length value. func (enc *Encoder) EndIndefinite() error { if len(enc.indefTypes) == 0 { return errors.New("cbor: cannot encode \"break\" code outside indefinite length values") @@ -238,18 +244,22 @@ func (enc *Encoder) EndIndefinite() error { return err } -var cborIndefHeader = map[cborType][]byte{ - cborTypeByteString: {cborByteStringWithIndefiniteLengthHead}, - cborTypeTextString: {cborTextStringWithIndefiniteLengthHead}, - cborTypeArray: {cborArrayWithIndefiniteLengthHead}, - cborTypeMap: {cborMapWithIndefiniteLengthHead}, -} - func (enc *Encoder) startIndefinite(typ cborType) error { if enc.em.indefLength == IndefLengthForbidden { return &IndefiniteLengthError{typ} } - _, err := enc.w.Write(cborIndefHeader[typ]) + var head byte + switch typ { + case cborTypeByteString: + head = cborByteStringWithIndefiniteLengthHead + case cborTypeTextString: + head = cborTextStringWithIndefiniteLengthHead + case cborTypeArray: + head = cborArrayWithIndefiniteLengthHead + case cborTypeMap: + head = cborMapWithIndefiniteLengthHead + } + _, err := enc.w.Write([]byte{head}) if err == nil { enc.indefTypes = append(enc.indefTypes, typ) } @@ -262,7 +272,9 @@ type RawMessage []byte // MarshalCBOR returns m or CBOR nil if m is nil. func (m RawMessage) MarshalCBOR() ([]byte, error) { if len(m) == 0 { - return cborNil, nil + b := make([]byte, len(cborNil)) + copy(b, cborNil) + return b, nil } return m, nil } diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/structfields.go b/constraint/vendor/github.com/fxamacker/cbor/v2/structfields.go index cf0a922cd..b2d71f2e9 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/structfields.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/structfields.go @@ -6,27 +6,43 @@ package cbor import ( "reflect" "sort" + "strconv" "strings" ) +// field holds shared struct field metadata returned by getFields(). type field struct { - name string - nameAsInt int64 // used to decoder to match field name with CBOR int + name string + nameAsInt int64 // used to match field name with CBOR int + idx []int + typ reflect.Type // used during cache building only + keyAsInt bool // used to encode/decode field name as int + tagged bool // used to choose dominant field (at the same level tagged fields dominate untagged fields) + omitEmpty bool // used to skip empty field + omitZero bool // used to skip zero field +} + +type fields []*field + +// encodingField extends field with encoding-specific data. +type encodingField struct { + field cborName []byte - cborNameByteString []byte // major type 2 name encoding iff cborName has major type 3 - idx []int - typ reflect.Type + cborNameByteString []byte // major type 2 name encoding if cborName has major type 3 ef encodeFunc ief isEmptyFunc izf isZeroFunc - typInfo *typeInfo // used to decoder to reuse type info - tagged bool // used to choose dominant field (at the same level tagged fields dominate untagged fields) - omitEmpty bool // used to skip empty field - omitZero bool // used to skip zero field - keyAsInt bool // used to encode/decode field name as int } -type fields []*field +type encodingFields []*encodingField + +// decodingField extends field with decoding-specific data. +type decodingField struct { + field + typInfo *typeInfo // used by decoder to reuse type info +} + +type decodingFields []*decodingField // indexFieldSorter sorts fields by field idx at each level, breaking ties with idx depth. type indexFieldSorter struct { @@ -48,7 +64,7 @@ func (x *indexFieldSorter) Less(i, j int) bool { return iIdx[k] < jIdx[k] } } - return len(iIdx) <= len(jIdx) + return len(iIdx) < len(jIdx) } // nameLevelAndTagFieldSorter sorts fields by field name, idx depth, and presence of tag. @@ -69,6 +85,10 @@ func (x *nameLevelAndTagFieldSorter) Less(i, j int) bool { if fi.name != fj.name { return fi.name < fj.name } + // Fields with the same name but different keyAsInt are in separate namespaces. + if fi.keyAsInt != fj.keyAsInt { + return fi.keyAsInt + } if len(fi.idx) != len(fj.idx) { return len(fi.idx) < len(fj.idx) } @@ -117,22 +137,37 @@ func getFields(t reflect.Type) (flds fields, structOptions string) { } } + // Normalize keyasint field names to their canonical integer string form. + // This ensures that "01", "+1", and "1" are treated as the same key + // during deduplication. + for _, f := range flds { + if f.keyAsInt { + nameAsInt, err := strconv.Atoi(f.name) + if err != nil { + continue // Leave invalid names for callers to report. + } + f.nameAsInt = int64(nameAsInt) + f.name = strconv.Itoa(nameAsInt) + } + } + sort.Sort(&nameLevelAndTagFieldSorter{flds}) // Keep visible fields. j := 0 // index of next unique field for i := 0; i < len(flds); { name := flds[i].name + keyAsInt := flds[i].keyAsInt if i == len(flds)-1 || // last field - name != flds[i+1].name || // field i has unique field name + name != flds[i+1].name || flds[i+1].keyAsInt != keyAsInt || // field i has unique (name, keyAsInt) len(flds[i].idx) < len(flds[i+1].idx) || // field i is at a less nested level than field i+1 (flds[i].tagged && !flds[i+1].tagged) { // field i is tagged while field i+1 is not flds[j] = flds[i] j++ } - // Skip fields with the same field name. - for i++; i < len(flds) && name == flds[i].name; i++ { //nolint:revive + // Skip fields with the same (name, keyAsInt). + for i++; i < len(flds) && name == flds[i].name && keyAsInt == flds[i].keyAsInt; i++ { //nolint:revive } } if j != len(flds) { diff --git a/constraint/vendor/github.com/fxamacker/cbor/v2/valid.go b/constraint/vendor/github.com/fxamacker/cbor/v2/valid.go index b40793b95..850b95019 100644 --- a/constraint/vendor/github.com/fxamacker/cbor/v2/valid.go +++ b/constraint/vendor/github.com/fxamacker/cbor/v2/valid.go @@ -54,7 +54,7 @@ func (e *MaxMapPairsError) Error() string { return "cbor: exceeded max number of key-value pairs " + strconv.Itoa(e.maxMapPairs) + " for CBOR map" } -// IndefiniteLengthError indicates found disallowed indefinite length items. +// IndefiniteLengthError indicates found disallowed indefinite-length items. type IndefiniteLengthError struct { t cborType } @@ -113,7 +113,7 @@ func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, err } return d.wellformedIndefiniteString(t, depth, checkBuiltinTags) } - valInt := int(val) + valInt := int(val) //nolint:gosec if valInt < 0 { // Detect integer overflow return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, causing integer overflow") @@ -136,7 +136,7 @@ func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, err return d.wellformedIndefiniteArrayOrMap(t, depth, checkBuiltinTags) } - valInt := int(val) + valInt := int(val) //nolint:gosec if valInt < 0 { // Detect integer overflow return 0, errors.New("cbor: " + t.String() + " length " + strconv.FormatUint(val, 10) + " is too large, it would cause integer overflow") @@ -212,7 +212,7 @@ func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, err return depth, nil } -// wellformedIndefiniteString checks indefinite length byte/text string's well-formedness and returns max depth and error. +// wellformedIndefiniteString checks indefinite-length byte/text string's well-formedness and returns max depth and error. func (d *decoder) wellformedIndefiniteString(t cborType, depth int, checkBuiltinTags bool) (int, error) { var err error for { @@ -223,7 +223,7 @@ func (d *decoder) wellformedIndefiniteString(t cborType, depth int, checkBuiltin d.off++ break } - // Peek ahead to get next type and indefinite length status. + // Peek ahead to get next type and indefinite-length status. nt, ai := parseInitialByte(d.data[d.off]) if t != nt { return 0, &SyntaxError{"cbor: wrong element type " + nt.String() + " for indefinite-length " + t.String()} @@ -238,7 +238,7 @@ func (d *decoder) wellformedIndefiniteString(t cborType, depth int, checkBuiltin return depth, nil } -// wellformedIndefiniteArrayOrMap checks indefinite length array/map's well-formedness and returns max depth and error. +// wellformedIndefiniteArrayOrMap checks indefinite-length array/map's well-formedness and returns max depth and error. func (d *decoder) wellformedIndefiniteArrayOrMap(t cborType, depth int, checkBuiltinTags bool) (int, error) { var err error maxDepth := depth @@ -326,7 +326,7 @@ func (d *decoder) wellformedHead() (t cborType, ai byte, val uint64, err error) val = uint64(binary.BigEndian.Uint16(d.data[d.off : d.off+argumentSize])) d.off += argumentSize if t == cborTypePrimitives { - if err := d.acceptableFloat(float64(float16.Frombits(uint16(val)).Float32())); err != nil { + if err := d.acceptableFloat(float64(float16.Frombits(uint16(val)).Float32())); err != nil { //nolint:gosec return 0, 0, 0, err } } @@ -341,7 +341,7 @@ func (d *decoder) wellformedHead() (t cborType, ai byte, val uint64, err error) val = uint64(binary.BigEndian.Uint32(d.data[d.off : d.off+argumentSize])) d.off += argumentSize if t == cborTypePrimitives { - if err := d.acceptableFloat(float64(math.Float32frombits(uint32(val)))); err != nil { + if err := d.acceptableFloat(float64(math.Float32frombits(uint32(val)))); err != nil { //nolint:gosec return 0, 0, 0, err } } @@ -379,12 +379,12 @@ func (d *decoder) wellformedHead() (t cborType, ai byte, val uint64, err error) func (d *decoder) acceptableFloat(f float64) error { switch { - case d.dm.nanDec == NaNDecodeForbidden && math.IsNaN(f): + case d.dm.nan == NaNDecodeForbidden && math.IsNaN(f): return &UnacceptableDataItemError{ CBORType: cborTypePrimitives.String(), Message: "floating-point NaN", } - case d.dm.infDec == InfDecodeForbidden && math.IsInf(f, 0): + case d.dm.inf == InfDecodeForbidden && math.IsInf(f, 0): return &UnacceptableDataItemError{ CBORType: cborTypePrimitives.String(), Message: "floating-point infinity", diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/.gitignore b/constraint/vendor/github.com/go-openapi/jsonpointer/.gitignore index 769c24400..d8f4186fe 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/.gitignore @@ -1 +1,5 @@ -secrets.yml +*.out +*.cov +.idea +.env +.mcp.json diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/constraint/vendor/github.com/go-openapi/jsonpointer/.golangci.yml index 22f8d21cc..9d2733176 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/.golangci.yml @@ -1,61 +1,70 @@ -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 + - goconst - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage + - gomodguard + - gomodguard_v2 + - exhaustruct - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt + - nonamedreturns + - noinlineerr - paralleltest - - tparallel + - recvcheck + - testpackage - thelper - - ifshort - - exhaustruct + - tparallel - 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/constraint/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/constraint/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md index 9322b065e..bac878f21 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md b/constraint/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md new file mode 100644 index 000000000..de0bf5c04 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/CONTRIBUTORS.md @@ -0,0 +1,25 @@ +# Contributors + +- Repository: ['go-openapi/jsonpointer'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 13 | 132 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 83 | | +| @casualjim | 33 | | +| @magodo | 3 | | +| @youyuanwu | 3 | | +| @alexandear | 2 | | +| @gaiaz-iusipov | 1 | | +| @gbjk | 1 | | +| @gordallott | 1 | | +| @ianlancetaylor | 1 | | +| @mfleader | 1 | | +| @Neo2308 | 1 | | +| @olivierlemasle | 1 | | +| @testwill | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github-community-projects/contributors)_ diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/LICENSE b/constraint/vendor/github.com/go-openapi/jsonpointer/LICENSE index d64569567..261eeb9e9 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ b/constraint/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/constraint/vendor/github.com/go-openapi/jsonpointer/NOTICE b/constraint/vendor/github.com/go-openapi/jsonpointer/NOTICE new file mode 100644 index 000000000..201908d2f --- /dev/null +++ b/constraint/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/sigu-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/constraint/vendor/github.com/go-openapi/jsonpointer/README.md b/constraint/vendor/github.com/go-openapi/jsonpointer/README.md index 0108f1d57..6e7929c64 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/README.md +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/README.md @@ -1,19 +1,177 @@ -# 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] [![Discord Channel][discord-badge]][discord-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`. + +## Announcements + +* **2026-07-07** : landing v1.0.0 + * stable API pledge + +* **2026-06-29** : reinsourced external dependency to swag (v0.24.0) + * module `github.com/go-openapi/swag/jsonname` is source directly here, so we no longer have any external dependency + * `jsonname` was never really used by any other package, so it makes sense to deprecate it away from the `swag` family + and retrofit its functionality here. `jsonpointer` no longer get external dependencies, besides test dependencies. + +* **2026-04-15** : added support for trailing "-" for arrays (v0.23.0) + * this brings full support of [RFC6901][RFC6901] + * this is supported for types relying on the reflection-based implemented + * API semantics remain essentially unaltered. Exception: `Pointer.Set(document any,value any) (document any, err error)` + can only perform a best-effort to mutate the input document in place. In the case of adding elements to an array with a + trailing "-", either pass a mutable array (`*[]T`) as the input document, or use the returned updated document instead. + * types that implement the `JSONSetable` interface may not implement the mutation implied by the trailing "-" + +* **2026-04-15** : added support for optional alternate JSON name providers + * for struct support the defaults might not suit all situations: there are known limitations + when it comes to handle untagged fields or embedded types. + * the default name provider in use is not fully aligned with go JSON stdlib + * exposed an option (or global setting) to change the provider that resolves a struct into json keys + * the default behavior is not altered ## Status -Completed YES -Tested YES +API is stable and feature-complete. + +The project continues to receive regular updates, bug fixes and hygiene maintenance (CI, linting, etc). + +## 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][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 + +* [RFC6901][RFC6901] is now fully supported, including trailing "-" semantics for arrays (for `Set` operations). +* Default behavior: JSON name detection in go `struct`s + - Unlike go standard marshaling, untagged fields do not default to the go field name and are ignored. + - anonymous fields are not traversed if untagged + - the above limitations may be overcome by calling `UseGoNameProvider()` at initialization time. + - alternatively, users may inject the desired custom behavior for naming fields as an option. + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines][contributing-doc-site] +* [Maintainers documentation][maintainers-doc-site] +* [Code style][style-doc-site] + +## 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 + +[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 + +[godoc-badge]: https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/jsonpointer +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/FfnFYaC3k5 + + +[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 +[RFC6901]: https://www.rfc-editor.org/rfc/rfc6901 + +[contributing-doc-site]: https://go-openapi.github.io/doc-site/contributing/contributing/index.html +[maintainers-doc-site]: https://go-openapi.github.io/doc-site/maintainers/index.html +[style-doc-site]: https://go-openapi.github.io/doc-site/contributing/style/index.html diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/SECURITY.md b/constraint/vendor/github.com/go-openapi/jsonpointer/SECURITY.md new file mode 100644 index 000000000..1fea2c573 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: 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 diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/errors.go b/constraint/vendor/github.com/go-openapi/jsonpointer/errors.go new file mode 100644 index 000000000..2ae6e3cfb --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/errors.go @@ -0,0 +1,60 @@ +// 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 { + return string(e) +} + +const ( + // 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 pointerError = `JSON pointer must be empty or start with a "` + pointerSeparator + `"` + + // 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" + + // ErrDashToken indicates use of the RFC 6901 "-" reference token in a context where it cannot be + // resolved. + // + // Per RFC 6901 §4 the "-" token refers to the (nonexistent) element after the last array element. + // It may only be used as the terminal token of a [Pointer.Set] against a slice, where it means + // "append". + // + // Any other use (get, offset, intermediate traversal, non-slice target) is an error condition that + // wraps this sentinel. + ErrDashToken pointerError = `the "-" array token cannot be resolved here` //nolint:gosec // G101 false positive: this is a JSON Pointer reference token, not a credential. +) + +const dashToken = "-" + +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) +} + +func errDashOnGet() error { + return fmt.Errorf("cannot resolve %q token on get: %w: %w", dashToken, ErrDashToken, ErrPointer) +} + +func errDashIntermediate() error { + return fmt.Errorf("the %q token may only appear as the terminal token of a pointer: %w: %w", dashToken, ErrDashToken, ErrPointer) +} + +func errDashOnOffset() error { + return fmt.Errorf("cannot compute offset for %q token (nonexistent element): %w: %w", dashToken, ErrDashToken, ErrPointer) +} diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/ifaces.go b/constraint/vendor/github.com/go-openapi/jsonpointer/ifaces.go new file mode 100644 index 000000000..31359c48f --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/ifaces.go @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonpointer + +import "reflect" + +// 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 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 or want to avoid the use of reflection. +// +// # Handling of the RFC 6901 "-" token +// +// When a type implementing JSONSetable is the terminal parent of a [Pointer.Set] call, the library +// passes the raw reference token to JSONSet without interpretation. +// +// In particular, the RFC 6901 "-" token (which conventionally means "append" for arrays, per RFC +// 6902) is forwarded verbatim as the key argument. +// +// Implementations that model an array-like container are expected to give "-" the append semantics; +// implementations that do not should return an error wrapping [ErrDashToken] (or [ErrPointer]) for +// clarity. +// +// Implementations are responsible for any in-place mutation: the library does not attempt to rebind +// the result of JSONSet into a parent container. +type JSONSetable interface { + // JSONSet sets the value pointed at the (unescaped) key. + // + // The key may be the RFC 6901 "-" token when the pointer targets a slice-like member; see the + // interface documentation for details. + JSONSet(key string, value any) error +} + +// NameProvider knows how to resolve go struct fields into json names. +// +// The default provider is brought by +// [github.com/go-openapi/jsonpointer/jsonname.DefaultJSONNameProvider]. +type NameProvider interface { + // GetGoName gets the go name for a json property name + GetGoName(subject any, name string) (string, bool) + + // GetGoNameForType gets the go name for a given type for a json property name + GetGoNameForType(tpe reflect.Type, name string) (string, bool) +} diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/doc.go b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/doc.go new file mode 100644 index 000000000..79232eaca --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/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/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go new file mode 100644 index 000000000..5eec18fbf --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/go_name_provider.go @@ -0,0 +1,288 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonname + +import ( + "reflect" + "strings" + "sync" +) + +var _ providerIface = (*GoNameProvider)(nil) + +// GoNameProvider resolves json property names to go struct field names following the same rules as +// the standard library's [encoding/json] package. +// +// Contrary to [NameProvider], it considers exported fields without a json tag, and promotes fields +// from anonymous embedded struct types. +// +// Rules (aligned with encoding/json): +// +// - unexported fields are ignored; +// - a field tagged `json:"-"` is ignored; +// - a field tagged `json:"-,"` is kept under the json name "-" (stdlib quirk); +// - a field tagged `json:""` or with no json tag at all keeps its Go name as json name; +// - anonymous struct fields without an explicit json tag have their fields +// promoted into the parent, following breadth-first depth rules: +// a shallower field wins over a deeper one; at equal depth, a conflict +// discards all conflicting fields unless exactly one has an explicit json tag. +// +// This type is safe for concurrent use. +type GoNameProvider struct { + lock sync.Mutex + index map[reflect.Type]nameIndex +} + +// NewGoNameProvider creates a new [GoNameProvider]. +func NewGoNameProvider() *GoNameProvider { + return &GoNameProvider{ + index: make(map[reflect.Type]nameIndex), + } +} + +// GetJSONNames gets all the json property names for a type. +func (n *GoNameProvider) GetJSONNames(subject any) []string { + n.lock.Lock() + defer n.lock.Unlock() + + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names := n.nameIndexFor(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 *GoNameProvider) 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 *GoNameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + + names := n.nameIndexFor(tpe) + nme, ok := names.goNames[name] + + return nme, ok +} + +// GetGoName gets the go name for a json property name. +func (n *GoNameProvider) 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 *GoNameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + + names := n.nameIndexFor(tpe) + nme, ok := names.jsonNames[name] + + return nme, ok +} + +func (n *GoNameProvider) nameIndexFor(tpe reflect.Type) nameIndex { + if names, ok := n.index[tpe]; ok { + return names + } + + names := buildGoNameIndex(tpe) + n.index[tpe] = names + + return names +} + +// fieldEntry captures a candidate field discovered while walking a struct along with the +// indirection path from the root type (used to resolve conflicts by depth in the same way +// encoding/json does). +type fieldEntry struct { + goName string + jsonName string + index []int + tagged bool +} + +func buildGoNameIndex(tpe reflect.Type) nameIndex { + fields := collectGoFields(tpe) + + idx := make(map[string]string, len(fields)) + reverseIdx := make(map[string]string, len(fields)) + for _, f := range fields { + idx[f.jsonName] = f.goName + reverseIdx[f.goName] = f.jsonName + } + + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// collectGoFields walks tpe breadth-first along anonymous struct fields, +// reproducing the field selection performed by encoding/json.typeFields. +// +//nolint:gocognit // everything is inlined to help the compiler determine what escapes and what doesn't +func collectGoFields(tpe reflect.Type) []fieldEntry { + if tpe.Kind() != reflect.Struct { + return nil + } + + type queued struct { + typ reflect.Type + index []int + } + + current := []queued{} + next := []queued{{typ: tpe}} + visited := map[reflect.Type]bool{tpe: true} + + var ( + candidates []fieldEntry + count = map[string]int{} + nextCount = map[string]int{} + ) + + for len(next) > 0 { + current, next = next, current[:0] + count, nextCount = nextCount, count + for k := range nextCount { + delete(nextCount, k) + } + + for _, q := range current { + for i := range q.typ.NumField() { + sf := q.typ.Field(i) + + if sf.Anonymous { + ft := sf.Type + if ft.Kind() == reflect.Pointer { + ft = ft.Elem() + } + if !sf.IsExported() && ft.Kind() != reflect.Struct { + continue + } + } else if !sf.IsExported() { + continue + } + + tag := sf.Tag.Get("json") + if tag == "-" { + continue + } + jsonName, _ := parseJSONTag(tag) + tagged := jsonName != "" + + ft := sf.Type + if ft.Kind() == reflect.Pointer { + ft = ft.Elem() + } + + if sf.Anonymous && ft.Kind() == reflect.Struct && !tagged { + if visited[ft] { + continue + } + visited[ft] = true + + index := make([]int, len(q.index)+1) + copy(index, q.index) + index[len(q.index)] = i + next = append(next, queued{typ: ft, index: index}) + + continue + } + + name := jsonName + if name == "" { + name = sf.Name + } + + index := make([]int, len(q.index)+1) + copy(index, q.index) + index[len(q.index)] = i + + candidates = append(candidates, fieldEntry{ + goName: sf.Name, + jsonName: name, + index: index, + tagged: tagged, + }) + nextCount[name]++ + } + } + } + + return dominantFields(candidates) +} + +// dominantFields applies the Go encoding/json conflict resolution rules: at each JSON name, the +// shallowest field wins; at equal depth, a uniquely tagged candidate wins; otherwise all candidates +// for that name are dropped. +func dominantFields(candidates []fieldEntry) []fieldEntry { + byName := make(map[string][]fieldEntry, len(candidates)) + for _, c := range candidates { + byName[c.jsonName] = append(byName[c.jsonName], c) + } + + out := make([]fieldEntry, 0, len(byName)) + for _, group := range byName { + if len(group) == 1 { + out = append(out, group[0]) + + continue + } + + minDepth := len(group[0].index) + for _, c := range group[1:] { + if len(c.index) < minDepth { + minDepth = len(c.index) + } + } + + var shallow []fieldEntry + for _, c := range group { + if len(c.index) == minDepth { + shallow = append(shallow, c) + } + } + + if len(shallow) == 1 { + out = append(out, shallow[0]) + + continue + } + + var tagged []fieldEntry + for _, c := range shallow { + if c.tagged { + tagged = append(tagged, c) + } + } + if len(tagged) == 1 { + out = append(out, tagged[0]) + } + } + + return out +} + +// parseJSONTag returns the name component of a json struct tag and whether it carried any non-name +// option (kept for future-proofing, e.g. "omitempty"). +func parseJSONTag(tag string) (string, string) { + if tag == "" { + return "", "" + } + if before, after, ok := strings.Cut(tag, ","); ok { + return before, after + } + + return tag, "" +} diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/ifaces.go b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/ifaces.go new file mode 100644 index 000000000..64871f0d2 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/ifaces.go @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonname + +import "reflect" + +// providerIface is an unexported compile-time contract that every name provider in this package is +// expected to satisfy. +// +// It mirrors the interface declared by the main consumer of this module: +// [github.com/go-openapi/jsonpointer.NameProvider]. +type providerIface interface { + GetGoName(subject any, name string) (string, bool) + GetGoNameForType(tpe reflect.Type, name string) (string, bool) +} diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go new file mode 100644 index 000000000..1bec2406b --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/jsonname/name_provider.go @@ -0,0 +1,140 @@ +// 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() //nolint:gochecknoglobals // default settings, for backward compatible package-level settings + +var _ providerIface = (*NameProvider)(nil) + +// 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 := range tpe.NumField() { + 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 { + idx := make(map[string]string, tpe.NumField()) + 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/constraint/vendor/github.com/go-openapi/jsonpointer/options.go b/constraint/vendor/github.com/go-openapi/jsonpointer/options.go new file mode 100644 index 000000000..223c1e5ff --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonpointer/options.go @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package jsonpointer + +import ( + "sync" + + "github.com/go-openapi/jsonpointer/jsonname" +) + +// Option to tune the behavior of a JSON [Pointer]. +type Option func(*options) + +var ( + //nolint:gochecknoglobals // package level defaults are provided as a convenient, backward-compatible way to adopt options. + defaultOptions = options{ + provider: jsonname.DefaultJSONNameProvider, + } + //nolint:gochecknoglobals // guards defaultOptions against concurrent SetDefaultNameProvider / read races (testing) + defaultOptionsMu sync.RWMutex +) + +// SetDefaultNameProvider sets the [NameProvider] as a package-level default. +// +// By default, the default provider is [jsonname.DefaultJSONNameProvider]. +// +// It is safe to call concurrently with [Pointer.Get], [Pointer.Set], [GetForToken] and +// [SetForToken]. +// The typical usage is to call it once at initialization time. +// +// A nil provider is ignored. +func SetDefaultNameProvider(provider NameProvider) { + if provider == nil { + return + } + + defaultOptionsMu.Lock() + defer defaultOptionsMu.Unlock() + + defaultOptions.provider = provider +} + +// UseGoNameProvider sets the [NameProvider] as a package-level default to the alternative provider +// [jsonname.GoNameProvider], that covers a few areas not supported by the default name provider. +// +// This implementation supports untagged exported fields and embedded types in go struct. +// It follows strictly the behavior of the JSON standard library regarding field naming conventions. +// +// It is safe to call concurrently with [Pointer.Get], [Pointer.Set], [GetForToken] and +// [SetForToken]. +// The typical usage is to call it once at initialization time. +func UseGoNameProvider() { + SetDefaultNameProvider(jsonname.NewGoNameProvider()) +} + +// DefaultNameProvider returns the current package-level [NameProvider]. +func DefaultNameProvider() NameProvider { //nolint:ireturn // returning the interface is the point — callers pick their own implementation. + defaultOptionsMu.RLock() + defer defaultOptionsMu.RUnlock() + + return defaultOptions.provider +} + +// WithNameProvider injects a custom [NameProvider] to resolve json names from go struct types. +func WithNameProvider(provider NameProvider) Option { + return func(o *options) { + o.provider = provider + } +} + +type options struct { + provider NameProvider +} + +func optionsWithDefaults(opts []Option) options { + var o options + o.provider = DefaultNameProvider() + + for _, apply := range opts { + apply(&o) + } + + return o +} diff --git a/constraint/vendor/github.com/go-openapi/jsonpointer/pointer.go b/constraint/vendor/github.com/go-openapi/jsonpointer/pointer.go index d970c7cf4..05fc863ee 100644 --- a/constraint/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ b/constraint/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 ( @@ -32,421 +11,670 @@ import ( "reflect" "strconv" "strings" - - "github.com/go-openapi/swag" ) const ( emptyPointer = `` pointerSeparator = `/` - - invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator - notFound = `Can't find the pointer in the document` ) -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONPointable interface { - JSONLookup(string) (any, error) -} - -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONSetable interface { - JSONSet(string, any) 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 [JSONSetable.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 for the given 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 + return p, err } -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string +// 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, opts ...Option) (any, reflect.Kind, error) { + o := optionsWithDefaults(opts) + + return p.get(document, o.provider) } -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { +// Set uses the pointer to set a value from a data type that represent a JSON document. +// +// # Mutation contract +// +// Set mutates the provided document in place whenever Go's type system allows it: when document is +// a map, a pointer, or when the targeted value is reached through an addressable ancestor (e.g. a +// struct field traversed via a pointer, a slice element). +// +// Callers that rely on this in-place behavior may continue to ignore the returned document. +// +// The returned document is only load-bearing when Set cannot mutate in place. +// +// This happens in one specific case: appending to a top-level slice passed by value (e.g. document +// of type []T rather than *[]T) via the RFC 6901 "-" terminal token. reflect.Append produces a new +// slice header that the library cannot rebind into the caller's variable; the updated document is +// returned instead. +// +// Pass *[]T if you want in-place rebind for that case as well. +// +// See [ErrDashToken] for the semantics of the "-" token. +func (p *Pointer) Set(document any, value any, opts ...Option) (any, error) { + o := optionsWithDefaults(opts) - var err error + return p.set(document, value, o.provider) +} - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.New(invalidStart) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) - } +// 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)) } - return err + 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 } -// 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) +// String representation of a pointer. +func (p *Pointer) String() string { + if len(p.referenceTokens) == 0 { + return emptyPointer + } + + return pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) } -// 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) +// Offset returns the byte offset, in the raw JSON text of document, of the location referenced by +// this pointer's terminal token. +// +// Unlike [Pointer.Get] and [Pointer.Set], which operate on a decoded Go value, Offset operates +// directly on the textual JSON source. +// +// It drives an [encoding/json.Decoder] over the string and stops at the terminal token, returning +// the position at which the decoder was about to read that token. +// +// It is primarily intended for tooling that needs to map a pointer back to a region of the original +// source: reporting line/column for validation or parse diagnostics, extracting a sub-document by +// slicing the raw bytes, or highlighting the referenced span in an editor. +// +// # Offset semantics +// +// The meaning of the returned offset depends on whether the terminal token addresses an object +// property or an array element: +// +// - Object property: the offset points to the first byte of the key (its +// opening quote character), not to the associated value. For example, +// pointer "/foo/bar" against {"foo": {"bar": 21}} returns 9, the index of +// the opening quote of "bar". +// - Array element: the offset points to the first byte of the value at that +// index. For example, pointer "/0/1" against [[1,2], [3,4]] returns 4, +// the index of the digit 2. +// +// # Errors +// +// Offset returns an error in any of these cases: +// +// - document is not syntactically valid JSON; +// - the structure of document does not match the pointer (e.g. traversing +// into a scalar, or a token that is neither a valid key nor a valid +// numeric index); +// - a referenced key or index does not exist in document; +// - the pointer's terminal token is the RFC 6901 "-" array token, which +// designates a nonexistent element and therefore has no offset in the +// source. The returned error wraps [ErrDashToken]. +// +// All errors wrap [ErrPointer]. +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 skipJSONSeparator(document, offset), 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) +// skipJSONSeparator advances offset past trailing JSON whitespace and at most one value separator +// (comma) in document, so the result points at the first byte of the next JSON token. +// +// The streaming decoder's InputOffset sits right after the most recently consumed token, which +// between values is the comma (or whitespace) — not the following token. +// +// Normalizing here keeps Offset's contract uniform: for both object keys and array elements, and +// regardless of position within the parent container, the returned offset always points at the +// first byte of the addressed token. +func skipJSONSeparator(document string, offset int64) int64 { + n := int64(len(document)) + for offset < n && isJSONWhitespace(document[offset]) { + offset++ + } + if offset < n && document[offset] == ',' { + offset++ + } + for offset < n && isJSONWhitespace(document[offset]) { + offset++ + } + return offset } -// 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 isJSONWhitespace(c byte) bool { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' } -func isNil(input any) bool { - if input == nil { - return true +// "Constructor", parses the given string JSON pointer. +func (p *Pointer) parse(jsonPointerString string) error { + if jsonPointerString == emptyPointer { + return nil } - 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 + 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 } -func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - if isNil(node) { - return nil, kind, fmt.Errorf("nil value has not field %q", decodedToken) +func (p *Pointer) get(node any, nameProvider NameProvider) (any, reflect.Kind, error) { + if nameProvider == nil { + nameProvider = defaultOptions.provider } - switch typed := node.(type) { - case JSONPointable: - r, err := typed.JSONLookup(decodedToken) + 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, kind, err + return nil, knd, err } - return r, kind, nil - case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect - return getSingleImpl(*typed, decodedToken, nameProvider) + node = r + } + + rValue := reflect.ValueOf(node) + kind = rValue.Kind() + + return node, kind, nil +} + +func (p *Pointer) set(node, data any, nameProvider NameProvider) (any, error) { + knd := reflect.ValueOf(node).Kind() + + if knd != reflect.Pointer && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { + return node, errors.Join( + fmt.Errorf("unexpected type: %T", node), //nolint:err113 // err wrapping is carried out by errors.Join, not fmt.Errorf. + ErrUnsupportedValueType, + ErrPointer, + ) + } + + // full document when empty + if len(p.referenceTokens) == 0 { + return node, nil + } + + if nameProvider == nil { + nameProvider = defaultOptions.provider + } + + return p.setAt(node, p.referenceTokens, data, nameProvider) +} + +// setAt recursively walks the token list, setting the data at the terminal token and rebinding any +// new child reference (e.g. a slice header returned by an "-" append) into its parent on the way +// back up. +// +// Returning the (possibly new) node at each level is what makes append work at any depth without +// requiring the caller to pass a pointer to the containing slice: the new slice header propagates +// up and each parent rebinds it via the appropriate kind-specific setter. +func (p *Pointer) setAt(node any, tokens []string, data any, nameProvider NameProvider) (any, error) { + decodedToken := Unescape(tokens[0]) + + if len(tokens) == 1 { + return setSingleImpl(node, data, decodedToken, nameProvider) } - switch kind { //nolint:exhaustive + child, err := p.resolveNodeForToken(node, decodedToken, nameProvider) + if err != nil { + return node, err + } + + newChild, err := p.setAt(child, tokens[1:], data, nameProvider) + if err != nil { + return node, err + } + + return rebindChild(node, decodedToken, newChild, nameProvider) +} + +// rebindChild writes newChild back into node at decodedToken. +// +// For cases where the child was already mutated in place (pointer aliasing, addressable slice +// elements) the rebind is a safe no-op. +// +// For cases where the child was returned by value (map entries holding a slice, slices reached +// through a non-addressable ancestor), the rebind propagates the new value into the parent. +// +// Parents implementing [JSONPointable] are left alone: they took ownership of the child via +// JSONLookup and did not opt into a JSONSet-based rebind on intermediate tokens. +func rebindChild(node any, decodedToken string, newChild any, nameProvider NameProvider) (any, error) { + if _, ok := node.(JSONPointable); ok { + return node, nil + } + + rValue := reflect.Indirect(reflect.ValueOf(node)) + + switch rValue.Kind() { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { - return nil, kind, fmt.Errorf("object has no field %q", decodedToken) + return node, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } fld := rValue.FieldByName(nm) - return fld.Interface(), kind, nil + if !fld.CanSet() { + return node, nil + } + assignReflectValue(fld, newChild) + return node, nil case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if mv.IsValid() { - return mv.Interface(), kind, nil - } - return nil, kind, fmt.Errorf("object has no key %q", decodedToken) + rValue.SetMapIndex(reflect.ValueOf(decodedToken), reflect.ValueOf(newChild)) + return node, nil case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) + if decodedToken == dashToken { + return node, errDashIntermediate() + } + idx, err := strconv.Atoi(decodedToken) if err != nil { - return nil, kind, err + return node, 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'", sLength-1, tokenIndex) + elem := rValue.Index(idx) + if !elem.CanSet() { + return node, nil } - - elem := rValue.Index(tokenIndex) - return elem.Interface(), kind, nil + assignReflectValue(elem, newChild) + return node, nil default: - return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) + return node, errInvalidReference(decodedToken) } - } -func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) +// assignReflectValue assigns src into dst, unwrapping a pointer when dst expects the pointee type. +// +// This tolerates the pointer-wrapping performed by [typeFromValue] for addressable fields. +func assignReflectValue(dst reflect.Value, src any) { + nv := reflect.ValueOf(src) + if !nv.IsValid() { + return + } + if nv.Type().AssignableTo(dst.Type()) { + dst.Set(nv) + return + } + if nv.Kind() == reflect.Pointer && nv.Elem().Type().AssignableTo(dst.Type()) { + dst.Set(nv.Elem()) + } +} - if ns, ok := node.(JSONSetable); ok { // pointer impl - return ns.JSONSet(decodedToken, data) +func (p *Pointer) resolveNodeForToken(node any, decodedToken string, nameProvider 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) } - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) + 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 } - switch rValue.Kind() { //nolint:exhaustive + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + + switch kind { case reflect.Struct: nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) + return nil, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) } - return nil + + return typeFromValue(rValue.FieldByName(nm)), nil case reflect.Map: kv := reflect.ValueOf(decodedToken) - rValue.SetMapIndex(kv, reflect.ValueOf(data)) - return nil + mv := rValue.MapIndex(kv) + + if !mv.IsValid() { + return nil, errNoKey(decodedToken) + } + + return typeFromValue(mv), nil case reflect.Slice: + if decodedToken == dashToken { + return nil, errDashIntermediate() + } tokenIndex, err := strconv.Atoi(decodedToken) if err != nil { - return err + return nil, errors.Join(err, ErrPointer) } + sLength := rValue.Len() if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + return nil, errOutOfBounds(sLength, tokenIndex) } - elem := rValue.Index(tokenIndex) - if !elem.CanSet() { - return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) - } - elem.Set(reflect.ValueOf(data)) - return nil + return typeFromValue(rValue.Index(tokenIndex)), nil default: - return fmt.Errorf("invalid token reference %q", decodedToken) + return nil, errInvalidReference(decodedToken) } - } -func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider +func isNil(input any) bool { + if input == nil { + return true } - kind := reflect.Invalid + kind := reflect.TypeOf(input).Kind() + switch kind { + case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Chan: + return reflect.ValueOf(input).IsNil() + default: + return false + } +} - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil +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() } - for _, token := range p.referenceTokens { + return v.Interface() +} - decodedToken := Unescape(token) +// GetForToken gets a value for a json pointer token 1 level deep. +func GetForToken(document any, decodedToken string, opts ...Option) (any, reflect.Kind, error) { + o := optionsWithDefaults(opts) - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) + return getSingleImpl(document, decodedToken, o.provider) +} + +// SetForToken sets a value for a json pointer token 1 level deep. +// +// See [Pointer.Set] for the mutation contract, in particular the handling of the RFC 6901 "-" token +// on slices. +func SetForToken(document any, decodedToken string, value any, opts ...Option) (any, error) { + o := optionsWithDefaults(opts) + + return setSingleImpl(document, value, decodedToken, o.provider) +} + +func getSingleImpl(node any, decodedToken string, nameProvider NameProvider) (any, reflect.Kind, error) { + rValue := reflect.Indirect(reflect.ValueOf(node)) + kind := rValue.Kind() + if isNil(node) { + return nil, kind, fmt.Errorf("nil value has no field %q: %w", decodedToken, ErrPointer) + } + + switch typed := node.(type) { + case JSONPointable: + r, err := typed.JSONLookup(decodedToken) if err != nil { - return nil, knd, err + return nil, kind, err } - node = r + return r, kind, nil + case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect + return getSingleImpl(*typed, decodedToken, nameProvider) } - rValue := reflect.ValueOf(node) - kind = rValue.Kind() + 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) + } - return node, kind, nil -} + fld := rValue.FieldByName(nm) -func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error { - knd := reflect.ValueOf(node).Kind() + return fld.Interface(), kind, nil - if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { - return errors.New("only structs, pointers, maps and slices are supported for setting values") + case reflect.Map: + kv := reflect.ValueOf(decodedToken) + mv := rValue.MapIndex(kv) + + if mv.IsValid() { + return mv.Interface(), kind, nil + } + + return nil, kind, errNoKey(decodedToken) + + case reflect.Slice: + if decodedToken == dashToken { + return nil, kind, errDashOnGet() + } + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return nil, kind, errors.Join(err, ErrPointer) + } + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return nil, kind, errOutOfBounds(sLength, tokenIndex) + } + + elem := rValue.Index(tokenIndex) + return elem.Interface(), kind, nil + + default: + return nil, kind, errInvalidReference(decodedToken) } +} - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider +func setSingleImpl(node, data any, decodedToken string, nameProvider NameProvider) (any, error) { + // check for nil to prevent panic when calling rValue.Type() + if isNil(node) { + return node, fmt.Errorf("cannot set field %q on nil value: %w", decodedToken, ErrPointer) } - // Full document when empty - if len(p.referenceTokens) == 0 { - return nil + if ns, ok := node.(JSONSetable); ok { + return node, ns.JSONSet(decodedToken, data) } - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) + rValue := reflect.Indirect(reflect.ValueOf(node)) - if isLastToken { + switch rValue.Kind() { + case reflect.Struct: + nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) + if !ok { + return node, fmt.Errorf("object has no field %q: %w", decodedToken, ErrPointer) + } - return setSingleImpl(node, data, decodedToken, nameProvider) + fld := rValue.FieldByName(nm) + if !fld.CanSet() { + return node, fmt.Errorf("can't set struct field %s to %v: %w", nm, data, ErrPointer) } - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := fld.Type() - 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 + if !valueType.AssignableTo(assignedType) { + return node, fmt.Errorf("can't set value with type %T to field %s with type %v: %w", data, nm, assignedType, ErrPointer) } - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - 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() + fld.Set(value) - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) + return node, nil - if !mv.IsValid() { - return fmt.Errorf("object has no key %q", decodedToken) - } - 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.Map: + kv := reflect.ValueOf(decodedToken) + rValue.SetMapIndex(kv, reflect.ValueOf(data)) - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err + return node, nil + + case reflect.Slice: + if decodedToken == dashToken { + // RFC 6901 §4 / RFC 6902 append semantics: terminal "-" appends the value to the slice. + // + // We rebind in place when the slice is reachable via an addressable ancestor; otherwise we + // return the new slice header for the parent (or the public Set) to rebind. + value := reflect.ValueOf(data) + elemType := rValue.Type().Elem() + if !value.Type().AssignableTo(elemType) { + return node, fmt.Errorf("can't append value of type %T to slice of %v: %w", data, elemType, ErrPointer) } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) + newSlice := reflect.Append(rValue, value) + if rValue.CanSet() { + rValue.Set(newSlice) + return node, nil } + return newSlice.Interface(), nil + } - 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() + tokenIndex, err := strconv.Atoi(decodedToken) + if err != nil { + return node, errors.Join(err, ErrPointer) + } - default: - return fmt.Errorf("invalid token reference %q", decodedToken) + sLength := rValue.Len() + if tokenIndex < 0 || tokenIndex >= sLength { + return node, errOutOfBounds(sLength, tokenIndex) } - } + elem := rValue.Index(tokenIndex) + if !elem.CanSet() { + return node, fmt.Errorf("can't set slice index %s to %v: %w", decodedToken, data, ErrPointer) + } - return nil -} + value := reflect.ValueOf(data) + valueType := value.Type() + assignedType := elem.Type() -// 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 -} + if !valueType.AssignableTo(assignedType) { + return node, fmt.Errorf("can't set value with type %T to slice element %d with type %v: %w", data, tokenIndex, assignedType, ErrPointer) + } -// 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 -} + elem.Set(value) -// Pointer to string representation function -func (p *Pointer) String() string { + return node, nil - if len(p.referenceTokens) == 0 { - return emptyPointer + default: + return node, errInvalidReference(decodedToken) } - - 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() { +func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { + for dec.More() { + offset := dec.InputOffset() tk, err := dec.Token() if err != nil { return 0, err } - switch tk := tk.(type) { - case json.Delim: - switch tk { - case '{': - offset, err = offsetSingleObject(dec, ttk) - if err != nil { - return 0, err - } - case '[': - offset, err = offsetSingleArray(dec, ttk) - if err != nil { - return 0, err - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) + key, ok := tk.(string) + if !ok { + return 0, fmt.Errorf("invalid key token %#v: %w", tk, ErrPointer) + } + if key == decodedToken { + return offset, nil } - } - return offset, nil -} -func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { - for dec.More() { - offset := dec.InputOffset() - tk, err := dec.Token() + // Consume the associated value. + // Scalars are fully read by a single Token() call; composite values must be drained. + tk, err = dec.Token() if err != nil { return 0, err } - switch tk := tk.(type) { - case json.Delim: - switch tk { - case '{': - if err = drainSingle(dec); err != nil { - return 0, err - } - case '[': + if delim, isDelim := tk.(json.Delim); isDelim { + switch delim { + case '{', '[': if err = drainSingle(dec); err != nil { return 0, err } } - case string: - if tk == decodedToken { - return offset, nil - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) } } - return 0, fmt.Errorf("token reference %q not found", decodedToken) + + return 0, fmt.Errorf("token reference %q not found: %w", decodedToken, ErrPointer) } func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { + if decodedToken == dashToken { + return 0, errDashOnOffset() + } idx, err := strconv.Atoi(decodedToken) if err != nil { - return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err) + 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++ { @@ -470,12 +698,14 @@ func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { } if !dec.More() { - return 0, fmt.Errorf("token reference %q not found", decodedToken) + 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() { @@ -497,17 +727,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 -// ~0 => ~ -// ~1 => / -// ... and vice versa +// JSON pointer encoding: ~0 => ~ ~1 => / ... and vice versa. const ( encRefTok0 = `~0` @@ -516,16 +744,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/constraint/vendor/github.com/go-openapi/jsonreference/.editorconfig b/constraint/vendor/github.com/go-openapi/jsonreference/.editorconfig new file mode 100644 index 000000000..3152da69a --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/jsonreference/.gitignore b/constraint/vendor/github.com/go-openapi/jsonreference/.gitignore index 769c24400..d8f4186fe 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/.gitignore +++ b/constraint/vendor/github.com/go-openapi/jsonreference/.gitignore @@ -1 +1,5 @@ -secrets.yml +*.out +*.cov +.idea +.env +.mcp.json diff --git a/constraint/vendor/github.com/go-openapi/jsonreference/.golangci.yml b/constraint/vendor/github.com/go-openapi/jsonreference/.golangci.yml index 013fc1943..dc7c96053 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/.golangci.yml +++ b/constraint/vendor/github.com/go-openapi/jsonreference/.golangci.yml @@ -1,50 +1,67 @@ -linters-settings: - govet: - check-shadowing: true - gocyclo: - min-complexity: 30 - maligned: - suggest-new: true - dupl: - threshold: 100 - goconst: - min-len: 2 - min-occurrences: 4 - paralleltest: - ignore-missing: true +version: "2" linters: - enable-all: true + default: all disable: - - maligned - - lll - - gochecknoglobals - - godox - - gocognit - - whitespace - - wsl + - depguard - funlen - - gochecknoglobals - - gochecknoinits - - scopelint - - wrapcheck - - exhaustivestruct - - exhaustive + - godox + - exhaustruct - nlreturn + - nonamedreturns + - noinlineerr + - paralleltest + - recvcheck - testpackage - - gci - - gofumpt - - goerr113 - - gomnd + - thelper - tparallel - - nestif - - godot - - errorlint - - varcheck - - interfacer - - deadcode - - golint - - ifshort - - structcheck - - nosnakecase - varnamelen - - exhaustruct + - 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/constraint/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/constraint/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md index 9322b065e..bac878f21 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md +++ b/constraint/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/constraint/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md b/constraint/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md new file mode 100644 index 000000000..d20737c94 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonreference/CONTRIBUTORS.md @@ -0,0 +1,21 @@ +# Contributors + +- Repository: ['go-openapi/jsonreference'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 9 | 83 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 46 | | +| @casualjim | 25 | | +| @youyuanwu | 5 | | +| @olivierlemasle | 2 | | +| @apelisse | 1 | | +| @gbjk | 1 | | +| @honza | 1 | | +| @Neo2308 | 1 | | +| @erraggy | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github-community-projects/contributors)_ diff --git a/constraint/vendor/github.com/go-openapi/jsonreference/NOTICE b/constraint/vendor/github.com/go-openapi/jsonreference/NOTICE new file mode 100644 index 000000000..814e87ef8 --- /dev/null +++ b/constraint/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/jsonreference, 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/jsonreference +=========================== + +// 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/constraint/vendor/github.com/go-openapi/jsonreference/README.md b/constraint/vendor/github.com/go-openapi/jsonreference/README.md index b94753aa5..fbd16cf89 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/README.md +++ b/constraint/vendor/github.com/go-openapi/jsonreference/README.md @@ -1,15 +1,123 @@ -# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) +# jsonreference -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference) -An implementation of JSON Reference - Go language + +[![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] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] + +--- + +An implementation of JSON Reference for golang. + +## Announcements + +* **2026-07-07** : landing v1.0.0 + * stable API pledge ## 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 + +```go +// Creating a new reference +ref, err := jsonreference.New("http://example.com/doc.json#/definitions/Pet") + +// Fragment-only reference +fragRef := jsonreference.MustCreateRef("#/definitions/Pet") + +// Resolving references +parent, _ := jsonreference.New("http://example.com/base.json") +child, _ := jsonreference.New("#/definitions/Pet") +resolved, _ := parent.Inherits(child) +// Result: "http://example.com/base.json#/definitions/Pet" +``` + + +## 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][contributing-doc-site] +* [Maintainers documentation][maintainers-doc-site] +* [Code style][style-doc-site] + +## 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 +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/FfnFYaC3k5 + + +[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 + +[contributing-doc-site]: https://go-openapi.github.io/doc-site/contributing/contributing/index.html +[maintainers-doc-site]: https://go-openapi.github.io/doc-site/maintainers/index.html +[style-doc-site]: https://go-openapi.github.io/doc-site/contributing/style/index.html diff --git a/constraint/vendor/github.com/go-openapi/jsonreference/SECURITY.md b/constraint/vendor/github.com/go-openapi/jsonreference/SECURITY.md new file mode 100644 index 000000000..1fea2c573 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/jsonreference/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: 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 diff --git a/constraint/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/constraint/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index f0610cf1e..a08b47320 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/constraint/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/constraint/vendor/github.com/go-openapi/jsonreference/reference.go b/constraint/vendor/github.com/go-openapi/jsonreference/reference.go index cfdef03e5..003ba7a83 100644 --- a/constraint/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/constraint/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,51 @@ const ( fragmentRune = `#` ) -// New creates a new reference for the given string -func New(jsonReferenceString string) (Ref, error) { +// ErrChildURL is raised when there is no child. +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 +72,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 +80,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 +134,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/constraint/vendor/github.com/go-openapi/swag/.codecov.yml b/constraint/vendor/github.com/go-openapi/swag/.codecov.yml new file mode 100644 index 000000000..3354f44b2 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/.gitignore b/constraint/vendor/github.com/go-openapi/swag/.gitignore index c4b1b64f0..3ceb596fa 100644 --- a/constraint/vendor/github.com/go-openapi/swag/.gitignore +++ b/constraint/vendor/github.com/go-openapi/swag/.gitignore @@ -3,3 +3,5 @@ vendor Godeps .idea *.out +.mcp.json +.worktrees diff --git a/constraint/vendor/github.com/go-openapi/swag/.golangci.yml b/constraint/vendor/github.com/go-openapi/swag/.golangci.yml index 80e2be004..099c0a78c 100644 --- a/constraint/vendor/github.com/go-openapi/swag/.golangci.yml +++ b/constraint/vendor/github.com/go-openapi/swag/.golangci.yml @@ -1,60 +1,81 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 3 - min-occurrences: 3 - +version: "2" linters: - enable-all: true + default: all disable: - - maligned - - lll - - gochecknoinits - - gochecknoglobals + - cyclop + - depguard + - errchkjson + - errorlint + - exhaustruct + - forcetypeassert - funlen - - godox + - gochecknoglobals + - gochecknoinits - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - godot - - gofumpt + - godox + - goconst + - gomoddirectives + - gomodguard + - gomodguard_v2 + - gosmopolitan + - inamedparam + - intrange + - ireturn + - lll + - musttag + - modernize + - nestif + - nlreturn + - nonamedreturns + - noinlineerr - paralleltest - - tparallel + - recvcheck + - testpackage - thelper - - ifshort - - exhaustruct + - tagliatelle + - tparallel + - unparam - 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 + 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/constraint/vendor/github.com/go-openapi/swag/.mockery.yml b/constraint/vendor/github.com/go-openapi/swag/.mockery.yml new file mode 100644 index 000000000..8557cb58d --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/constraint/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md index 9322b065e..bac878f21 100644 --- a/constraint/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ b/constraint/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md @@ -23,7 +23,9 @@ include: Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or + advances + * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic @@ -55,7 +57,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All +reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. @@ -68,7 +70,7 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] +available at [][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ diff --git a/constraint/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md b/constraint/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md new file mode 100644 index 000000000..0f0711cd5 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/CONTRIBUTORS.md @@ -0,0 +1,36 @@ +# Contributors + +- Repository: ['go-openapi/swag'] + +| Total Contributors | Total Contributions | +| --- | --- | +| 24 | 251 | + +| Username | All Time Contribution Count | All Commits | +| --- | --- | --- | +| @fredbi | 121 | | +| @casualjim | 98 | | +| @alexandear | 4 | | +| @orisano | 3 | | +| @reinerRubin | 2 | | +| @n-inja | 2 | | +| @nitinmohan87 | 2 | | +| @Neo2308 | 2 | | +| @michaelbowler-form3 | 2 | | +| @ujjwalsh | 1 | | +| @griffin-stewie | 1 | | +| @POD666 | 1 | | +| @pytlesk4 | 1 | | +| @shirou | 1 | | +| @seanprince | 1 | | +| @petrkotas | 1 | | +| @mszczygiel | 1 | | +| @sosiska | 1 | | +| @kzys | 1 | | +| @faguirre1 | 1 | | +| @posener | 1 | | +| @diego-fu-hs | 1 | | +| @davidalpert | 1 | | +| @Xe | 1 | | + + _this file was generated by the [Contributors GitHub Action](https://github.com/github-community-projects/contributors)_ diff --git a/constraint/vendor/github.com/go-openapi/swag/README.md b/constraint/vendor/github.com/go-openapi/swag/README.md index a72922299..c6c2d21e9 100644 --- a/constraint/vendor/github.com/go-openapi/swag/README.md +++ b/constraint/vendor/github.com/go-openapi/swag/README.md @@ -1,23 +1,223 @@ -# 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) +# 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) -[![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) + +[![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] [![Discord Channel][discord-badge]][discord-url] [![go version][goversion-badge]][goversion-url] ![Top language][top-badge] ![Commits since latest release][commits-badge] -Contains a bunch of helper functions for go-openapi and go-swagger projects. +--- + +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) +* [Change log](#change-log) +* [Licensing](#licensing) +* [Note to contributors](#note-to-contributors) +* [Roadmap](#roadmap) + +## Announcements + +* **2025-12-19** : new community chat on discord + * a new discord community channel is available to be notified of changes and support users + +You may join the discord community by clicking the invite link on the discord badge (also above). [![Discord Channel][discord-badge]][discord-url] + +## Status + +API is stable. + +## Import this library in your project + +```cmd +go get github.com/go-openapi/swag/{module} +``` + +Or for backward compatibility: + +```cmd +go get github.com/go-openapi/swag +``` + +## Contents + +`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 (deprecated) | infer JSON names from `go` properties
use `github.com/go-openapi/jsonpointer/jsonname` instead | +| `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
| +| `pools` | utilities to work with sync.Pools | | +| `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` + +## Usage + +**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). + +--- + +## Note to contributors + +All kinds of contributions are welcome. + +This repo is a go mono-repo. See [docs](docs/MAINTAINERS.md). + +More general guidelines are available [here](.github/CONTRIBUTING.md). + +## Roadmap + +See the current [TODO list](docs/TODOS.md) + +## Change log + +See + +For pre-v0.26.0 releases, see [release notes](./docs/NOTES.md). + +**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. + + + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + + + + + +## Other documentation + +* [All-time contributors](./CONTRIBUTORS.md) +* [Contributing guidelines][contributing-doc-site] +* [Maintainers documentation][maintainers-doc-site] +* [Code style][style-doc-site] + +## Cutting a new release + +Maintainers can cut a new release by either: +* running [this workflow](https://github.com/go-openapi/swag/actions/workflows/bump-release.yml) +* or pushing a semver tag + * signed tags are preferred + * The tag message is prepended to release notes -This repo has only few dependencies outside of the standard library: + +[test-badge]: https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg +[test-url]: https://github.com/go-openapi/swag/actions/workflows/go-test.yml +[cov-badge]: https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg +[cov-url]: https://codecov.io/gh/go-openapi/swag +[vuln-scan-badge]: https://github.com/go-openapi/swag/actions/workflows/scanner.yml/badge.svg +[vuln-scan-url]: https://github.com/go-openapi/swag/actions/workflows/scanner.yml +[codeql-badge]: https://github.com/go-openapi/swag/actions/workflows/codeql.yml/badge.svg +[codeql-url]: https://github.com/go-openapi/swag/actions/workflows/codeql.yml + +[release-badge]: https://badge.fury.io/gh/go-openapi%2Fswag.svg +[release-url]: https://badge.fury.io/gh/go-openapi%2Fswag +[gomod-badge]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag.svg +[gomod-url]: https://badge.fury.io/go/github.com%2Fgo-openapi%2Fswag + +[gocard-badge]: https://goreportcard.com/badge/github.com/go-openapi/swag +[gocard-url]: https://goreportcard.com/report/github.com/go-openapi/swag +[codefactor-badge]: https://img.shields.io/codefactor/grade/github/go-openapi/swag +[codefactor-url]: https://www.codefactor.io/repository/github/go-openapi/swag + +[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/swag +[godoc-url]: http://pkg.go.dev/github.com/go-openapi/swag +[discord-badge]: https://img.shields.io/discord/1446918742398341256?logo=discord&label=discord&color=blue +[discord-url]: https://discord.gg/FfnFYaC3k5 -* YAML utilities depend on `gopkg.in/yaml.v3` -* `github.com/mailru/easyjson v0.7.7` + +[license-badge]: http://img.shields.io/badge/license-Apache%20v2-orange.svg +[license-url]: https://github.com/go-openapi/swag/?tab=Apache-2.0-1-ov-file#readme + +[goversion-badge]: https://img.shields.io/github/go-mod/go-version/go-openapi/swag +[goversion-url]: https://github.com/go-openapi/swag/blob/master/go.mod +[top-badge]: https://img.shields.io/github/languages/top/go-openapi/swag +[commits-badge]: https://img.shields.io/github/commits-since/go-openapi/swag/latest + +[contributing-doc-site]: https://go-openapi.github.io/doc-site/contributing/contributing/index.html +[maintainers-doc-site]: https://go-openapi.github.io/doc-site/maintainers/index.html +[style-doc-site]: https://go-openapi.github.io/doc-site/contributing/style/index.html diff --git a/constraint/vendor/github.com/go-openapi/swag/SECURITY.md b/constraint/vendor/github.com/go-openapi/swag/SECURITY.md new file mode 100644 index 000000000..1fea2c573 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/SECURITY.md @@ -0,0 +1,37 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| O.x | :white_check_mark: | + +## Vulnerability checks in place + +This repository uses automated vulnerability scans, at every merged commit and at least once a week. + +We use: + +* [`GitHub CodeQL`][codeql-url] +* [`trivy`][trivy-url] +* [`govulncheck`][govulncheck-url] + +Reports are centralized in github security reports and visible only to the maintainers. + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +**please report it privately to the maintainers** +rather than opening a publicly visible GitHub issue. + +Please follow the instructions provided by github to [Privately report a security vulnerability][github-guidance-url]. + +> [!NOTE] +> On Github, navigate to the project's "Security" tab then click on "Report a vulnerability". + +[codeql-url]: https://github.com/github/codeql +[trivy-url]: https://trivy.dev/docs/latest/getting-started +[govulncheck-url]: https://go.dev/blog/govulncheck +[github-guidance-url]: 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 diff --git a/constraint/vendor/github.com/go-openapi/swag/cmdutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/cmdutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go b/constraint/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go new file mode 100644 index 000000000..6c7bbb26f --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/cmdutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/cmdutils/doc.go new file mode 100644 index 000000000..31f2c3753 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/cmdutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/cmdutils_iface.go new file mode 100644 index 000000000..bd0c1fc12 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/LICENSE b/constraint/vendor/github.com/go-openapi/swag/conv/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/convert.go b/constraint/vendor/github.com/go-openapi/swag/conv/convert.go new file mode 100644 index 000000000..f205c3913 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/convert_types.go b/constraint/vendor/github.com/go-openapi/swag/conv/convert_types.go new file mode 100644 index 000000000..cf4c6495e --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/doc.go b/constraint/vendor/github.com/go-openapi/swag/conv/doc.go new file mode 100644 index 000000000..1bd6ead6e --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/format.go b/constraint/vendor/github.com/go-openapi/swag/conv/format.go new file mode 100644 index 000000000..5b87b8e14 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/sizeof.go b/constraint/vendor/github.com/go-openapi/swag/conv/sizeof.go new file mode 100644 index 000000000..494346557 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv/type_constraints.go b/constraint/vendor/github.com/go-openapi/swag/conv/type_constraints.go new file mode 100644 index 000000000..81135e827 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/conv_iface.go b/constraint/vendor/github.com/go-openapi/swag/conv_iface.go new file mode 100644 index 000000000..eea7b2e56 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/convert.go b/constraint/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index fc085aeb8..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/convert_types.go b/constraint/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c49cc473a..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/doc.go b/constraint/vendor/github.com/go-openapi/swag/doc.go index 55094cb74..b54b57478 100644 --- a/constraint/vendor/github.com/go-openapi/swag/doc.go +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/file.go b/constraint/vendor/github.com/go-openapi/swag/file.go deleted file mode 100644 index 16accc55f..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/fileutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/fileutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/fileutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/fileutils/doc.go new file mode 100644 index 000000000..859a200d8 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/fileutils/file.go b/constraint/vendor/github.com/go-openapi/swag/fileutils/file.go new file mode 100644 index 000000000..5ad4cfaea --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/path.go b/constraint/vendor/github.com/go-openapi/swag/fileutils/path.go similarity index 58% rename from constraint/vendor/github.com/go-openapi/swag/path.go rename to constraint/vendor/github.com/go-openapi/swag/fileutils/path.go index 941bd0176..dd09f690b 100644 --- a/constraint/vendor/github.com/go-openapi/swag/path.go +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/fileutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/fileutils_iface.go new file mode 100644 index 000000000..f3e79a0e4 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/go.work b/constraint/vendor/github.com/go-openapi/swag/go.work new file mode 100644 index 000000000..f1dddc436 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/go.work @@ -0,0 +1,21 @@ +use ( + . + ./cmdutils + ./conv + ./fileutils + ./jsonname + ./jsonutils + ./jsonutils/adapters/easyjson + ./jsonutils/adapters/testintegration + ./jsonutils/adapters/testintegration/benchmarks + ./jsonutils/fixtures_test + ./loading + ./mangling + ./netutils + ./pools + ./stringutils + ./typeutils + ./yamlutils +) + +go 1.25.0 diff --git a/constraint/vendor/github.com/go-openapi/swag/go.work.sum b/constraint/vendor/github.com/go-openapi/swag/go.work.sum new file mode 100644 index 000000000..c1308cafa --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/initialism_index.go b/constraint/vendor/github.com/go-openapi/swag/initialism_index.go deleted file mode 100644 index 20a359bb6..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/json.go b/constraint/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index 7e9902ca3..000000000 --- a/constraint/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,312 +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 - } - - if len(b) < 3 { // 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/constraint/vendor/github.com/go-openapi/swag/jsonname_iface.go b/constraint/vendor/github.com/go-openapi/swag/jsonname_iface.go new file mode 100644 index 000000000..443560caa --- /dev/null +++ b/constraint/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/jsonpointer/jsonname" +) + +// DefaultJSONNameProvider is the default cache for types +// +// Deprecated: use [github.com/go-openapi/jsonpointer/jsonname.DefaultJSONNameProvider] instead. +var DefaultJSONNameProvider = jsonname.DefaultJSONNameProvider + +// NameProvider represents an object capable of translating from go property names +// to json property names. +// +// Deprecated: use [github.com/go-openapi/jsonpointer/jsonname.NameProvider] instead. +type NameProvider = jsonname.NameProvider + +// NewNameProvider creates a new name provider +// +// Deprecated: use [github.com/go-openapi/jsonpointer/jsonname.NewNameProvider] instead. +func NewNameProvider() *NameProvider { return jsonname.NewNameProvider() } diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/jsonutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/README.md b/constraint/vendor/github.com/go-openapi/swag/jsonutils/README.md new file mode 100644 index 000000000..07a2ca1d7 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/README.md @@ -0,0 +1,109 @@ +# 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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go new file mode 100644 index 000000000..76d3898fc --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go new file mode 100644 index 000000000..1fd43a1fa --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go new file mode 100644 index 000000000..7805e5e5e --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go new file mode 100644 index 000000000..2d6c69f4e --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go new file mode 100644 index 000000000..3062acaff --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go new file mode 100644 index 000000000..94185f79c --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + stdjson "encoding/json" + "fmt" + + "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 { + options +} + +// NewAdapter yields an [ifaces.Adapter] using the standard library. +func NewAdapter(opts ...Option) *Adapter { + var o options + + return &Adapter{ + options: buildOptions(o, opts), + } +} + +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, redeem := poolOfWriters.BorrowWithRedeem() + defer redeem() + w.setBuf() + + a.orderedMarshal(w, value, 1) + + return w.BuildBytes() +} + +func (a *Adapter) OrderedUnmarshal(data []byte, value ifaces.SetOrdered) error { + var m MapSlice + if err := m.orderedUnmarshalJSON(data, a.maxDepth()); 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() { + a.options = options{} +} + +// orderedMarshal writes value to w, tracking the container nesting depth to guard +// against stack overflow on deeply nested structures. +func (a *Adapter) orderedMarshal(w *jwriter, value ifaces.Ordered, depth int) { + if typeutils.IsNil(value) { + w.RawString("null") + + return + } + + if maxDepth := a.maxDepth(); depth > maxDepth { + w.SetErr(fmt.Errorf("maximum nesting depth of %d exceeded: %w", maxDepth, ErrStdlib)) + + return + } + + 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: + a.orderedMarshal(w, val, depth+1) + default: + w.Raw(stdjson.Marshal(v)) + } + } + + w.RawByte('}') +} diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go new file mode 100644 index 000000000..5ea1b4404 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go new file mode 100644 index 000000000..ac81cbc75 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go @@ -0,0 +1,356 @@ +// 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) //nolint:gosec // delimiter runes are single byte +} + +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 + + // depth tracks the current JSON container nesting level, and maxDepth caps it + // to guard against stack-overflow on adversarially deep documents. The standard + // library's streaming [encoding/json.Decoder.Token] API (used here) does not + // enforce the max-depth guard that [encoding/json.Unmarshal] provides, so we do. + depth int + maxDepth int +} + +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, + maxDepth: defaultMaxNestingDepth, + } + 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 + l.depth = 0 + l.maxDepth = defaultMaxNestingDepth + l.dec = nil + // leave l.buf alone, since they are replaced at every Borrow + l.buf = nil +} + +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) + + return + } + + // Track container nesting depth centrally: every '{' or '[' opens a level and + // every '}' or ']' closes one. This guards the mutually-recursive unmarshal + // routines (unmarshalObject/unmarshalArray/asInterface) against stack overflow. + switch c { + case '{', '[': + l.depth++ + if l.maxDepth > 0 && l.depth > l.maxDepth { + l.err = fmt.Errorf("maximum nesting depth of %d exceeded: %w", l.maxDepth, ErrStdlib) + } + case '}', ']': + l.depth-- + } +} + +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} +} + +func (l *jlexer) setBuf(data []byte) func() { + rdr, redeemBuf := poolOfReaders.BorrowWithRedeem() + l.buf = rdr + l.buf.buf = data + l.dec = stdjson.NewDecoder(l.buf) // cannot pool, not exposed by the encoding/json API + + return redeemBuf +} diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go new file mode 100644 index 000000000..f114f1f1a --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/options.go @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +// defaultMaxNestingDepth is the default maximum number of nested JSON containers +// ('{' or '[') that the ordered-JSON marshaler and unmarshaler will process before +// returning an error. +// +// It mirrors the limit enforced by the standard library's [encoding/json] decoder +// (see encoding/json's internal maxNestingDepth), which this adapter would otherwise +// not benefit from since it drives [encoding/json.Decoder.Token] directly. +const defaultMaxNestingDepth = 10000 + +// Option selects options for the stdlib adapter. +type Option func(o options) options + +type options struct { + maxNestingDepth int +} + +func buildOptions(o options, opts []Option) options { + for _, apply := range opts { + o = apply(o) + } + + return o +} + +// maxDepth returns the configured maximum nesting depth, or the default when unset. +func (o options) maxDepth() int { + if o.maxNestingDepth <= 0 { + return defaultMaxNestingDepth + } + + return o.maxNestingDepth +} + +// WithMaxNestingDepth sets the maximum number of nested JSON containers accepted +// when marshaling or unmarshaling ordered JSON. +// +// A value <= 0 selects the default (10,000). +// +// This guards against stack-overflow crashes on deeply nested (possibly adversarial) +// JSON documents or in-memory structures. +func WithMaxNestingDepth(depth int) Option { + return func(o options) options { + o.maxNestingDepth = depth + + return o + } +} diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go new file mode 100644 index 000000000..a5a8f4b63 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go @@ -0,0 +1,289 @@ +// 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, redeem := poolOfWriters.BorrowWithRedeem() + defer redeem() + w.setBuf() + + s.marshalObject(w, 1) + + 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 { + return s.orderedUnmarshalJSON(data, defaultMaxNestingDepth) +} + +func (s *MapSlice) orderedUnmarshalJSON(data []byte, maxDepth int) error { + l, redeem := poolOfLexers.BorrowWithRedeem() + defer redeem() + + redeemBuf := l.setBuf(data) + defer redeemBuf() + + if maxDepth > 0 { + l.maxDepth = maxDepth + } + + s.unmarshalObject(l) + + return l.Error() +} + +func (s MapSlice) marshalObject(w *jwriter, depth int) { + if s == nil { + w.RawString("null") + + return + } + + if depth > defaultMaxNestingDepth { + w.SetErr(fmt.Errorf("maximum nesting depth of %d exceeded: %w", defaultMaxNestingDepth, ErrStdlib)) + + return + } + + w.RawByte('{') + + if len(s) == 0 { + w.RawByte('}') + + return + } + + s[0].marshalJSON(w, depth) + + for i := 1; i < len(s); i++ { + w.RawByte(',') + s[i].marshalJSON(w, depth) + } + + 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, depth int) { + w.String(s.Key) + w.RawByte(':') + + // Recurse internally for nested ordered maps so the depth guard is not lost across + // the stdjson.Marshal boundary (which would reset it and re-enable stack overflow). + if nested, ok := s.Value.(MapSlice); ok { + nested.marshalObject(w, depth+1) + + return + } + + 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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go new file mode 100644 index 000000000..2f06b88e8 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package json + +import ( + "github.com/go-openapi/swag/jsonutils/adapters/ifaces" + "github.com/go-openapi/swag/pools" +) + +var ( + poolOfAdapters = pools.New[Adapter]() + poolOfWriters = pools.NewRedeemable[jwriter]() + poolOfLexers = pools.NewRedeemable[jlexer]() + poolOfReaders = pools.NewRedeemable[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.Borrow() +} + +// 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/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go new file mode 100644 index 000000000..0dec85425 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go @@ -0,0 +1,34 @@ +// 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, opts ...Option) { + t := reflect.TypeOf(Adapter{}) + var o options + o = buildOptions(o, opts) + + dispatcher.RegisterFor( + ifaces.RegistryEntry{ + Who: fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()), + What: ifaces.AllCapabilities, + Constructor: func() ifaces.Adapter { + a := BorrowAdapter() + a.options = o + + return a + }, + Support: support, + }) +} + +func support(_ ifaces.Capability, _ any) bool { + return true +} diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go new file mode 100644 index 000000000..c84e02cd8 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go @@ -0,0 +1,88 @@ +// 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 (w *jwriter) Reset() { + if w.buf != nil { + w.buf.Reset() + } + w.err = nil +} + +// SetErr records the first error encountered while building the JSON output. +func (w *jwriter) SetErr(err error) { + if w.err != nil { + return + } + w.err = err +} + +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 +} + +func (w *jwriter) setBuf() { + if w.buf != nil { + return + } + + buf := make([]byte, 0, sensibleBufferSize) + w.buf = bytes.NewBuffer(buf) +} diff --git a/constraint/vendor/github.com/go-openapi/swag/jsonutils/concat.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/concat.go new file mode 100644 index 000000000..2068503af --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/doc.go new file mode 100644 index 000000000..3926cc58d --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/json.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/json.go new file mode 100644 index 000000000..40753ce03 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go new file mode 100644 index 000000000..38dd3e244 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/jsonutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/jsonutils_iface.go new file mode 100644 index 000000000..7bd4105fa --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/loading/LICENSE b/constraint/vendor/github.com/go-openapi/swag/loading/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/loading/doc.go b/constraint/vendor/github.com/go-openapi/swag/loading/doc.go new file mode 100644 index 000000000..112c49968 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/loading/doc.go @@ -0,0 +1,29 @@ +// 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. +// +// # Security +// +// By default, the local loader reads any path the process can access, including absolute +// paths and "file://" URIs (for example "file:///etc/passwd"). Applications that pass +// untrusted input to [LoadFromFileOrHTTP], [JSONDoc] (or to downstream consumers such as +// go-openapi/loads) must confine local loading to a trusted directory. +// +// Use [WithRoot] to do so: it resolves every requested path relative to a chosen directory +// and rejects anything that escapes it, including via symlink. It is built on [os.Root] +// and is therefore safer than passing an [os.DirFS] to [WithFS], which does not block +// symlink escapes. +// +// Remote loading uses a standard [net/http] client. +// By default it follows redirects and performs no destination filtering — exactly like [net/http.DefaultClient]. +// +// A caller-controlled URL may therefore reach internal services or cloud metadata endpoints +// (server-side request forgery). +// +// This package does not, and should not, embed a network policy: +// when the URL may derive from untrusted input, supply a restricted client with +// [WithHTTPClient] whose transport rejects unwanted destinations at dial time — which also +// covers redirects and DNS rebinding. +// See the example on [LoadFromFileOrHTTP]. +package loading diff --git a/constraint/vendor/github.com/go-openapi/swag/loading/errors.go b/constraint/vendor/github.com/go-openapi/swag/loading/errors.go new file mode 100644 index 000000000..b3964289c --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/loading/json.go b/constraint/vendor/github.com/go-openapi/swag/loading/json.go new file mode 100644 index 000000000..59db12f5c --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/loading.go b/constraint/vendor/github.com/go-openapi/swag/loading/loading.go similarity index 53% rename from constraint/vendor/github.com/go-openapi/swag/loading.go rename to constraint/vendor/github.com/go-openapi/swag/loading/loading.go index 783442fdd..0b38ac1e3 100644 --- a/constraint/vendor/github.com/go-openapi/swag/loading.go +++ b/constraint/vendor/github.com/go-openapi/swag/loading/loading.go @@ -1,54 +1,30 @@ -// 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) +// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in. +// +// Security: by default a local path is read with no confinement, so a caller-controlled path +// (including a "file://" URI or an absolute path) may read any file the process can access. +// When the path may derive from untrusted input, confine local loading with [WithRoot]. +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 +57,15 @@ 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) { - if strings.HasPrefix(pth, "http") { +func LoadStrategy(pth string, local, remote func(string) ([]byte, error), opts ...Option) func(string) ([]byte, error) { + if hasHTTPScheme(pth) { return remote } + o := optionsWithDefaults(opts) + _, isEmbedFS := o.fs.(embed.FS) + // any loader backed by an fs.FS or an os.Root consumes forward-slash paths on every + // platform, so it must not go through the windows-native file:// preprocessing below. + isFSBacked := o.fs != nil || o.root != "" return func(p string) ([]byte, error) { upth, err := url.PathUnescape(p) @@ -92,19 +73,25 @@ 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 || isFSBacked || 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 isEmbedFS { + // embed.FS always uses "/" as separator, even on windows, and rejects leading "./" or "/". + return local(strings.TrimLeft(filepath.ToSlash(cpth), "./")) // remove invalid leading characters for embed FS + } - if runtime.GOOS != "windows" { - // crude processing: this leaves full URIs with a host with a (mostly) unexpected result - upth = strings.TrimPrefix(upth, `file://`) + if isFSBacked { + // other fs.FS (e.g. os.DirFS) and os.Root loaders also use "/" on every platform. + // Escaping paths (absolute, "..", escaping symlinks) are rejected by the loader, not rewritten here. + return local(filepath.ToSlash(cpth)) + } - 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 +126,44 @@ func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(s } } -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { +// hasHTTPScheme reports whether pth is an absolute URL with an http or https scheme, +// selecting the remote loader. The comparison is case-insensitive, as URL schemes are. +// +// Requiring the "://" separator (rather than a bare "http" prefix) avoids misrouting a +// local file whose name merely starts with "http" (e.g. "httpbin.json") to the remote loader. +func hasHTTPScheme(pth string) bool { + for _, scheme := range [...]string{"http://", "https://"} { + if len(pth) >= len(scheme) && strings.EqualFold(pth[:len(scheme)], scheme) { + return true + } + } + + return false +} + +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) } @@ -168,7 +180,7 @@ func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { } if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) + return nil, fmt.Errorf("could not access document at %q [%s]: %w", path, resp.Status, ErrLoader) } return io.ReadAll(resp.Body) diff --git a/constraint/vendor/github.com/go-openapi/swag/loading/options.go b/constraint/vendor/github.com/go-openapi/swag/loading/options.go new file mode 100644 index 000000000..2c1282317 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/loading/options.go @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package loading + +import ( + "errors" + "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 + root string // when non-empty, local reads are confined to this directory via os.Root + } + + options struct { + httpOptions + fileOptions + } +) + +func (fo fileOptions) ReadFileFunc() func(string) ([]byte, error) { + if fo.root != "" { + root := fo.root + + return func(name string) ([]byte, error) { + r, err := os.OpenRoot(root) + if err != nil { + return nil, errors.Join(err, ErrLoader) + } + defer func() { _ = r.Close() }() + + return r.ReadFile(name) + } + } + + 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. +// +// WithFS and [WithRoot] are mutually exclusive: the last one applied wins. +// +// Security note: a file system built from [os.DirFS] confines paths but does NOT protect +// against symlinks that escape the root. To load from a directory derived from untrusted +// input, prefer [WithRoot], which is symlink-escape resistant. +func WithFS(filesystem fs.FS) Option { + return func(o *options) { + o.root = "" // last-wins vs WithRoot + if rfs, ok := filesystem.(fs.ReadFileFS); ok { + o.fs = rfs + + return + } + o.fs = readFileFS{FS: filesystem} + } +} + +// WithRoot confines local file loading to dir. +// +// Every requested path is resolved relative to dir, and any path that would escape dir — +// whether through an absolute path, ".." traversal, or a symlink pointing outside dir — is +// rejected. This is built on [os.Root] and is therefore resistant to the symlink escapes +// that a plain [os.DirFS] does not prevent. +// +// WithRoot is the recommended option when loading specs from a location derived from +// untrusted input. It applies to local loading only and has no effect on remote +// (http/https) loading. WithRoot and [WithFS] are mutually exclusive: the last one applied +// wins. +// +// Note: [os.Root] confines path resolution but does not, by itself, protect against +// traversal of mount/bind boundaries, /proc special files, or device files. Point WithRoot +// at a directory that holds only the documents you intend to expose. +func WithRoot(dir string) Option { + return func(o *options) { + o.root = dir + o.fs = nil // last-wins vs WithFS + } +} + +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/constraint/vendor/github.com/go-openapi/swag/loading/yaml.go b/constraint/vendor/github.com/go-openapi/swag/loading/yaml.go new file mode 100644 index 000000000..3ebb53668 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/loading_iface.go b/constraint/vendor/github.com/go-openapi/swag/loading_iface.go new file mode 100644 index 000000000..78dadfccd --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/loading_iface.go @@ -0,0 +1,93 @@ +// 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 { + const defaultOptions = 3 + o := make([]loading.Option, 0, defaultOptions+len(opts)) + o = append(o, []loading.Option{ + loading.WithTimeout(LoadHTTPTimeout), + loading.WithBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword), + loading.WithCustomHeaders(LoadHTTPCustomHeaders), + }...) + o = append(o, opts...) + + return o +} diff --git a/constraint/vendor/github.com/go-openapi/swag/BENCHMARK.md b/constraint/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md similarity index 53% rename from constraint/vendor/github.com/go-openapi/swag/BENCHMARK.md rename to constraint/vendor/github.com/go-openapi/swag/mangling/BENCHMARK.md index e7f28ed6b..abe6e9533 100644 --- a/constraint/vendor/github.com/go-openapi/swag/BENCHMARK.md +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/LICENSE b/constraint/vendor/github.com/go-openapi/swag/mangling/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/doc.go b/constraint/vendor/github.com/go-openapi/swag/mangling/doc.go new file mode 100644 index 000000000..ce0d89048 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/initialism_index.go b/constraint/vendor/github.com/go-openapi/swag/mangling/initialism_index.go new file mode 100644 index 000000000..e5b70c149 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/name_lexem.go b/constraint/vendor/github.com/go-openapi/swag/mangling/name_lexem.go new file mode 100644 index 000000000..bc837e3b9 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/name_mangler.go b/constraint/vendor/github.com/go-openapi/swag/mangling/name_mangler.go new file mode 100644 index 000000000..da685681d --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/options.go b/constraint/vendor/github.com/go-openapi/swag/mangling/options.go new file mode 100644 index 000000000..3c92b2f18 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/pools.go b/constraint/vendor/github.com/go-openapi/swag/mangling/pools.go new file mode 100644 index 000000000..f81043514 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/split.go b/constraint/vendor/github.com/go-openapi/swag/mangling/split.go new file mode 100644 index 000000000..ed12ea256 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/string_bytes.go b/constraint/vendor/github.com/go-openapi/swag/mangling/string_bytes.go similarity index 60% rename from constraint/vendor/github.com/go-openapi/swag/string_bytes.go rename to constraint/vendor/github.com/go-openapi/swag/mangling/string_bytes.go index 90745d5ca..28daaf72b 100644 --- a/constraint/vendor/github.com/go-openapi/swag/string_bytes.go +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling/util.go b/constraint/vendor/github.com/go-openapi/swag/mangling/util.go new file mode 100644 index 000000000..0636417e3 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/mangling_iface.go b/constraint/vendor/github.com/go-openapi/swag/mangling_iface.go new file mode 100644 index 000000000..98b9a9992 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/name_lexem.go b/constraint/vendor/github.com/go-openapi/swag/name_lexem.go deleted file mode 100644 index 8bb64ac32..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/net.go b/constraint/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 821235f84..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/netutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/netutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/netutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/netutils/doc.go new file mode 100644 index 000000000..74282f8e5 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/netutils/net.go b/constraint/vendor/github.com/go-openapi/swag/netutils/net.go new file mode 100644 index 000000000..82a1544af --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/netutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/netutils_iface.go new file mode 100644 index 000000000..d658de25b --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/pools/LICENSE b/constraint/vendor/github.com/go-openapi/swag/pools/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/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/constraint/vendor/github.com/go-openapi/swag/pools/README.md b/constraint/vendor/github.com/go-openapi/swag/pools/README.md new file mode 100644 index 000000000..1966461cb --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/README.md @@ -0,0 +1 @@ +# pools diff --git a/constraint/vendor/github.com/go-openapi/swag/pools/debug.go b/constraint/vendor/github.com/go-openapi/swag/pools/debug.go new file mode 100644 index 000000000..94415e989 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/debug.go @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package pools + +// TB is the subset of [testing.TB] used by [AssertNoLeaks]. +// +// It is satisfied by *[testing.T] and *[testing.B]. +// +// A local interface is used (rather than importing "testing") so that the +// release build does not pull the testing package — and its flags — into +// production binaries. +type TB interface { + Helper() + Errorf(format string, args ...any) + Logf(format string, args ...any) +} diff --git a/constraint/vendor/github.com/go-openapi/swag/pools/debug_off.go b/constraint/vendor/github.com/go-openapi/swag/pools/debug_off.go new file mode 100644 index 000000000..9163d6d60 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/debug_off.go @@ -0,0 +1,51 @@ +//go:build !poolsdebug + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package pools + +// This is the release implementation of the pool instrumentation: it does +// nothing. +// +// tracker is an empty struct, so it adds no field to the pool types and its +// methods inline away to nothing. +// +// Build with -tags poolsdebug to get the instrumented variant (see +// debug_on.go). + +// debugBuild reports whether the pool instrumentation is compiled in (the +// poolsdebug tag). +const debugBuild = false + +// DebugBuild reports whether the pool instrumentation is compiled in (the +// poolsdebug build tag). +// +// It lets a test that must run in both modes skip the parts that are invalid +// under instrumentation — e.g. an allocation-count assertion, since the +// instrumented build allocates a per-borrow tracker. +const DebugBuild = debugBuild + +type tracker[T any] struct{} + +func (tracker[T]) register() {} + +func (tracker[T]) onBorrow(*T) {} + +func (tracker[T]) onRedeem(*T) {} + +func (tracker[T]) borrowRedeemer(_ *T, cached func()) func() { return cached } + +// AssertNoLeaks reports whether every borrowed object has been redeemed across +// all pools. +// +// It is only meaningful in the instrumented build (-tags poolsdebug). +// +// In a release build it is a no-op that always reports true, so the same test +// can run in both modes. +func AssertNoLeaks(TB) bool { return true } + +// ResetTracking clears all recorded borrow/redeem tracking. +// +// This is a no-op in a release build. +func ResetTracking() {} diff --git a/constraint/vendor/github.com/go-openapi/swag/pools/debug_on.go b/constraint/vendor/github.com/go-openapi/swag/pools/debug_on.go new file mode 100644 index 000000000..64ccc57d3 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/debug_on.go @@ -0,0 +1,237 @@ +//go:build poolsdebug + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package pools + +import ( + "fmt" + "runtime" + "sync" +) + +// This is the instrumented implementation of the pool tracking, enabled with +// -tags poolsdebug. +// +// Each pool carries a tracker that records, per recycled pointer, whether it is +// currently borrowed or redeemed, together with the call sites of the last +// borrow and redeem. +// It panics loudly (with those call sites) when it detects misuse: +// +// - a double redeem (the same object returned to the pool twice — corrupts sync.Pool); +// - for the redeemable pools, a redeem of a stale borrow (the slot was re-borrowed since — the +// ABA case the production atomic guard cannot catch), thanks to a per-borrow generation; +// - a redeem of an object the pool never handed out; +// - a borrow of an object still checked out (a symptom of an earlier double-Put). +// +// Borrowed-but-never-redeemed objects (leaks) are reported by [AssertNoLeaks]. + +// debugBuild reports whether the pool instrumentation is compiled in (the +// poolsdebug tag). +const debugBuild = true + +// DebugBuild reports whether the pool instrumentation is compiled in (the +// poolsdebug build tag). +// +// See the release-build doc for usage. +const DebugBuild = debugBuild + +type trackStatus uint8 + +const ( + trackBorrowed trackStatus = iota + 1 + trackRedeemed +) + +type trackEntry struct { + status trackStatus + gen uint64 // identifies the current borrow, to detect a redeem racing a re-borrow (ABA) + borrowedAt string + redeemedAt string +} + +type tracker[T any] struct { + mu sync.Mutex + entries map[*T]*trackEntry + nextGen uint64 +} + +func (t *tracker[T]) register() { + t.mu.Lock() + if t.entries == nil { + t.entries = make(map[*T]*trackEntry) + } + t.mu.Unlock() + + registerLeakChecker(t) +} + +// markBorrow records a borrow of ptr and returns its generation. +// +// Caller must hold no lock. +func (t *tracker[T]) markBorrow(ptr *T, site string) uint64 { + t.mu.Lock() + defer t.mu.Unlock() + + e := t.entries[ptr] + if e == nil { + e = &trackEntry{} + t.entries[ptr] = e + } else if e.status == trackBorrowed { + panic(fmt.Sprintf( + "pools: borrow of an object still checked out (borrowed at %s); "+ + "this usually means it was redeemed twice earlier", e.borrowedAt)) + } + + t.nextGen++ + e.status = trackBorrowed + e.gen = t.nextGen + e.borrowedAt = site + + return t.nextGen +} + +// markRedeem validates and records a redeem of ptr. gen is the borrow +// generation the caller is redeeming, or 0 to skip the ABA check (plain +// Pool[T], which has no per-borrow token). +func (t *tracker[T]) markRedeem(ptr *T, gen uint64, site string) { + t.mu.Lock() + defer t.mu.Unlock() + + e := t.entries[ptr] + switch { + case e == nil: + panic("pools: redeem of an object this pool never handed out") + case e.status != trackBorrowed: + panic(fmt.Sprintf("pools: double redeem (first redeemed at %s)", e.redeemedAt)) + case gen != 0 && e.gen != gen: + panic(fmt.Sprintf( + "pools: redeem of a stale borrow (the slot was re-borrowed at %s since this borrow); "+ + "a redeem is racing a re-borrow of the same slot (ABA)", e.borrowedAt)) + } + + e.status = trackRedeemed + e.redeemedAt = site +} + +const stackOffset = 3 + +func (t *tracker[T]) onBorrow(ptr *T) { + t.markBorrow(ptr, caller(stackOffset)) +} + +func (t *tracker[T]) onRedeem(ptr *T) { + t.markRedeem(ptr, 0, caller(stackOffset)) +} + +// borrowRedeemer records the borrow and returns a generation-stamped redeemer +// that validates the redeem (catching double-redeem and ABA) before delegating +// to the cached redeemer. +func (t *tracker[T]) borrowRedeemer(ptr *T, cached func()) func() { + gen := t.markBorrow(ptr, caller(stackOffset)) + + return func() { + t.markRedeem(ptr, gen, caller(stackOffset-1)) + cached() + } +} + +func (t *tracker[T]) checkLeaks(tb TB) bool { + t.mu.Lock() + defer t.mu.Unlock() + + ok := true + for _, e := range t.entries { + if e.status != trackRedeemed { + tb.Logf("pools: object borrowed but never redeemed (borrowed at %s)", e.borrowedAt) + ok = false + } + } + + return ok +} + +func (t *tracker[T]) resetTracking() { + t.mu.Lock() + t.entries = make(map[*T]*trackEntry) + t.nextGen = 0 + t.mu.Unlock() +} + +// leakChecker is the build-erased view of a tracker that the global registry +// holds, so trackers of different element types can be checked uniformly. +type leakChecker interface { + checkLeaks(tb TB) bool + resetTracking() +} + +var ( + registryMu sync.Mutex + registry []leakChecker +) + +func registerLeakChecker(c leakChecker) { + registryMu.Lock() + registry = append(registry, c) + registryMu.Unlock() +} + +// AssertNoLeaks reports whether every borrowed object has been redeemed across +// all pools created so far. +// +// It logs the borrow call site of each leaked object and fails tb when any are +// found. +// +// Typical use, with [ResetTracking] to isolate the test from earlier ones: +// +// func TestX(t *testing.T) { +// pools.ResetTracking() +// t.Cleanup(func() { pools.AssertNoLeaks(t) }) +// // ... exercise code that borrows/redeems ... +// } +func AssertNoLeaks(tb TB) bool { + tb.Helper() + registryMu.Lock() + defer registryMu.Unlock() + + ok := true + for _, c := range registry { + if !c.checkLeaks(tb) { + ok = false + } + } + if !ok { + tb.Errorf("pools: leaked pooled objects detected (borrowed but never redeemed)") + } + + return ok +} + +// ResetTracking clears all recorded borrow/redeem tracking across every pool. +// +// Call it at the start of a test so leaks from earlier tests are not attributed +// to it. +func ResetTracking() { + registryMu.Lock() + defer registryMu.Unlock() + + for _, c := range registry { + c.resetTracking() + } +} + +// caller returns "file:line" of the frame skip levels above caller itself. +func caller(skip int) string { + pc, _, _, ok := runtime.Caller(skip) + if !ok { + return "unknown" + } + fn := runtime.FuncForPC(pc) + if fn == nil { + return "unknown" + } + file, line := fn.FileLine(pc) + + return fmt.Sprintf("%s:%d", file, line) +} diff --git a/constraint/vendor/github.com/go-openapi/swag/pools/doc.go b/constraint/vendor/github.com/go-openapi/swag/pools/doc.go new file mode 100644 index 000000000..395c24d29 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/doc.go @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +// Package pools provide utilities to recycle allocated objects. +// +// This package provides: +// +// - a generic [Pool] type that wraps [sync.Pool], +// - a [PoolRedeemable] variant that hands out a cached redeem closure, +// - a [PoolSlice] for recycling slices without juggling pointers. +// +// # Debug build +// +// Building with the "poolsdebug" tag (go test -tags poolsdebug ./...) turns on +// instrumentation that tracks every borrow and redeem and panics on misuse: +// +// - double redeem (including the A -> B -> A case for the redeemable pools), +// - redeem of a foreign object, +// - borrow of an object still checked out +// +// It reports the offending call sites. +// +// [AssertNoLeaks] then reports any object borrowed but never redeemed. +// +// The instrumentation is a no-op with zero overhead when the tag is absent. +package pools diff --git a/constraint/vendor/github.com/go-openapi/swag/pools/pools.go b/constraint/vendor/github.com/go-openapi/swag/pools/pools.go new file mode 100644 index 000000000..d78ea5790 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/pools/pools.go @@ -0,0 +1,410 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package pools + +import ( + "iter" + "slices" + "sync" + "sync/atomic" +) + +// Resettable is an interface for types that want to recycle a clean instance +// from a [Pool]. +// +// When T (or rather *T) implements [Resettable], the pool calls Reset on an +// instance both when it is redeemed and when it is borrowed: +// +// - on redeem, so that no references held by the instance are retained while it sits idle in the +// pool (which would pin a reference graph alive across a GC cycle); +// - on borrow, so that the next borrower receives a clean object regardless of how the instance +// reached the pool. +// +// Reset must be safe to call more than once on the same instance (it runs at +// least twice per cycle). +type Resettable interface { + Reset() +} + +// resetIfResettable calls Reset on v when *T implements [Resettable]. +func resetIfResettable[T any](v *T) { + if r, ok := any(v).(Resettable); ok { + r.Reset() + } +} + +// borrow state of a [redeemable] wrapper, used to detect double-redeem. +const ( + stateIdle uint32 = iota // sitting in the pool (or freshly created), not checked out + stateBorrowed // checked out by a borrower +) + +type redeemable[T any] struct { + inner *T + redeemer func() + // state guards against a double-redeem (the same wrapper Put into the pool + // twice, which would let one object be handed to two borrowers). + // + // It is set to stateBorrowed on borrow and atomically flipped back to + // stateIdle on redeem; a redeem that finds it already idle panics. + state atomic.Uint32 +} + +// redeemPanic is the message raised when a slot is redeemed while already idle. +const redeemPanic = "pools: " + + "double redeem detected (object already returned to the pool); " + + "a borrowed object must be redeemed exactly once" + +// Pool wraps a [sync.Pool] to make it available for any type. +// +// T must be the value type of the pooled object (e.g. Pool[bytes.Buffer]): +// [Pool.Borrow] returns a *T. Using a pointer type as T (e.g. +// Pool[*bytes.Buffer]) would yield a **T and is almost certainly a mistake. +type Pool[T any] struct { + pool sync.Pool + tracker tracker[T] // empty (zero-cost) unless built with the poolsdebug tag +} + +// PoolRedeemable wraps a [sync.Pool] to make it available for any type. +// +// It differs from [Pool] in the way objects are redeemed to the pool: borrowing +// also yields a cached redeem closure, so no closure is allocated at redeem +// time. +type PoolRedeemable[T any] struct { + pool sync.Pool + tracker tracker[redeemable[T]] // empty (zero-cost) unless built with the poolsdebug tag +} + +// New builds a new [Pool] to recycle allocations of type T explicitly using +// [Pool.Redeem] and the allocated pointer. +// +// Freshly allocated instances of type T are set to their zero value; like +// recycled instances they are reset (if [Resettable]) when borrowed, so +// [Pool.Borrow] always yields a clean object. +func New[T any]() *Pool[T] { + p := &Pool[T]{} + p.pool = sync.Pool{ + New: func() any { + return new(T) + }, + } + p.tracker.register() + + return p +} + +// NewRedeemable builds a new redeemable [Pool] to recycle allocations of type +// T, and use the inner redeemer to relinquish objects to the pool. +func NewRedeemable[T any]() *PoolRedeemable[T] { + p := &PoolRedeemable[T]{} + p.pool = sync.Pool{ + New: func() any { + r := &redeemable[T]{inner: new(T)} + r.redeemer = func() { + if !r.state.CompareAndSwap(stateBorrowed, stateIdle) { + panic(redeemPanic) + } + resetIfResettable(r.inner) + p.pool.Put(r) + } + + return r + }, + } + p.tracker.register() + + return p +} + +// Borrow an instance from the pool. +// +// If the type implements [Resettable], the returned instance is reset before +// being handed out, so it is always clean. +func (p *Pool[T]) Borrow() *T { + target := p.pool.Get().(*T) + resetIfResettable(target) + p.tracker.onBorrow(target) + + return target +} + +// Redeem a borrowed instance to the pool. +// +// A nil pointer is ignored (it would otherwise corrupt the pool: a typed-nil +// boxed into an interface is not the nil interface that [sync.Pool.Put] skips). +// +// The instance is reset (if it implements [Resettable]) before being returned +// to the pool. +// After calling Redeem, the caller must drop its reference to ptr: continuing +// to use it is a use-after-redeem bug. +// +// Unlike [PoolRedeemable], this plain pool holds no per-object state, so it +// cannot detect a double-redeem of the same pointer (which corrupts the pool). +// +// Prefer [PoolRedeemable] when you want that guard, or the debug build for full +// tracking. +func (p *Pool[T]) Redeem(ptr *T) { + if ptr == nil { + return + } + p.tracker.onRedeem(ptr) + resetIfResettable(ptr) + p.pool.Put(ptr) +} + +// BorrowWithRedeem borrows an instance from the pool and provides the +// corresponding redeem function. +// +// This is useful for instance to use with defer. +// +// The instance is reset (if it implements [Resettable]) both when borrowed and +// when the returned redeem closure is called. +// After calling the redeem closure, the caller must drop its reference to the +// returned instance. +// +// Calling the redeem closure more than once panics (see [redeemable.state]): a +// borrowed instance must be redeemed exactly once. +func (p *PoolRedeemable[T]) BorrowWithRedeem() (*T, func()) { + container := p.pool.Get().(*redeemable[T]) + container.state.Store(stateBorrowed) + resetIfResettable(container.inner) + + // In release builds borrowRedeemer returns container.redeemer unchanged (zero + // cost). + // Under the poolsdebug tag it returns a generation-stamped wrapper that tracks + // the borrow and detects double-redeem (incl. + // + // ABA), foreign-redeem and leaks. + return container.inner, p.tracker.borrowRedeemer(container, container.redeemer) +} + +// Slice is a struct that wraps a slice []T. +// +// This is useful to borrow and redeem slices from a pool, without having to +// constantly manipulate pointers to the slice. +// +// The wrapper holds the authoritative slice header. +// +// Its mutating methods ([Slice.Append], [Slice.Concat], [Slice.Grow]) return +// the current backing slice for convenience, so it reads as an idiomatic []T. +// +// But the returned slice is only a snapshot of the wrapper's state at that +// moment: if you keep it and grow it yourself with the builtin append and it +// reallocates, the new backing array lives only in your local copy and is NOT +// tracked by the wrapper — it will not be recycled when the wrapper is +// redeemed (and a later borrower would get the old, smaller array). +// +// Rule of thumb: it is fine to read or pass the returned []T to a consumer; but +// if you plan to grow the slice, keep calling the wrapper's methods so the +// growth is tracked and recycled. +type Slice[T any] struct { + length int + inner []T +} + +// Slice returns the inner slice. +// +// Treat the result as a read-only view (for ranging or passing to a consumer), +// valid until the next mutation or redeem. +// To grow or append, use the wrapper methods so the new backing array is +// tracked and recycled (see [Slice]). +func (s *Slice[T]) Slice() []T { + return s.inner +} + +// Grow the inner slice so it can accommodate at least size more elements +// without reallocating, and return the current backing slice. +// +// Growth is tracked by the wrapper, so the enlarged backing array is recycled +// on redeem. +// See [Slice] for the caveat about growing the returned slice yourself. +func (s *Slice[T]) Grow(size int) []T { + s.inner = slices.Grow(s.inner, size) + + return s.inner +} + +func (s *Slice[T]) Len() int { + return len(s.inner) +} + +func (s *Slice[T]) Cap() int { + return cap(s.inner) +} + +// Append elements to the inner slice and return the current backing slice. +// +// This should be preferred to the append builtin if you plan that the slice will +// grow and you want the newly allocated space to be tracked and recycled. +// See [Slice] for the caveat about growing the returned slice yourself. +func (s *Slice[T]) Append(elems ...T) []T { + s.inner = append(s.inner, elems...) + + return s.inner +} + +// Concat another slice to the inner slice and return the current backing slice. +// +// Unlike [slices.Concat], this reuses the inner slice's capacity instead of +// always allocating a fresh backing array. +// See [Slice] for the caveat about growing the returned slice yourself. +func (s *Slice[T]) Concat(slice []T) []T { + s.inner = append(s.inner, slice...) + + return s.inner +} + +// IndexedElems iterates over the inner slice. +func (s *Slice[T]) IndexedElems() iter.Seq2[int, T] { + return func(yield func(int, T) bool) { + for i, elem := range s.inner { + if !yield(i, elem) { + return + } + } + } +} + +// Reset the inner slice to its configured initial length, keeping allocated +// capacity. +// +// All elements are zeroed, so the pool never retains stale element references +// (which would keep a referenced graph alive for slices of pointers) and so a +// [WithLength] slice is handed out clean rather than carrying data from a +// previous borrower. +func (s *Slice[T]) Reset() { + clear(s.inner) + if s.length > cap(s.inner) { + s.inner = slices.Grow(s.inner[:0], s.length) + } + s.inner = s.inner[:s.length] +} + +// Clip removes unused capacity from the inner slice. +func (s *Slice[T]) Clip() { + s.inner = slices.Clip(s.inner) +} + +// resetWithCapacity discards the current backing array and replaces it with a +// fresh one of the configured length and the given capacity. +// +// It is used by a capacity-capped pool to stop recycling an oversized backing +// array (the old array is left for the GC). +func (s *Slice[T]) resetWithCapacity(capacity int) { + s.inner = make([]T, s.length, max(s.length, capacity)) +} + +// PoolSlice is a pool of [Slice[T]]. +// +// [PoolSlice.BorrowWithRedeem] will return an empty inner slice by default. +// This default may be altered using [WithMinimumCapacity]. +// +// Use [PoolSlice.BorrowWithSizeAndRedeem] or [Slice.Grow] to grow the capacity +// of the inner slice. +type PoolSlice[T any] struct { + // redeemable is held as an unexported field rather than embedded, so the + // underlying [PoolRedeemable] and its [sync.Pool] are not part of PoolSlice's + // public surface. + redeemable *PoolRedeemable[Slice[T]] +} + +// PoolSliceOption alters the default settings to allocate new pooled slices +type PoolSliceOption func(*poolSliceOptions) + +type poolSliceOptions struct { + minCapacity int + length int + maxCapacity int +} + +func WithMinimumCapacity(size int) PoolSliceOption { + return func(o *poolSliceOptions) { + o.minCapacity = size + } +} + +// WithMaxCapacity bounds the capacity of recycled slices. +// +// When a borrowed slice has grown past size at redeem time, its (oversized) +// backing array is discarded and replaced with a fresh one sized to the minimum +// capacity, instead of being recycled. +// +// This stops the pool from accumulating large backing arrays after an +// occasional large request, keeping the steady-state memory bounded. +// +// The trade-off: a workload that genuinely needs slices larger than size will +// reallocate on every cycle. +// Set size from the high-water mark you actually expect, not below it. +// A size of 0 (the default) means no cap: grown slices are recycled as-is. +func WithMaxCapacity(size int) PoolSliceOption { + return func(o *poolSliceOptions) { + o.maxCapacity = size + } +} + +// WithLength ensures that the borrowed slices have a fixed given initial +// length. +// +// By default, the borrowed slices are reset to length 0. +func WithLength(size int) PoolSliceOption { + return func(o *poolSliceOptions) { + o.length = size + } +} + +// NewPoolSlice builds a pool to recycle slices of type []T. +func NewPoolSlice[T any](opts ...PoolSliceOption) *PoolSlice[T] { + var o poolSliceOptions + for _, apply := range opts { + apply(&o) + } + + rp := &PoolRedeemable[Slice[T]]{} + rp.pool = sync.Pool{ + New: func() any { + s := &redeemable[Slice[T]]{ + inner: &Slice[T]{ + length: o.length, + inner: make([]T, o.length, max(o.length, o.minCapacity)), + }, + } + + s.redeemer = func() { + if !s.state.CompareAndSwap(stateBorrowed, stateIdle) { + panic(redeemPanic) + } + if o.maxCapacity > 0 && s.inner.Cap() > o.maxCapacity { + s.inner.resetWithCapacity(o.minCapacity) + } else { + s.inner.Reset() + } + rp.pool.Put(s) + } + + return s + }, + } + rp.tracker.register() + + return &PoolSlice[T]{redeemable: rp} +} + +// BorrowWithRedeem returns the slice wrapper and the redeem closure to +// relinquish the allocated wrapper. +// +// The wrapper is reset (elements zeroed, length restored) both on borrow and +// when the redeem closure is called. +// Calling the redeem closure more than once panics. +func (p *PoolSlice[T]) BorrowWithRedeem() (*Slice[T], func()) { + return p.redeemable.BorrowWithRedeem() +} + +// BorrowWithSizeAndRedeem borrows a slice []T from the pool and ensures that +// its capacity is at least the provided size. +func (p *PoolSlice[T]) BorrowWithSizeAndRedeem(size int) (*Slice[T], func()) { + s, redeem := p.BorrowWithRedeem() + s.Grow(size) + + return s, redeem +} diff --git a/constraint/vendor/github.com/go-openapi/swag/split.go b/constraint/vendor/github.com/go-openapi/swag/split.go deleted file mode 100644 index 274727a86..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/stringutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/stringutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go b/constraint/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go new file mode 100644 index 000000000..28056ad25 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/stringutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/stringutils/doc.go new file mode 100644 index 000000000..c6d17a116 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/stringutils/strings.go b/constraint/vendor/github.com/go-openapi/swag/stringutils/strings.go new file mode 100644 index 000000000..cd792b7d0 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/stringutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/stringutils_iface.go new file mode 100644 index 000000000..dbfa48484 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/typeutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/typeutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/typeutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/typeutils/doc.go new file mode 100644 index 000000000..66bed20df --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/typeutils/types.go b/constraint/vendor/github.com/go-openapi/swag/typeutils/types.go new file mode 100644 index 000000000..55487a673 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/typeutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/typeutils_iface.go new file mode 100644 index 000000000..b63813ea4 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/util.go b/constraint/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 5051401c4..000000000 --- a/constraint/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/constraint/vendor/github.com/go-openapi/swag/yaml.go b/constraint/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index f59e02593..000000000 --- a/constraint/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" - "errors" - "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, errors.New("only YAML documents that are objects are supported") - } - 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", root.Kind) - } -} - -func yamlDocument(node *yaml.Node) (interface{}, error) { - if len(node.Content) != 1 { - return nil, fmt.Errorf("unexpected YAML Document node content length: %d", len(node.Content)) - } - return yamlNode(node.Content[0]) -} - -func yamlMapping(node *yaml.Node) (interface{}, error) { - m := make(JSONMapSlice, len(node.Content)/2) - - 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", err) - } - 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", k, err) - } - 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", err) - } - 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", node.Value, err) - } - 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", node.Value, err) - } - 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", node.Value, err) - } - 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", node.LongTag()) - } -} - -func yamlStringScalarC(node *yaml.Node) (string, error) { - if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q", node.Kind) - } - switch node.LongTag() { - case yamlStringScalar, yamlIntScalar, yamlFloatScalar: - return node.Value, nil - default: - return "", fmt.Errorf("YAML tag %q is not supported as map key", node.LongTag()) - } -} - -// 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", val) - } -} - -// 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", k) - } - } - - 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/constraint/vendor/github.com/go-openapi/swag/yamlutils/LICENSE b/constraint/vendor/github.com/go-openapi/swag/yamlutils/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/yamlutils/doc.go b/constraint/vendor/github.com/go-openapi/swag/yamlutils/doc.go new file mode 100644 index 000000000..7bb92a82f --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/yamlutils/errors.go b/constraint/vendor/github.com/go-openapi/swag/yamlutils/errors.go new file mode 100644 index 000000000..e87bc5e8b --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go b/constraint/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go new file mode 100644 index 000000000..24d951f8d --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go @@ -0,0 +1,335 @@ +// 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, 1) + 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 { + return s.unmarshalYAML(newYAMLWalker(), node, 0) +} + +// unmarshalYAML builds the slice from a [yaml.Node], tracking the recursion depth (against +// stack-overflow) and threading the [yamlWalker] so anchor/alias expansion stays bounded +// across the whole document. +func (s *YAMLMapSlice) unmarshalYAML(w *yamlWalker, node *yaml.Node, depth int) error { + if depth > defaultMaxNestingDepth { + return errMaxNestingDepth + } + + 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 { + if err := w.account(); err != nil { // account the key node + return err + } + + 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 := w.node(node.Content[i+1], depth+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, depth int) (*yaml.Node, error) { + if depth > defaultMaxNestingDepth { + return nil, errMaxNestingDepth + } + + if typeutils.IsNil(item) { + return &yaml.Node{ + Kind: yaml.ScalarNode, + Value: "null", + }, nil + } + + switch val := item.(type) { + case ifaces.Ordered: + return orderedYAML(val, depth) + + 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, depth+1) + 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], depth+1) + 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, depth int) (*yaml.Node, error) { + var n yaml.Node + n.Kind = yaml.MappingNode + for key, value := range val.OrderedItems() { + childNode, err := json2yaml(value, depth+1) + 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/constraint/vendor/github.com/go-openapi/swag/yamlutils/yaml.go b/constraint/vendor/github.com/go-openapi/swag/yamlutils/yaml.go new file mode 100644 index 000000000..d4b5335f6 --- /dev/null +++ b/constraint/vendor/github.com/go-openapi/swag/yamlutils/yaml.go @@ -0,0 +1,328 @@ +// 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" +) + +// defaultMaxNestingDepth caps the recursion depth of the YAML<->JSON transforms to +// guard against stack-overflow on deeply nested (possibly adversarial) input. +// +// It matches the limit enforced by go.yaml.in/yaml/v3's own parser and by +// encoding/json's decoder. +const defaultMaxNestingDepth = 10000 + +// Bounds on YAML anchor/alias expansion. +// +// go.yaml.in/yaml/v3 enforces these when decoding into Go values, but that guard is +// coupled to the library's own tree walk: when we decode into a low-level [yaml.Node] +// (to preserve key order) and expand aliases ourselves in [yamlWalker.node], we bypass +// it. We therefore reproduce it here, with the same constants and ratio schedule as the +// library's decoder (see go.yaml.in/yaml/v3 decode.go, "excessive aliasing"). +const ( + aliasCountThreshold = 100 + decodeCountThreshold = 1000 + + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion. + aliasRatioRangeLow = 400000 + // 4,000,000 decode operations is ~5MB of dense object declarations. + aliasRatioRangeHigh = 4000000 + aliasRatioRange = float64(aliasRatioRangeHigh - aliasRatioRangeLow) + + // tolerated share of alias-driven decodes: from aliasRatioSmall (small/medium documents) + // down to aliasRatioLarge (very large ones), interpolated with slope aliasRatioSlope. + aliasRatioSmall = 0.99 + aliasRatioLarge = 0.10 + aliasRatioSlope = aliasRatioSmall - aliasRatioLarge +) + +var ( + // errMaxNestingDepth is returned when a document nests deeper than [defaultMaxNestingDepth]. + errMaxNestingDepth = fmt.Errorf("maximum nesting depth of %d exceeded: %w", defaultMaxNestingDepth, ErrYAML) + + // errExcessiveAliasing is returned when anchor/alias expansion is disproportionate to the + // size of the document, i.e. an "alias bomb". + errExcessiveAliasing = fmt.Errorf("document contains excessive aliasing: %w", ErrYAML) +) + +// allowedAliasRatio scales the tolerated share of alias-driven decode operations from 99% +// for small-to-medium documents down to 10% for very large ones, mirroring go.yaml.in/yaml/v3. +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= aliasRatioRangeLow: + return aliasRatioSmall + case decodeCount >= aliasRatioRangeHigh: + return aliasRatioLarge + default: + return aliasRatioSmall - aliasRatioSlope*(float64(decodeCount-aliasRatioRangeLow)/aliasRatioRange) + } +} + +// yamlWalker carries the state needed to bound a single YAML-tree traversal: +// anchor/alias expansion accounting and cycle detection. +// +// A fresh walker is created per top-level conversion; it is threaded (not copied) through +// the whole recursive walk so its counters accumulate across the entire document. +type yamlWalker struct { + decodeCount int + aliasCount int + aliasDepth int + aliases map[*yaml.Node]bool // anchors currently being expanded, for cycle detection +} + +func newYAMLWalker() *yamlWalker { + return &yamlWalker{aliases: make(map[*yaml.Node]bool)} +} + +// account records one processed node and fails if alias expansion has become excessive. +func (w *yamlWalker) account() error { + w.decodeCount++ + if w.aliasDepth > 0 { + w.aliasCount++ + } + + if w.aliasCount > aliasCountThreshold && + w.decodeCount > decodeCountThreshold && + float64(w.aliasCount)/float64(w.decodeCount) > allowedAliasRatio(w.decodeCount) { + return errExcessiveAliasing + } + + return nil +} + +// 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, 0) + 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 (w *yamlWalker) node(root *yaml.Node, depth int) (any, error) { + if depth > defaultMaxNestingDepth { + return nil, errMaxNestingDepth + } + if err := w.account(); err != nil { + return nil, err + } + + switch root.Kind { + case yaml.DocumentNode: + return w.document(root, depth) + case yaml.SequenceNode: + return w.sequence(root, depth) + case yaml.MappingNode: + return w.mapping(root, depth) + case yaml.ScalarNode: + return yamlScalar(root) + case yaml.AliasNode: + return w.alias(root, depth) + default: + return nil, fmt.Errorf("unsupported YAML node type: %v: %w", root.Kind, ErrYAML) + } +} + +// alias resolves an anchor reference, expanding the anchored subtree. It detects cycles +// (an anchor whose expansion transitively references itself) and accounts the expansion +// against the alias-bomb budget via [yamlWalker.aliasDepth]. +func (w *yamlWalker) alias(node *yaml.Node, depth int) (any, error) { + if node.Alias == nil { + return nil, fmt.Errorf("invalid YAML alias node %q: %w", node.Value, ErrYAML) + } + if w.aliases[node.Alias] { + return nil, fmt.Errorf("anchor %q contains itself: %w", node.Value, ErrYAML) + } + + w.aliases[node.Alias] = true + w.aliasDepth++ + out, err := w.node(node.Alias, depth+1) + w.aliasDepth-- + delete(w.aliases, node.Alias) + + return out, err +} + +func (w *yamlWalker) document(node *yaml.Node, depth int) (any, error) { + if len(node.Content) != 1 { + return nil, fmt.Errorf("unexpected YAML Document node content length: %d: %w", len(node.Content), ErrYAML) + } + return w.node(node.Content[0], depth+1) +} + +func (w *yamlWalker) mapping(node *yaml.Node, depth int) (any, error) { + const sensibleAllocDivider = 2 // nodes concatenate (key,value) sequences + m := make(YAMLMapSlice, len(node.Content)/sensibleAllocDivider) + + if err := m.unmarshalYAML(w, node, depth); err != nil { + return nil, err + } + + return m, nil +} + +func (w *yamlWalker) sequence(node *yaml.Node, depth int) (any, error) { + s := make([]any, 0) + + for i := range len(node.Content) { + v, err := w.node(node.Content[i], depth+1) + 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, depth int) (out any, err error) { + if depth > defaultMaxNestingDepth { + return nil, errMaxNestingDepth + } + + switch in := input.(type) { + case yaml.Node: + return newYAMLWalker().node(&in, depth) + case *yaml.Node: + return newYAMLWalker().node(in, depth) + 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, depth+1) + 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], depth+1) + if err != nil { + return nil, err + } + } + return o, nil + } + return input, nil +} diff --git a/constraint/vendor/github.com/go-openapi/swag/yamlutils_iface.go b/constraint/vendor/github.com/go-openapi/swag/yamlutils_iface.go new file mode 100644 index 000000000..57767efc5 --- /dev/null +++ b/constraint/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/constraint/vendor/github.com/google/cel-go/cel/prompt.go b/constraint/vendor/github.com/google/cel-go/cel/prompt.go index ca25e7ad7..f59934827 100644 --- a/constraint/vendor/github.com/google/cel-go/cel/prompt.go +++ b/constraint/vendor/github.com/google/cel-go/cel/prompt.go @@ -1,233 +1,233 @@ -// Copyright 2025 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cel - -import ( - _ "embed" - "sort" - "strings" - "text/template" - - "github.com/google/cel-go/common" - "github.com/google/cel-go/common/operators" - "github.com/google/cel-go/common/overloads" - "github.com/google/cel-go/common/types" -) - -//go:embed templates/authoring.tmpl -var authoringPrompt string - -// splitImpl splits a string into a list of strings. -// -// Normalizes extracted comments (trim common prefix whitespace and extra trailing newlines). -func splitImpl(str string) []string { - str = strings.TrimRight(str, " \n\t\r") - out := strings.Split(str, "\n") - if len(out) == 0 { - return nil - } - negative := strings.TrimLeft(out[0], " \t") - lenNegative := len(negative) - lenOut := len(out[0]) - if lenNegative == lenOut { - return out - } - prefix := out[0][:lenOut-lenNegative] - trimmed := make([]string, len(out)) - for i, line := range out { - if line == "" { - trimmed[i] = "" - continue - } - if !strings.HasPrefix(line, prefix) { - return out - } - trimmed[i] = strings.TrimPrefix(line, prefix) - } - - return trimmed -} - -// AuthoringPrompt creates a prompt template from a CEL environment for the purpose of AI-assisted authoring. -func AuthoringPrompt(env *Env) (*Prompt, error) { - funcMap := template.FuncMap{ - "split": splitImpl, - "newlineToSpace": func(str string) string { return strings.ReplaceAll(str, "\n", " ") }, - } - tmpl := template.New("cel").Funcs(funcMap) - tmpl, err := tmpl.Parse(authoringPrompt) - if err != nil { - return nil, err - } - return &Prompt{ - Persona: defaultPersona, - FormatRules: defaultFormatRules, - GeneralUsage: defaultGeneralUsage, - tmpl: tmpl, - env: env, - }, nil -} - -// AuthoringPromptWithFieldPaths creates a prompt template from a CEL environment for the purpose of AI-assisted authoring. -// Includes documentation for all of the reachable field paths in the environment. -func AuthoringPromptWithFieldPaths(env *Env) (*Prompt, error) { - p, err := AuthoringPrompt(env) - if err != nil { - return nil, err - } - p.fieldPaths = true - return p, nil -} - -// Prompt represents the core components of an LLM prompt based on a CEL environment. -// -// All fields of the prompt may be overwritten / modified with support for rendering the -// prompt to a human-readable string. -type Prompt struct { - // Persona indicates something about the kind of user making the request - Persona string - - // FormatRules indicate how the LLM should generate its output - FormatRules string - - // GeneralUsage specifies additional context on how CEL should be used. - GeneralUsage string - - // tmpl is the text template base-configuration for rendering text. - tmpl *template.Template - - // fieldPaths is a flag to include reachable field paths in the prompt. - fieldPaths bool - - // env reference used to collect variables, functions, and macros available to the prompt. - env *Env -} - -type promptVariable struct { - *common.Doc - FieldPaths []*common.Doc -} - -type promptInst struct { - *Prompt - - Variables []*promptVariable - Macros []*common.Doc - Functions []*common.Doc - UserPrompt string -} - -// Render renders the user prompt with the associated context from the prompt template -// for use with LLM generators. -// -// User-supplied input is passed as template data via the UserPrompt field, which -// Go's text/template renders as a literal string value. Template action delimiters -// such as {{.Persona}} in the user prompt are never evaluated as template directives -// because text/template only executes directives present in the template definition -// itself, not in data values interpolated at render time. -func (p *Prompt) Render(userPrompt string) string { - var buffer strings.Builder - vars := make([]*promptVariable, len(p.env.Variables())) - for i, v := range p.env.Variables() { - vars[i] = &promptVariable{Doc: v.Documentation()} - if p.fieldPaths && v.Type().Kind() == types.StructKind { - var fieldPaths []*common.Doc - - paths := fieldPathsForType(p.env.CELTypeProvider(), v.Name(), v.Type()) - if len(paths) < 2 { - paths = nil - } else { - // First path is the variable which is already documented. - paths = paths[1:] - } - for _, path := range paths { - fieldPaths = append(fieldPaths, path.Documentation()) - } - - sort.SliceStable(fieldPaths, func(i, j int) bool { - return fieldPaths[i].Name < fieldPaths[j].Name - }) - vars[i].FieldPaths = fieldPaths - } - } - sort.SliceStable(vars, func(i, j int) bool { - return vars[i].Name < vars[j].Name - }) - macs := make([]*common.Doc, len(p.env.Macros())) - for i, m := range p.env.Macros() { - macs[i] = m.(common.Documentor).Documentation() - } - funcs := make([]*common.Doc, 0, len(p.env.Functions())) - for _, f := range p.env.Functions() { - if _, hidden := hiddenFunctions[f.Name()]; hidden { - continue - } - funcs = append(funcs, f.Documentation()) - } - sort.SliceStable(funcs, func(i, j int) bool { - return funcs[i].Name < funcs[j].Name - }) - inst := &promptInst{ - Prompt: p, - Variables: vars, - Macros: macs, - Functions: funcs, - UserPrompt: userPrompt, - } - p.tmpl.Execute(&buffer, inst) - return buffer.String() -} - -const ( - defaultPersona = `You are a software engineer with expertise in networking and application security -authoring boolean Common Expression Language (CEL) expressions to ensure firewall, -networking, authentication, and data access is only permitted when all conditions -are satisfied.` - - defaultFormatRules = `Output your response as a CEL expression. - -Write the expression with the comment on the first line and the expression on the -subsequent lines. Format the expression using 80-character line limits commonly -found in C++ or Java code.` - - defaultGeneralUsage = `CEL supports Protocol Buffer and JSON types, as well as simple types and aggregate types. - -Simple types include bool, bytes, double, int, string, and uint: - -* double literals must always include a decimal point: 1.0, 3.5, -2.2 -* uint literals must be positive values suffixed with a 'u': 42u -* byte literals are strings prefixed with a 'b': b'1235' -* string literals can use either single quotes or double quotes: 'hello', "world" -* string literals can also be treated as raw strings that do not require any - escaping within the string by using the 'R' prefix: R"""quote: "hi" """ - -Aggregate types include list and map: - -* list literals consist of zero or more values between brackets: "['a', 'b', 'c']" -* map literal consist of colon-separated key-value pairs within braces: "{'key1': 1, 'key2': 2}" -* Only int, uint, string, and bool types are valid map keys. -* Maps containing HTTP headers must always use lower-cased string keys. - -Comments start with two-forward slashes followed by text and a newline.` -) - -var ( - hiddenFunctions = map[string]bool{ - overloads.DeprecatedIn: true, - operators.OldIn: true, - operators.OldNotStrictlyFalse: true, - operators.NotStrictlyFalse: true, - } -) \ No newline at end of file +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cel + +import ( + _ "embed" + "sort" + "strings" + "text/template" + + "github.com/google/cel-go/common" + "github.com/google/cel-go/common/operators" + "github.com/google/cel-go/common/overloads" + "github.com/google/cel-go/common/types" +) + +//go:embed templates/authoring.tmpl +var authoringPrompt string + +// splitImpl splits a string into a list of strings. +// +// Normalizes extracted comments (trim common prefix whitespace and extra trailing newlines). +func splitImpl(str string) []string { + str = strings.TrimRight(str, " \n\t\r") + out := strings.Split(str, "\n") + if len(out) == 0 { + return nil + } + negative := strings.TrimLeft(out[0], " \t") + lenNegative := len(negative) + lenOut := len(out[0]) + if lenNegative == lenOut { + return out + } + prefix := out[0][:lenOut-lenNegative] + trimmed := make([]string, len(out)) + for i, line := range out { + if line == "" { + trimmed[i] = "" + continue + } + if !strings.HasPrefix(line, prefix) { + return out + } + trimmed[i] = strings.TrimPrefix(line, prefix) + } + + return trimmed +} + +// AuthoringPrompt creates a prompt template from a CEL environment for the purpose of AI-assisted authoring. +func AuthoringPrompt(env *Env) (*Prompt, error) { + funcMap := template.FuncMap{ + "split": splitImpl, + "newlineToSpace": func(str string) string { return strings.ReplaceAll(str, "\n", " ") }, + } + tmpl := template.New("cel").Funcs(funcMap) + tmpl, err := tmpl.Parse(authoringPrompt) + if err != nil { + return nil, err + } + return &Prompt{ + Persona: defaultPersona, + FormatRules: defaultFormatRules, + GeneralUsage: defaultGeneralUsage, + tmpl: tmpl, + env: env, + }, nil +} + +// AuthoringPromptWithFieldPaths creates a prompt template from a CEL environment for the purpose of AI-assisted authoring. +// Includes documentation for all of the reachable field paths in the environment. +func AuthoringPromptWithFieldPaths(env *Env) (*Prompt, error) { + p, err := AuthoringPrompt(env) + if err != nil { + return nil, err + } + p.fieldPaths = true + return p, nil +} + +// Prompt represents the core components of an LLM prompt based on a CEL environment. +// +// All fields of the prompt may be overwritten / modified with support for rendering the +// prompt to a human-readable string. +type Prompt struct { + // Persona indicates something about the kind of user making the request + Persona string + + // FormatRules indicate how the LLM should generate its output + FormatRules string + + // GeneralUsage specifies additional context on how CEL should be used. + GeneralUsage string + + // tmpl is the text template base-configuration for rendering text. + tmpl *template.Template + + // fieldPaths is a flag to include reachable field paths in the prompt. + fieldPaths bool + + // env reference used to collect variables, functions, and macros available to the prompt. + env *Env +} + +type promptVariable struct { + *common.Doc + FieldPaths []*common.Doc +} + +type promptInst struct { + *Prompt + + Variables []*promptVariable + Macros []*common.Doc + Functions []*common.Doc + UserPrompt string +} + +// Render renders the user prompt with the associated context from the prompt template +// for use with LLM generators. +// +// User-supplied input is passed as template data via the UserPrompt field, which +// Go's text/template renders as a literal string value. Template action delimiters +// such as {{.Persona}} in the user prompt are never evaluated as template directives +// because text/template only executes directives present in the template definition +// itself, not in data values interpolated at render time. +func (p *Prompt) Render(userPrompt string) string { + var buffer strings.Builder + vars := make([]*promptVariable, len(p.env.Variables())) + for i, v := range p.env.Variables() { + vars[i] = &promptVariable{Doc: v.Documentation()} + if p.fieldPaths && v.Type().Kind() == types.StructKind { + var fieldPaths []*common.Doc + + paths := fieldPathsForType(p.env.CELTypeProvider(), v.Name(), v.Type()) + if len(paths) < 2 { + paths = nil + } else { + // First path is the variable which is already documented. + paths = paths[1:] + } + for _, path := range paths { + fieldPaths = append(fieldPaths, path.Documentation()) + } + + sort.SliceStable(fieldPaths, func(i, j int) bool { + return fieldPaths[i].Name < fieldPaths[j].Name + }) + vars[i].FieldPaths = fieldPaths + } + } + sort.SliceStable(vars, func(i, j int) bool { + return vars[i].Name < vars[j].Name + }) + macs := make([]*common.Doc, len(p.env.Macros())) + for i, m := range p.env.Macros() { + macs[i] = m.(common.Documentor).Documentation() + } + funcs := make([]*common.Doc, 0, len(p.env.Functions())) + for _, f := range p.env.Functions() { + if _, hidden := hiddenFunctions[f.Name()]; hidden { + continue + } + funcs = append(funcs, f.Documentation()) + } + sort.SliceStable(funcs, func(i, j int) bool { + return funcs[i].Name < funcs[j].Name + }) + inst := &promptInst{ + Prompt: p, + Variables: vars, + Macros: macs, + Functions: funcs, + UserPrompt: userPrompt, + } + p.tmpl.Execute(&buffer, inst) + return buffer.String() +} + +const ( + defaultPersona = `You are a software engineer with expertise in networking and application security +authoring boolean Common Expression Language (CEL) expressions to ensure firewall, +networking, authentication, and data access is only permitted when all conditions +are satisfied.` + + defaultFormatRules = `Output your response as a CEL expression. + +Write the expression with the comment on the first line and the expression on the +subsequent lines. Format the expression using 80-character line limits commonly +found in C++ or Java code.` + + defaultGeneralUsage = `CEL supports Protocol Buffer and JSON types, as well as simple types and aggregate types. + +Simple types include bool, bytes, double, int, string, and uint: + +* double literals must always include a decimal point: 1.0, 3.5, -2.2 +* uint literals must be positive values suffixed with a 'u': 42u +* byte literals are strings prefixed with a 'b': b'1235' +* string literals can use either single quotes or double quotes: 'hello', "world" +* string literals can also be treated as raw strings that do not require any + escaping within the string by using the 'R' prefix: R"""quote: "hi" """ + +Aggregate types include list and map: + +* list literals consist of zero or more values between brackets: "['a', 'b', 'c']" +* map literal consist of colon-separated key-value pairs within braces: "{'key1': 1, 'key2': 2}" +* Only int, uint, string, and bool types are valid map keys. +* Maps containing HTTP headers must always use lower-cased string keys. + +Comments start with two-forward slashes followed by text and a newline.` +) + +var ( + hiddenFunctions = map[string]bool{ + overloads.DeprecatedIn: true, + operators.OldIn: true, + operators.OldNotStrictlyFalse: true, + operators.NotStrictlyFalse: true, + } +) diff --git a/constraint/vendor/github.com/google/cel-go/ext/lists.go b/constraint/vendor/github.com/google/cel-go/ext/lists.go index 37ae2d3d6..b4ac25899 100644 --- a/constraint/vendor/github.com/google/cel-go/ext/lists.go +++ b/constraint/vendor/github.com/google/cel-go/ext/lists.go @@ -779,6 +779,9 @@ func trackListSelfCompare(l traits.Lister) *uint64 { // trackAllocatingListCall computes costs as a function of the size of the result list with a baseline cost // for the call dispatch and the associated list allocation. func trackAllocatingListCall(costFactor float64, size uint64) *uint64 { + if costFactor < 0.0 { + costFactor = 1.0 + } cost := safeAdd(uint64(float64(size)*costFactor), callCost, common.ListCreateBaseCost) return &cost } diff --git a/constraint/vendor/github.com/josharian/intern/README.md b/constraint/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b219..000000000 --- a/constraint/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/constraint/vendor/github.com/josharian/intern/intern.go b/constraint/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe90..000000000 --- a/constraint/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/constraint/vendor/github.com/josharian/intern/license.md b/constraint/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d3055f..000000000 --- a/constraint/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/constraint/vendor/github.com/mailru/easyjson/LICENSE b/constraint/vendor/github.com/mailru/easyjson/LICENSE deleted file mode 100644 index fbff658f7..000000000 --- a/constraint/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/constraint/vendor/github.com/mailru/easyjson/buffer/pool.go b/constraint/vendor/github.com/mailru/easyjson/buffer/pool.go deleted file mode 100644 index 598a54af9..000000000 --- a/constraint/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/constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go deleted file mode 100644 index ff7b27c5b..000000000 --- a/constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ /dev/null @@ -1,24 +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 ( - "reflect" - "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 { - h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) - shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} - return *(*string)(unsafe.Pointer(&shdr)) -} diff --git a/constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/constraint/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go deleted file mode 100644 index 864d1be67..000000000 --- a/constraint/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/constraint/vendor/github.com/mailru/easyjson/jlexer/error.go b/constraint/vendor/github.com/mailru/easyjson/jlexer/error.go deleted file mode 100644 index e90ec40d0..000000000 --- a/constraint/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/constraint/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/constraint/vendor/github.com/mailru/easyjson/jlexer/lexer.go deleted file mode 100644 index b5f5e2613..000000000 --- a/constraint/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ /dev/null @@ -1,1244 +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 -} diff --git a/constraint/vendor/github.com/mailru/easyjson/jwriter/writer.go b/constraint/vendor/github.com/mailru/easyjson/jwriter/writer.go deleted file mode 100644 index 2c5b20105..000000000 --- a/constraint/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ /dev/null @@ -1,405 +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) -} - -// 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/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/README.md b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/README.md deleted file mode 100644 index 87b842c5d..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Semconv v1.17.0 - -[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/semconv/v1.17.0)](https://pkg.go.dev/go.opentelemetry.io/otel/semconv/v1.17.0) diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/doc.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/doc.go deleted file mode 100644 index e087c9c04..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconv implements OpenTelemetry semantic conventions. -// -// OpenTelemetry semantic conventions are agreed standardized naming -// patterns for OpenTelemetry things. This package represents the conventions -// as of the v1.17.0 version of the OpenTelemetry specification. -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/event.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/event.go deleted file mode 100644 index c7b804bbe..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/event.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -import "go.opentelemetry.io/otel/attribute" - -// This semantic convention defines the attributes used to represent a feature -// flag evaluation as an event. -const ( - // FeatureFlagKeyKey is the attribute Key conforming to the - // "feature_flag.key" semantic conventions. It represents the unique - // identifier of the feature flag. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'logo-color' - FeatureFlagKeyKey = attribute.Key("feature_flag.key") - - // FeatureFlagProviderNameKey is the attribute Key conforming to the - // "feature_flag.provider_name" semantic conventions. It represents the - // name of the service provider that performs the flag evaluation. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'Flag Manager' - FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") - - // FeatureFlagVariantKey is the attribute Key conforming to the - // "feature_flag.variant" semantic conventions. It represents the sHOULD be - // a semantic identifier for a value. If one is unavailable, a stringified - // version of the value can be used. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'red', 'true', 'on' - // Note: A semantic identifier, commonly referred to as a variant, provides - // a means - // for referring to a value without including the value itself. This can - // provide additional context for understanding the meaning behind a value. - // For example, the variant `red` maybe be used for the value `#c05543`. - // - // A stringified version of the value can be used in situations where a - // semantic identifier is unavailable. String representation of the value - // should be determined by the implementer. - FeatureFlagVariantKey = attribute.Key("feature_flag.variant") -) - -// FeatureFlagKey returns an attribute KeyValue conforming to the -// "feature_flag.key" semantic conventions. It represents the unique identifier -// of the feature flag. -func FeatureFlagKey(val string) attribute.KeyValue { - return FeatureFlagKeyKey.String(val) -} - -// FeatureFlagProviderName returns an attribute KeyValue conforming to the -// "feature_flag.provider_name" semantic conventions. It represents the name of -// the service provider that performs the flag evaluation. -func FeatureFlagProviderName(val string) attribute.KeyValue { - return FeatureFlagProviderNameKey.String(val) -} - -// FeatureFlagVariant returns an attribute KeyValue conforming to the -// "feature_flag.variant" semantic conventions. It represents the sHOULD be a -// semantic identifier for a value. If one is unavailable, a stringified -// version of the value can be used. -func FeatureFlagVariant(val string) attribute.KeyValue { - return FeatureFlagVariantKey.String(val) -} - -// RPC received/sent message. -const ( - // MessageTypeKey is the attribute Key conforming to the "message.type" - // semantic conventions. It represents the whether this is a received or - // sent message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessageTypeKey = attribute.Key("message.type") - - // MessageIDKey is the attribute Key conforming to the "message.id" - // semantic conventions. It represents the mUST be calculated as two - // different counters starting from `1` one for sent messages and one for - // received message. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Note: This way we guarantee that the values will be consistent between - // different implementations. - MessageIDKey = attribute.Key("message.id") - - // MessageCompressedSizeKey is the attribute Key conforming to the - // "message.compressed_size" semantic conventions. It represents the - // compressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - MessageCompressedSizeKey = attribute.Key("message.compressed_size") - - // MessageUncompressedSizeKey is the attribute Key conforming to the - // "message.uncompressed_size" semantic conventions. It represents the - // uncompressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - MessageUncompressedSizeKey = attribute.Key("message.uncompressed_size") -) - -var ( - // sent - MessageTypeSent = MessageTypeKey.String("SENT") - // received - MessageTypeReceived = MessageTypeKey.String("RECEIVED") -) - -// MessageID returns an attribute KeyValue conforming to the "message.id" -// semantic conventions. It represents the mUST be calculated as two different -// counters starting from `1` one for sent messages and one for received -// message. -func MessageID(val int) attribute.KeyValue { - return MessageIDKey.Int(val) -} - -// MessageCompressedSize returns an attribute KeyValue conforming to the -// "message.compressed_size" semantic conventions. It represents the compressed -// size of the message in bytes. -func MessageCompressedSize(val int) attribute.KeyValue { - return MessageCompressedSizeKey.Int(val) -} - -// MessageUncompressedSize returns an attribute KeyValue conforming to the -// "message.uncompressed_size" semantic conventions. It represents the -// uncompressed size of the message in bytes. -func MessageUncompressedSize(val int) attribute.KeyValue { - return MessageUncompressedSizeKey.Int(val) -} - -// The attributes used to report a single exception associated with a span. -const ( - // ExceptionEscapedKey is the attribute Key conforming to the - // "exception.escaped" semantic conventions. It represents the sHOULD be - // set to true if the exception event is recorded at a point where it is - // known that the exception is escaping the scope of the span. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Note: An exception is considered to have escaped (or left) the scope of - // a span, - // if that span is ended while the exception is still logically "in - // flight". - // This may be actually "in flight" in some languages (e.g. if the - // exception - // is passed to a Context manager's `__exit__` method in Python) but will - // usually be caught at the point of recording the exception in most - // languages. - // - // It is usually not possible to determine at the point where an exception - // is thrown - // whether it will escape the scope of a span. - // However, it is trivial to know that an exception - // will escape, if one checks for an active exception just before ending - // the span, - // as done in the [example above](#recording-an-exception). - // - // It follows that an exception may still escape the scope of the span - // even if the `exception.escaped` attribute was not set or set to false, - // since the event might have been recorded at a time where it was not - // clear whether the exception will escape. - ExceptionEscapedKey = attribute.Key("exception.escaped") -) - -// ExceptionEscaped returns an attribute KeyValue conforming to the -// "exception.escaped" semantic conventions. It represents the sHOULD be set to -// true if the exception event is recorded at a point where it is known that -// the exception is escaping the scope of the span. -func ExceptionEscaped(val bool) attribute.KeyValue { - return ExceptionEscapedKey.Bool(val) -} diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/exception.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/exception.go deleted file mode 100644 index 137acc67d..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/exception.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -const ( - // ExceptionEventName is the name of the Span event representing an exception. - ExceptionEventName = "exception" -) diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/http.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/http.go deleted file mode 100644 index d318221e5..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/http.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -// HTTP scheme attributes. -var ( - HTTPSchemeHTTP = HTTPSchemeKey.String("http") - HTTPSchemeHTTPS = HTTPSchemeKey.String("https") -) diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/resource.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/resource.go deleted file mode 100644 index 7e365e82c..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/resource.go +++ /dev/null @@ -1,1999 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -import "go.opentelemetry.io/otel/attribute" - -// The web browser in which the application represented by the resource is -// running. The `browser.*` attributes MUST be used only for resources that -// represent applications running in a web browser (regardless of whether -// running on a mobile or desktop device). -const ( - // BrowserBrandsKey is the attribute Key conforming to the "browser.brands" - // semantic conventions. It represents the array of brand name and version - // separated by a space - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: ' Not A;Brand 99', 'Chromium 99', 'Chrome 99' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.brands`). - BrowserBrandsKey = attribute.Key("browser.brands") - - // BrowserPlatformKey is the attribute Key conforming to the - // "browser.platform" semantic conventions. It represents the platform on - // which the browser is running - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Windows', 'macOS', 'Android' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.platform`). If unavailable, the legacy - // `navigator.platform` API SHOULD NOT be used instead and this attribute - // SHOULD be left unset in order for the values to be consistent. - // The list of possible values is defined in the [W3C User-Agent Client - // Hints - // specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). - // Note that some (but not all) of these values can overlap with values in - // the [`os.type` and `os.name` attributes](./os.md). However, for - // consistency, the values in the `browser.platform` attribute should - // capture the exact value that the user agent provides. - BrowserPlatformKey = attribute.Key("browser.platform") - - // BrowserMobileKey is the attribute Key conforming to the "browser.mobile" - // semantic conventions. It represents a boolean that is true if the - // browser is running on a mobile device - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.mobile`). If unavailable, this attribute - // SHOULD be left unset. - BrowserMobileKey = attribute.Key("browser.mobile") - - // BrowserUserAgentKey is the attribute Key conforming to the - // "browser.user_agent" semantic conventions. It represents the full - // user-agent string provided by the browser - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) - // AppleWebKit/537.36 (KHTML, ' - // 'like Gecko) Chrome/95.0.4638.54 Safari/537.36' - // Note: The user-agent value SHOULD be provided only from browsers that do - // not have a mechanism to retrieve brands and platform individually from - // the User-Agent Client Hints API. To retrieve the value, the legacy - // `navigator.userAgent` API can be used. - BrowserUserAgentKey = attribute.Key("browser.user_agent") - - // BrowserLanguageKey is the attribute Key conforming to the - // "browser.language" semantic conventions. It represents the preferred - // language of the user using the browser - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'en', 'en-US', 'fr', 'fr-FR' - // Note: This value is intended to be taken from the Navigator API - // `navigator.language`. - BrowserLanguageKey = attribute.Key("browser.language") -) - -// BrowserBrands returns an attribute KeyValue conforming to the -// "browser.brands" semantic conventions. It represents the array of brand name -// and version separated by a space -func BrowserBrands(val ...string) attribute.KeyValue { - return BrowserBrandsKey.StringSlice(val) -} - -// BrowserPlatform returns an attribute KeyValue conforming to the -// "browser.platform" semantic conventions. It represents the platform on which -// the browser is running -func BrowserPlatform(val string) attribute.KeyValue { - return BrowserPlatformKey.String(val) -} - -// BrowserMobile returns an attribute KeyValue conforming to the -// "browser.mobile" semantic conventions. It represents a boolean that is true -// if the browser is running on a mobile device -func BrowserMobile(val bool) attribute.KeyValue { - return BrowserMobileKey.Bool(val) -} - -// BrowserUserAgent returns an attribute KeyValue conforming to the -// "browser.user_agent" semantic conventions. It represents the full user-agent -// string provided by the browser -func BrowserUserAgent(val string) attribute.KeyValue { - return BrowserUserAgentKey.String(val) -} - -// BrowserLanguage returns an attribute KeyValue conforming to the -// "browser.language" semantic conventions. It represents the preferred -// language of the user using the browser -func BrowserLanguage(val string) attribute.KeyValue { - return BrowserLanguageKey.String(val) -} - -// A cloud environment (e.g. GCP, Azure, AWS) -const ( - // CloudProviderKey is the attribute Key conforming to the "cloud.provider" - // semantic conventions. It represents the name of the cloud provider. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - CloudProviderKey = attribute.Key("cloud.provider") - - // CloudAccountIDKey is the attribute Key conforming to the - // "cloud.account.id" semantic conventions. It represents the cloud account - // ID the resource is assigned to. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '111111111111', 'opentelemetry' - CloudAccountIDKey = attribute.Key("cloud.account.id") - - // CloudRegionKey is the attribute Key conforming to the "cloud.region" - // semantic conventions. It represents the geographical region the resource - // is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-central1', 'us-east-1' - // Note: Refer to your provider's docs to see the available regions, for - // example [Alibaba Cloud - // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS - // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), - // [Azure - // regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), - // [Google Cloud regions](https://cloud.google.com/about/locations), or - // [Tencent Cloud - // regions](https://intl.cloud.tencent.com/document/product/213/6091). - CloudRegionKey = attribute.Key("cloud.region") - - // CloudAvailabilityZoneKey is the attribute Key conforming to the - // "cloud.availability_zone" semantic conventions. It represents the cloud - // regions often have multiple, isolated locations known as zones to - // increase availability. Availability zone represents the zone where the - // resource is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-east-1c' - // Note: Availability zones are called "zones" on Alibaba Cloud and Google - // Cloud. - CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") - - // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" - // semantic conventions. It represents the cloud platform in use. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: The prefix of the service SHOULD match the one specified in - // `cloud.provider`. - CloudPlatformKey = attribute.Key("cloud.platform") -) - -var ( - // Alibaba Cloud - CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") - // Amazon Web Services - CloudProviderAWS = CloudProviderKey.String("aws") - // Microsoft Azure - CloudProviderAzure = CloudProviderKey.String("azure") - // Google Cloud Platform - CloudProviderGCP = CloudProviderKey.String("gcp") - // IBM Cloud - CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") - // Tencent Cloud - CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") -) - -var ( - // Alibaba Cloud Elastic Compute Service - CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") - // Alibaba Cloud Function Compute - CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") - // Red Hat OpenShift on Alibaba Cloud - CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") - // AWS Elastic Compute Cloud - CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") - // AWS Elastic Container Service - CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") - // AWS Elastic Kubernetes Service - CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") - // AWS Lambda - CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") - // AWS Elastic Beanstalk - CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") - // AWS App Runner - CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") - // Red Hat OpenShift on AWS (ROSA) - CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") - // Azure Virtual Machines - CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") - // Azure Container Instances - CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") - // Azure Kubernetes Service - CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") - // Azure Functions - CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") - // Azure App Service - CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") - // Azure Red Hat OpenShift - CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") - // Google Cloud Compute Engine (GCE) - CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") - // Google Cloud Run - CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") - // Google Cloud Kubernetes Engine (GKE) - CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") - // Google Cloud Functions (GCF) - CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") - // Google Cloud App Engine (GAE) - CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") - // Red Hat OpenShift on Google Cloud - CloudPlatformGoogleCloudOpenshift = CloudPlatformKey.String("google_cloud_openshift") - // Red Hat OpenShift on IBM Cloud - CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") - // Tencent Cloud Cloud Virtual Machine (CVM) - CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") - // Tencent Cloud Elastic Kubernetes Service (EKS) - CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") - // Tencent Cloud Serverless Cloud Function (SCF) - CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") -) - -// CloudAccountID returns an attribute KeyValue conforming to the -// "cloud.account.id" semantic conventions. It represents the cloud account ID -// the resource is assigned to. -func CloudAccountID(val string) attribute.KeyValue { - return CloudAccountIDKey.String(val) -} - -// CloudRegion returns an attribute KeyValue conforming to the -// "cloud.region" semantic conventions. It represents the geographical region -// the resource is running. -func CloudRegion(val string) attribute.KeyValue { - return CloudRegionKey.String(val) -} - -// CloudAvailabilityZone returns an attribute KeyValue conforming to the -// "cloud.availability_zone" semantic conventions. It represents the cloud -// regions often have multiple, isolated locations known as zones to increase -// availability. Availability zone represents the zone where the resource is -// running. -func CloudAvailabilityZone(val string) attribute.KeyValue { - return CloudAvailabilityZoneKey.String(val) -} - -// Resources used by AWS Elastic Container Service (ECS). -const ( - // AWSECSContainerARNKey is the attribute Key conforming to the - // "aws.ecs.container.arn" semantic conventions. It represents the Amazon - // Resource Name (ARN) of an [ECS container - // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:container/32624152-9086-4f0e-acae-1a75b14fe4d9' - AWSECSContainerARNKey = attribute.Key("aws.ecs.container.arn") - - // AWSECSClusterARNKey is the attribute Key conforming to the - // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an - // [ECS - // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSECSClusterARNKey = attribute.Key("aws.ecs.cluster.arn") - - // AWSECSLaunchtypeKey is the attribute Key conforming to the - // "aws.ecs.launchtype" semantic conventions. It represents the [launch - // type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) - // for an ECS task. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - AWSECSLaunchtypeKey = attribute.Key("aws.ecs.launchtype") - - // AWSECSTaskARNKey is the attribute Key conforming to the - // "aws.ecs.task.arn" semantic conventions. It represents the ARN of an - // [ECS task - // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:task/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSECSTaskARNKey = attribute.Key("aws.ecs.task.arn") - - // AWSECSTaskFamilyKey is the attribute Key conforming to the - // "aws.ecs.task.family" semantic conventions. It represents the task - // definition family this task definition is a member of. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-family' - AWSECSTaskFamilyKey = attribute.Key("aws.ecs.task.family") - - // AWSECSTaskRevisionKey is the attribute Key conforming to the - // "aws.ecs.task.revision" semantic conventions. It represents the revision - // for this task definition. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '8', '26' - AWSECSTaskRevisionKey = attribute.Key("aws.ecs.task.revision") -) - -var ( - // ec2 - AWSECSLaunchtypeEC2 = AWSECSLaunchtypeKey.String("ec2") - // fargate - AWSECSLaunchtypeFargate = AWSECSLaunchtypeKey.String("fargate") -) - -// AWSECSContainerARN returns an attribute KeyValue conforming to the -// "aws.ecs.container.arn" semantic conventions. It represents the Amazon -// Resource Name (ARN) of an [ECS container -// instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). -func AWSECSContainerARN(val string) attribute.KeyValue { - return AWSECSContainerARNKey.String(val) -} - -// AWSECSClusterARN returns an attribute KeyValue conforming to the -// "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an [ECS -// cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). -func AWSECSClusterARN(val string) attribute.KeyValue { - return AWSECSClusterARNKey.String(val) -} - -// AWSECSTaskARN returns an attribute KeyValue conforming to the -// "aws.ecs.task.arn" semantic conventions. It represents the ARN of an [ECS -// task -// definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). -func AWSECSTaskARN(val string) attribute.KeyValue { - return AWSECSTaskARNKey.String(val) -} - -// AWSECSTaskFamily returns an attribute KeyValue conforming to the -// "aws.ecs.task.family" semantic conventions. It represents the task -// definition family this task definition is a member of. -func AWSECSTaskFamily(val string) attribute.KeyValue { - return AWSECSTaskFamilyKey.String(val) -} - -// AWSECSTaskRevision returns an attribute KeyValue conforming to the -// "aws.ecs.task.revision" semantic conventions. It represents the revision for -// this task definition. -func AWSECSTaskRevision(val string) attribute.KeyValue { - return AWSECSTaskRevisionKey.String(val) -} - -// Resources used by AWS Elastic Kubernetes Service (EKS). -const ( - // AWSEKSClusterARNKey is the attribute Key conforming to the - // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an - // EKS cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSEKSClusterARNKey = attribute.Key("aws.eks.cluster.arn") -) - -// AWSEKSClusterARN returns an attribute KeyValue conforming to the -// "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an EKS -// cluster. -func AWSEKSClusterARN(val string) attribute.KeyValue { - return AWSEKSClusterARNKey.String(val) -} - -// Resources specific to Amazon Web Services. -const ( - // AWSLogGroupNamesKey is the attribute Key conforming to the - // "aws.log.group.names" semantic conventions. It represents the name(s) of - // the AWS log group(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '/aws/lambda/my-function', 'opentelemetry-service' - // Note: Multiple log groups must be supported for cases like - // multi-container applications, where a single application has sidecar - // containers, and each write to their own log group. - AWSLogGroupNamesKey = attribute.Key("aws.log.group.names") - - // AWSLogGroupARNsKey is the attribute Key conforming to the - // "aws.log.group.arns" semantic conventions. It represents the Amazon - // Resource Name(s) (ARN) of the AWS log group(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:*' - // Note: See the [log group ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - AWSLogGroupARNsKey = attribute.Key("aws.log.group.arns") - - // AWSLogStreamNamesKey is the attribute Key conforming to the - // "aws.log.stream.names" semantic conventions. It represents the name(s) - // of the AWS log stream(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSLogStreamNamesKey = attribute.Key("aws.log.stream.names") - - // AWSLogStreamARNsKey is the attribute Key conforming to the - // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of - // the AWS log stream(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:log-stream:logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - // Note: See the [log stream ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - // One log group can contain several log streams, so these ARNs necessarily - // identify both a log group and a log stream. - AWSLogStreamARNsKey = attribute.Key("aws.log.stream.arns") -) - -// AWSLogGroupNames returns an attribute KeyValue conforming to the -// "aws.log.group.names" semantic conventions. It represents the name(s) of the -// AWS log group(s) an application is writing to. -func AWSLogGroupNames(val ...string) attribute.KeyValue { - return AWSLogGroupNamesKey.StringSlice(val) -} - -// AWSLogGroupARNs returns an attribute KeyValue conforming to the -// "aws.log.group.arns" semantic conventions. It represents the Amazon Resource -// Name(s) (ARN) of the AWS log group(s). -func AWSLogGroupARNs(val ...string) attribute.KeyValue { - return AWSLogGroupARNsKey.StringSlice(val) -} - -// AWSLogStreamNames returns an attribute KeyValue conforming to the -// "aws.log.stream.names" semantic conventions. It represents the name(s) of -// the AWS log stream(s) an application is writing to. -func AWSLogStreamNames(val ...string) attribute.KeyValue { - return AWSLogStreamNamesKey.StringSlice(val) -} - -// AWSLogStreamARNs returns an attribute KeyValue conforming to the -// "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of the -// AWS log stream(s). -func AWSLogStreamARNs(val ...string) attribute.KeyValue { - return AWSLogStreamARNsKey.StringSlice(val) -} - -// A container instance. -const ( - // ContainerNameKey is the attribute Key conforming to the "container.name" - // semantic conventions. It represents the container name used by container - // runtime. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-autoconf' - ContainerNameKey = attribute.Key("container.name") - - // ContainerIDKey is the attribute Key conforming to the "container.id" - // semantic conventions. It represents the container ID. Usually a UUID, as - // for example used to [identify Docker - // containers](https://docs.docker.com/engine/reference/run/#container-identification). - // The UUID might be abbreviated. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'a3bf90e006b2' - ContainerIDKey = attribute.Key("container.id") - - // ContainerRuntimeKey is the attribute Key conforming to the - // "container.runtime" semantic conventions. It represents the container - // runtime managing this container. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'docker', 'containerd', 'rkt' - ContainerRuntimeKey = attribute.Key("container.runtime") - - // ContainerImageNameKey is the attribute Key conforming to the - // "container.image.name" semantic conventions. It represents the name of - // the image the container was built on. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'gcr.io/opentelemetry/operator' - ContainerImageNameKey = attribute.Key("container.image.name") - - // ContainerImageTagKey is the attribute Key conforming to the - // "container.image.tag" semantic conventions. It represents the container - // image tag. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0.1' - ContainerImageTagKey = attribute.Key("container.image.tag") -) - -// ContainerName returns an attribute KeyValue conforming to the -// "container.name" semantic conventions. It represents the container name used -// by container runtime. -func ContainerName(val string) attribute.KeyValue { - return ContainerNameKey.String(val) -} - -// ContainerID returns an attribute KeyValue conforming to the -// "container.id" semantic conventions. It represents the container ID. Usually -// a UUID, as for example used to [identify Docker -// containers](https://docs.docker.com/engine/reference/run/#container-identification). -// The UUID might be abbreviated. -func ContainerID(val string) attribute.KeyValue { - return ContainerIDKey.String(val) -} - -// ContainerRuntime returns an attribute KeyValue conforming to the -// "container.runtime" semantic conventions. It represents the container -// runtime managing this container. -func ContainerRuntime(val string) attribute.KeyValue { - return ContainerRuntimeKey.String(val) -} - -// ContainerImageName returns an attribute KeyValue conforming to the -// "container.image.name" semantic conventions. It represents the name of the -// image the container was built on. -func ContainerImageName(val string) attribute.KeyValue { - return ContainerImageNameKey.String(val) -} - -// ContainerImageTag returns an attribute KeyValue conforming to the -// "container.image.tag" semantic conventions. It represents the container -// image tag. -func ContainerImageTag(val string) attribute.KeyValue { - return ContainerImageTagKey.String(val) -} - -// The software deployment. -const ( - // DeploymentEnvironmentKey is the attribute Key conforming to the - // "deployment.environment" semantic conventions. It represents the name of - // the [deployment - // environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka - // deployment tier). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'staging', 'production' - DeploymentEnvironmentKey = attribute.Key("deployment.environment") -) - -// DeploymentEnvironment returns an attribute KeyValue conforming to the -// "deployment.environment" semantic conventions. It represents the name of the -// [deployment -// environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka -// deployment tier). -func DeploymentEnvironment(val string) attribute.KeyValue { - return DeploymentEnvironmentKey.String(val) -} - -// The device on which the process represented by this resource is running. -const ( - // DeviceIDKey is the attribute Key conforming to the "device.id" semantic - // conventions. It represents a unique identifier representing the device - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' - // Note: The device identifier MUST only be defined using the values - // outlined below. This value is not an advertising identifier and MUST NOT - // be used as such. On iOS (Swift or Objective-C), this value MUST be equal - // to the [vendor - // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). - // On Android (Java or Kotlin), this value MUST be equal to the Firebase - // Installation ID or a globally unique UUID which is persisted across - // sessions in your application. More information can be found - // [here](https://developer.android.com/training/articles/user-data-ids) on - // best practices and exact implementation details. Caution should be taken - // when storing personal data or anything which can identify a user. GDPR - // and data protection laws may apply, ensure you do your own due - // diligence. - DeviceIDKey = attribute.Key("device.id") - - // DeviceModelIdentifierKey is the attribute Key conforming to the - // "device.model.identifier" semantic conventions. It represents the model - // identifier for the device - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iPhone3,4', 'SM-G920F' - // Note: It's recommended this value represents a machine readable version - // of the model identifier rather than the market or consumer-friendly name - // of the device. - DeviceModelIdentifierKey = attribute.Key("device.model.identifier") - - // DeviceModelNameKey is the attribute Key conforming to the - // "device.model.name" semantic conventions. It represents the marketing - // name for the device model - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' - // Note: It's recommended this value represents a human readable version of - // the device model rather than a machine readable alternative. - DeviceModelNameKey = attribute.Key("device.model.name") - - // DeviceManufacturerKey is the attribute Key conforming to the - // "device.manufacturer" semantic conventions. It represents the name of - // the device manufacturer - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Apple', 'Samsung' - // Note: The Android OS provides this field via - // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). - // iOS apps SHOULD hardcode the value `Apple`. - DeviceManufacturerKey = attribute.Key("device.manufacturer") -) - -// DeviceID returns an attribute KeyValue conforming to the "device.id" -// semantic conventions. It represents a unique identifier representing the -// device -func DeviceID(val string) attribute.KeyValue { - return DeviceIDKey.String(val) -} - -// DeviceModelIdentifier returns an attribute KeyValue conforming to the -// "device.model.identifier" semantic conventions. It represents the model -// identifier for the device -func DeviceModelIdentifier(val string) attribute.KeyValue { - return DeviceModelIdentifierKey.String(val) -} - -// DeviceModelName returns an attribute KeyValue conforming to the -// "device.model.name" semantic conventions. It represents the marketing name -// for the device model -func DeviceModelName(val string) attribute.KeyValue { - return DeviceModelNameKey.String(val) -} - -// DeviceManufacturer returns an attribute KeyValue conforming to the -// "device.manufacturer" semantic conventions. It represents the name of the -// device manufacturer -func DeviceManufacturer(val string) attribute.KeyValue { - return DeviceManufacturerKey.String(val) -} - -// A serverless instance. -const ( - // FaaSNameKey is the attribute Key conforming to the "faas.name" semantic - // conventions. It represents the name of the single function that this - // runtime instance executes. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'my-function', 'myazurefunctionapp/some-function-name' - // Note: This is the name of the function as configured/deployed on the - // FaaS - // platform and is usually different from the name of the callback - // function (which may be stored in the - // [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) - // span attributes). - // - // For some cloud providers, the above definition is ambiguous. The - // following - // definition of function name MUST be used for this attribute - // (and consequently the span name) for the listed cloud - // providers/products: - // - // * **Azure:** The full name `/`, i.e., function app name - // followed by a forward slash followed by the function name (this form - // can also be seen in the resource JSON for the function). - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider (see also the `faas.id` attribute). - FaaSNameKey = attribute.Key("faas.name") - - // FaaSIDKey is the attribute Key conforming to the "faas.id" semantic - // conventions. It represents the unique ID of the single function that - // this runtime instance executes. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:lambda:us-west-2:123456789012:function:my-function' - // Note: On some cloud providers, it may not be possible to determine the - // full ID at startup, - // so consider setting `faas.id` as a span attribute instead. - // - // The exact value to use for `faas.id` depends on the cloud provider: - // - // * **AWS Lambda:** The function - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - // Take care not to use the "invoked ARN" directly but replace any - // [alias - // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) - // with the resolved function version, as the same runtime instance may - // be invokable with - // multiple different aliases. - // * **GCP:** The [URI of the - // resource](https://cloud.google.com/iam/docs/full-resource-names) - // * **Azure:** The [Fully Qualified Resource - // ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id) - // of the invoked function, - // *not* the function app, having the form - // `/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/`. - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider. - FaaSIDKey = attribute.Key("faas.id") - - // FaaSVersionKey is the attribute Key conforming to the "faas.version" - // semantic conventions. It represents the immutable version of the - // function being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '26', 'pinkfroid-00002' - // Note: Depending on the cloud provider and platform, use: - // - // * **AWS Lambda:** The [function - // version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - // (an integer represented as a decimal string). - // * **Google Cloud Run:** The - // [revision](https://cloud.google.com/run/docs/managing/revisions) - // (i.e., the function name plus the revision suffix). - // * **Google Cloud Functions:** The value of the - // [`K_REVISION` environment - // variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - // * **Azure Functions:** Not applicable. Do not set this attribute. - FaaSVersionKey = attribute.Key("faas.version") - - // FaaSInstanceKey is the attribute Key conforming to the "faas.instance" - // semantic conventions. It represents the execution environment ID as a - // string, that will be potentially reused for other invocations to the - // same function/function version. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2021/06/28/[$LATEST]2f399eb14537447da05ab2a2e39309de' - // Note: * **AWS Lambda:** Use the (full) log stream name. - FaaSInstanceKey = attribute.Key("faas.instance") - - // FaaSMaxMemoryKey is the attribute Key conforming to the - // "faas.max_memory" semantic conventions. It represents the amount of - // memory available to the serverless function in MiB. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 128 - // Note: It's recommended to set this attribute since e.g. too little - // memory can easily stop a Java AWS Lambda function from working - // correctly. On AWS Lambda, the environment variable - // `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. - FaaSMaxMemoryKey = attribute.Key("faas.max_memory") -) - -// FaaSName returns an attribute KeyValue conforming to the "faas.name" -// semantic conventions. It represents the name of the single function that -// this runtime instance executes. -func FaaSName(val string) attribute.KeyValue { - return FaaSNameKey.String(val) -} - -// FaaSID returns an attribute KeyValue conforming to the "faas.id" semantic -// conventions. It represents the unique ID of the single function that this -// runtime instance executes. -func FaaSID(val string) attribute.KeyValue { - return FaaSIDKey.String(val) -} - -// FaaSVersion returns an attribute KeyValue conforming to the -// "faas.version" semantic conventions. It represents the immutable version of -// the function being executed. -func FaaSVersion(val string) attribute.KeyValue { - return FaaSVersionKey.String(val) -} - -// FaaSInstance returns an attribute KeyValue conforming to the -// "faas.instance" semantic conventions. It represents the execution -// environment ID as a string, that will be potentially reused for other -// invocations to the same function/function version. -func FaaSInstance(val string) attribute.KeyValue { - return FaaSInstanceKey.String(val) -} - -// FaaSMaxMemory returns an attribute KeyValue conforming to the -// "faas.max_memory" semantic conventions. It represents the amount of memory -// available to the serverless function in MiB. -func FaaSMaxMemory(val int) attribute.KeyValue { - return FaaSMaxMemoryKey.Int(val) -} - -// A host is defined as a general computing instance. -const ( - // HostIDKey is the attribute Key conforming to the "host.id" semantic - // conventions. It represents the unique host ID. For Cloud, this must be - // the instance_id assigned by the cloud provider. For non-containerized - // Linux systems, the `machine-id` located in `/etc/machine-id` or - // `/var/lib/dbus/machine-id` may be used. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'fdbf79e8af94cb7f9e8df36789187052' - HostIDKey = attribute.Key("host.id") - - // HostNameKey is the attribute Key conforming to the "host.name" semantic - // conventions. It represents the name of the host. On Unix systems, it may - // contain what the hostname command returns, or the fully qualified - // hostname, or another name specified by the user. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-test' - HostNameKey = attribute.Key("host.name") - - // HostTypeKey is the attribute Key conforming to the "host.type" semantic - // conventions. It represents the type of host. For Cloud, this must be the - // machine type. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'n1-standard-1' - HostTypeKey = attribute.Key("host.type") - - // HostArchKey is the attribute Key conforming to the "host.arch" semantic - // conventions. It represents the CPU architecture the host system is - // running on. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - HostArchKey = attribute.Key("host.arch") - - // HostImageNameKey is the attribute Key conforming to the - // "host.image.name" semantic conventions. It represents the name of the VM - // image or OS install the host was instantiated from. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'infra-ami-eks-worker-node-7d4ec78312', 'CentOS-8-x86_64-1905' - HostImageNameKey = attribute.Key("host.image.name") - - // HostImageIDKey is the attribute Key conforming to the "host.image.id" - // semantic conventions. It represents the vM image ID. For Cloud, this - // value is from the provider. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ami-07b06b442921831e5' - HostImageIDKey = attribute.Key("host.image.id") - - // HostImageVersionKey is the attribute Key conforming to the - // "host.image.version" semantic conventions. It represents the version - // string of the VM image as defined in [Version - // Attributes](README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0.1' - HostImageVersionKey = attribute.Key("host.image.version") -) - -var ( - // AMD64 - HostArchAMD64 = HostArchKey.String("amd64") - // ARM32 - HostArchARM32 = HostArchKey.String("arm32") - // ARM64 - HostArchARM64 = HostArchKey.String("arm64") - // Itanium - HostArchIA64 = HostArchKey.String("ia64") - // 32-bit PowerPC - HostArchPPC32 = HostArchKey.String("ppc32") - // 64-bit PowerPC - HostArchPPC64 = HostArchKey.String("ppc64") - // IBM z/Architecture - HostArchS390x = HostArchKey.String("s390x") - // 32-bit x86 - HostArchX86 = HostArchKey.String("x86") -) - -// HostID returns an attribute KeyValue conforming to the "host.id" semantic -// conventions. It represents the unique host ID. For Cloud, this must be the -// instance_id assigned by the cloud provider. For non-containerized Linux -// systems, the `machine-id` located in `/etc/machine-id` or -// `/var/lib/dbus/machine-id` may be used. -func HostID(val string) attribute.KeyValue { - return HostIDKey.String(val) -} - -// HostName returns an attribute KeyValue conforming to the "host.name" -// semantic conventions. It represents the name of the host. On Unix systems, -// it may contain what the hostname command returns, or the fully qualified -// hostname, or another name specified by the user. -func HostName(val string) attribute.KeyValue { - return HostNameKey.String(val) -} - -// HostType returns an attribute KeyValue conforming to the "host.type" -// semantic conventions. It represents the type of host. For Cloud, this must -// be the machine type. -func HostType(val string) attribute.KeyValue { - return HostTypeKey.String(val) -} - -// HostImageName returns an attribute KeyValue conforming to the -// "host.image.name" semantic conventions. It represents the name of the VM -// image or OS install the host was instantiated from. -func HostImageName(val string) attribute.KeyValue { - return HostImageNameKey.String(val) -} - -// HostImageID returns an attribute KeyValue conforming to the -// "host.image.id" semantic conventions. It represents the vM image ID. For -// Cloud, this value is from the provider. -func HostImageID(val string) attribute.KeyValue { - return HostImageIDKey.String(val) -} - -// HostImageVersion returns an attribute KeyValue conforming to the -// "host.image.version" semantic conventions. It represents the version string -// of the VM image as defined in [Version -// Attributes](README.md#version-attributes). -func HostImageVersion(val string) attribute.KeyValue { - return HostImageVersionKey.String(val) -} - -// A Kubernetes Cluster. -const ( - // K8SClusterNameKey is the attribute Key conforming to the - // "k8s.cluster.name" semantic conventions. It represents the name of the - // cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-cluster' - K8SClusterNameKey = attribute.Key("k8s.cluster.name") -) - -// K8SClusterName returns an attribute KeyValue conforming to the -// "k8s.cluster.name" semantic conventions. It represents the name of the -// cluster. -func K8SClusterName(val string) attribute.KeyValue { - return K8SClusterNameKey.String(val) -} - -// A Kubernetes Node object. -const ( - // K8SNodeNameKey is the attribute Key conforming to the "k8s.node.name" - // semantic conventions. It represents the name of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'node-1' - K8SNodeNameKey = attribute.Key("k8s.node.name") - - // K8SNodeUIDKey is the attribute Key conforming to the "k8s.node.uid" - // semantic conventions. It represents the UID of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2' - K8SNodeUIDKey = attribute.Key("k8s.node.uid") -) - -// K8SNodeName returns an attribute KeyValue conforming to the -// "k8s.node.name" semantic conventions. It represents the name of the Node. -func K8SNodeName(val string) attribute.KeyValue { - return K8SNodeNameKey.String(val) -} - -// K8SNodeUID returns an attribute KeyValue conforming to the "k8s.node.uid" -// semantic conventions. It represents the UID of the Node. -func K8SNodeUID(val string) attribute.KeyValue { - return K8SNodeUIDKey.String(val) -} - -// A Kubernetes Namespace. -const ( - // K8SNamespaceNameKey is the attribute Key conforming to the - // "k8s.namespace.name" semantic conventions. It represents the name of the - // namespace that the pod is running in. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'default' - K8SNamespaceNameKey = attribute.Key("k8s.namespace.name") -) - -// K8SNamespaceName returns an attribute KeyValue conforming to the -// "k8s.namespace.name" semantic conventions. It represents the name of the -// namespace that the pod is running in. -func K8SNamespaceName(val string) attribute.KeyValue { - return K8SNamespaceNameKey.String(val) -} - -// A Kubernetes Pod object. -const ( - // K8SPodUIDKey is the attribute Key conforming to the "k8s.pod.uid" - // semantic conventions. It represents the UID of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SPodUIDKey = attribute.Key("k8s.pod.uid") - - // K8SPodNameKey is the attribute Key conforming to the "k8s.pod.name" - // semantic conventions. It represents the name of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry-pod-autoconf' - K8SPodNameKey = attribute.Key("k8s.pod.name") -) - -// K8SPodUID returns an attribute KeyValue conforming to the "k8s.pod.uid" -// semantic conventions. It represents the UID of the Pod. -func K8SPodUID(val string) attribute.KeyValue { - return K8SPodUIDKey.String(val) -} - -// K8SPodName returns an attribute KeyValue conforming to the "k8s.pod.name" -// semantic conventions. It represents the name of the Pod. -func K8SPodName(val string) attribute.KeyValue { - return K8SPodNameKey.String(val) -} - -// A container in a -// [PodTemplate](https://kubernetes.io/docs/concepts/workloads/pods/#pod-templates). -const ( - // K8SContainerNameKey is the attribute Key conforming to the - // "k8s.container.name" semantic conventions. It represents the name of the - // Container from Pod specification, must be unique within a Pod. Container - // runtime usually uses different globally unique name (`container.name`). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'redis' - K8SContainerNameKey = attribute.Key("k8s.container.name") - - // K8SContainerRestartCountKey is the attribute Key conforming to the - // "k8s.container.restart_count" semantic conventions. It represents the - // number of times the container was restarted. This attribute can be used - // to identify a particular container (running or stopped) within a - // container spec. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 0, 2 - K8SContainerRestartCountKey = attribute.Key("k8s.container.restart_count") -) - -// K8SContainerName returns an attribute KeyValue conforming to the -// "k8s.container.name" semantic conventions. It represents the name of the -// Container from Pod specification, must be unique within a Pod. Container -// runtime usually uses different globally unique name (`container.name`). -func K8SContainerName(val string) attribute.KeyValue { - return K8SContainerNameKey.String(val) -} - -// K8SContainerRestartCount returns an attribute KeyValue conforming to the -// "k8s.container.restart_count" semantic conventions. It represents the number -// of times the container was restarted. This attribute can be used to identify -// a particular container (running or stopped) within a container spec. -func K8SContainerRestartCount(val int) attribute.KeyValue { - return K8SContainerRestartCountKey.Int(val) -} - -// A Kubernetes ReplicaSet object. -const ( - // K8SReplicaSetUIDKey is the attribute Key conforming to the - // "k8s.replicaset.uid" semantic conventions. It represents the UID of the - // ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SReplicaSetUIDKey = attribute.Key("k8s.replicaset.uid") - - // K8SReplicaSetNameKey is the attribute Key conforming to the - // "k8s.replicaset.name" semantic conventions. It represents the name of - // the ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SReplicaSetNameKey = attribute.Key("k8s.replicaset.name") -) - -// K8SReplicaSetUID returns an attribute KeyValue conforming to the -// "k8s.replicaset.uid" semantic conventions. It represents the UID of the -// ReplicaSet. -func K8SReplicaSetUID(val string) attribute.KeyValue { - return K8SReplicaSetUIDKey.String(val) -} - -// K8SReplicaSetName returns an attribute KeyValue conforming to the -// "k8s.replicaset.name" semantic conventions. It represents the name of the -// ReplicaSet. -func K8SReplicaSetName(val string) attribute.KeyValue { - return K8SReplicaSetNameKey.String(val) -} - -// A Kubernetes Deployment object. -const ( - // K8SDeploymentUIDKey is the attribute Key conforming to the - // "k8s.deployment.uid" semantic conventions. It represents the UID of the - // Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDeploymentUIDKey = attribute.Key("k8s.deployment.uid") - - // K8SDeploymentNameKey is the attribute Key conforming to the - // "k8s.deployment.name" semantic conventions. It represents the name of - // the Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SDeploymentNameKey = attribute.Key("k8s.deployment.name") -) - -// K8SDeploymentUID returns an attribute KeyValue conforming to the -// "k8s.deployment.uid" semantic conventions. It represents the UID of the -// Deployment. -func K8SDeploymentUID(val string) attribute.KeyValue { - return K8SDeploymentUIDKey.String(val) -} - -// K8SDeploymentName returns an attribute KeyValue conforming to the -// "k8s.deployment.name" semantic conventions. It represents the name of the -// Deployment. -func K8SDeploymentName(val string) attribute.KeyValue { - return K8SDeploymentNameKey.String(val) -} - -// A Kubernetes StatefulSet object. -const ( - // K8SStatefulSetUIDKey is the attribute Key conforming to the - // "k8s.statefulset.uid" semantic conventions. It represents the UID of the - // StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SStatefulSetUIDKey = attribute.Key("k8s.statefulset.uid") - - // K8SStatefulSetNameKey is the attribute Key conforming to the - // "k8s.statefulset.name" semantic conventions. It represents the name of - // the StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SStatefulSetNameKey = attribute.Key("k8s.statefulset.name") -) - -// K8SStatefulSetUID returns an attribute KeyValue conforming to the -// "k8s.statefulset.uid" semantic conventions. It represents the UID of the -// StatefulSet. -func K8SStatefulSetUID(val string) attribute.KeyValue { - return K8SStatefulSetUIDKey.String(val) -} - -// K8SStatefulSetName returns an attribute KeyValue conforming to the -// "k8s.statefulset.name" semantic conventions. It represents the name of the -// StatefulSet. -func K8SStatefulSetName(val string) attribute.KeyValue { - return K8SStatefulSetNameKey.String(val) -} - -// A Kubernetes DaemonSet object. -const ( - // K8SDaemonSetUIDKey is the attribute Key conforming to the - // "k8s.daemonset.uid" semantic conventions. It represents the UID of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDaemonSetUIDKey = attribute.Key("k8s.daemonset.uid") - - // K8SDaemonSetNameKey is the attribute Key conforming to the - // "k8s.daemonset.name" semantic conventions. It represents the name of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SDaemonSetNameKey = attribute.Key("k8s.daemonset.name") -) - -// K8SDaemonSetUID returns an attribute KeyValue conforming to the -// "k8s.daemonset.uid" semantic conventions. It represents the UID of the -// DaemonSet. -func K8SDaemonSetUID(val string) attribute.KeyValue { - return K8SDaemonSetUIDKey.String(val) -} - -// K8SDaemonSetName returns an attribute KeyValue conforming to the -// "k8s.daemonset.name" semantic conventions. It represents the name of the -// DaemonSet. -func K8SDaemonSetName(val string) attribute.KeyValue { - return K8SDaemonSetNameKey.String(val) -} - -// A Kubernetes Job object. -const ( - // K8SJobUIDKey is the attribute Key conforming to the "k8s.job.uid" - // semantic conventions. It represents the UID of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SJobUIDKey = attribute.Key("k8s.job.uid") - - // K8SJobNameKey is the attribute Key conforming to the "k8s.job.name" - // semantic conventions. It represents the name of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SJobNameKey = attribute.Key("k8s.job.name") -) - -// K8SJobUID returns an attribute KeyValue conforming to the "k8s.job.uid" -// semantic conventions. It represents the UID of the Job. -func K8SJobUID(val string) attribute.KeyValue { - return K8SJobUIDKey.String(val) -} - -// K8SJobName returns an attribute KeyValue conforming to the "k8s.job.name" -// semantic conventions. It represents the name of the Job. -func K8SJobName(val string) attribute.KeyValue { - return K8SJobNameKey.String(val) -} - -// A Kubernetes CronJob object. -const ( - // K8SCronJobUIDKey is the attribute Key conforming to the - // "k8s.cronjob.uid" semantic conventions. It represents the UID of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SCronJobUIDKey = attribute.Key("k8s.cronjob.uid") - - // K8SCronJobNameKey is the attribute Key conforming to the - // "k8s.cronjob.name" semantic conventions. It represents the name of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - K8SCronJobNameKey = attribute.Key("k8s.cronjob.name") -) - -// K8SCronJobUID returns an attribute KeyValue conforming to the -// "k8s.cronjob.uid" semantic conventions. It represents the UID of the -// CronJob. -func K8SCronJobUID(val string) attribute.KeyValue { - return K8SCronJobUIDKey.String(val) -} - -// K8SCronJobName returns an attribute KeyValue conforming to the -// "k8s.cronjob.name" semantic conventions. It represents the name of the -// CronJob. -func K8SCronJobName(val string) attribute.KeyValue { - return K8SCronJobNameKey.String(val) -} - -// The operating system (OS) on which the process represented by this resource -// is running. -const ( - // OSTypeKey is the attribute Key conforming to the "os.type" semantic - // conventions. It represents the operating system type. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - OSTypeKey = attribute.Key("os.type") - - // OSDescriptionKey is the attribute Key conforming to the "os.description" - // semantic conventions. It represents the human readable (not intended to - // be parsed) OS version information, like e.g. reported by `ver` or - // `lsb_release -a` commands. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Microsoft Windows [Version 10.0.18363.778]', 'Ubuntu 18.04.1 - // LTS' - OSDescriptionKey = attribute.Key("os.description") - - // OSNameKey is the attribute Key conforming to the "os.name" semantic - // conventions. It represents the human readable operating system name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'iOS', 'Android', 'Ubuntu' - OSNameKey = attribute.Key("os.name") - - // OSVersionKey is the attribute Key conforming to the "os.version" - // semantic conventions. It represents the version string of the operating - // system as defined in [Version - // Attributes](../../resource/semantic_conventions/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '14.2.1', '18.04.1' - OSVersionKey = attribute.Key("os.version") -) - -var ( - // Microsoft Windows - OSTypeWindows = OSTypeKey.String("windows") - // Linux - OSTypeLinux = OSTypeKey.String("linux") - // Apple Darwin - OSTypeDarwin = OSTypeKey.String("darwin") - // FreeBSD - OSTypeFreeBSD = OSTypeKey.String("freebsd") - // NetBSD - OSTypeNetBSD = OSTypeKey.String("netbsd") - // OpenBSD - OSTypeOpenBSD = OSTypeKey.String("openbsd") - // DragonFly BSD - OSTypeDragonflyBSD = OSTypeKey.String("dragonflybsd") - // HP-UX (Hewlett Packard Unix) - OSTypeHPUX = OSTypeKey.String("hpux") - // AIX (Advanced Interactive eXecutive) - OSTypeAIX = OSTypeKey.String("aix") - // SunOS, Oracle Solaris - OSTypeSolaris = OSTypeKey.String("solaris") - // IBM z/OS - OSTypeZOS = OSTypeKey.String("z_os") -) - -// OSDescription returns an attribute KeyValue conforming to the -// "os.description" semantic conventions. It represents the human readable (not -// intended to be parsed) OS version information, like e.g. reported by `ver` -// or `lsb_release -a` commands. -func OSDescription(val string) attribute.KeyValue { - return OSDescriptionKey.String(val) -} - -// OSName returns an attribute KeyValue conforming to the "os.name" semantic -// conventions. It represents the human readable operating system name. -func OSName(val string) attribute.KeyValue { - return OSNameKey.String(val) -} - -// OSVersion returns an attribute KeyValue conforming to the "os.version" -// semantic conventions. It represents the version string of the operating -// system as defined in [Version -// Attributes](../../resource/semantic_conventions/README.md#version-attributes). -func OSVersion(val string) attribute.KeyValue { - return OSVersionKey.String(val) -} - -// An operating system process. -const ( - // ProcessPIDKey is the attribute Key conforming to the "process.pid" - // semantic conventions. It represents the process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 1234 - ProcessPIDKey = attribute.Key("process.pid") - - // ProcessParentPIDKey is the attribute Key conforming to the - // "process.parent_pid" semantic conventions. It represents the parent - // Process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 111 - ProcessParentPIDKey = attribute.Key("process.parent_pid") - - // ProcessExecutableNameKey is the attribute Key conforming to the - // "process.executable.name" semantic conventions. It represents the name - // of the process executable. On Linux based systems, can be set to the - // `Name` in `proc/[pid]/status`. On Windows, can be set to the base name - // of `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'otelcol' - ProcessExecutableNameKey = attribute.Key("process.executable.name") - - // ProcessExecutablePathKey is the attribute Key conforming to the - // "process.executable.path" semantic conventions. It represents the full - // path to the process executable. On Linux based systems, can be set to - // the target of `proc/[pid]/exe`. On Windows, can be set to the result of - // `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: '/usr/bin/cmd/otelcol' - ProcessExecutablePathKey = attribute.Key("process.executable.path") - - // ProcessCommandKey is the attribute Key conforming to the - // "process.command" semantic conventions. It represents the command used - // to launch the process (i.e. the command name). On Linux based systems, - // can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can - // be set to the first parameter extracted from `GetCommandLineW`. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'cmd/otelcol' - ProcessCommandKey = attribute.Key("process.command") - - // ProcessCommandLineKey is the attribute Key conforming to the - // "process.command_line" semantic conventions. It represents the full - // command used to launch the process as a single string representing the - // full command. On Windows, can be set to the result of `GetCommandLineW`. - // Do not set this if you have to assemble it just for monitoring; use - // `process.command_args` instead. - // - // Type: string - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'C:\\cmd\\otecol --config="my directory\\config.yaml"' - ProcessCommandLineKey = attribute.Key("process.command_line") - - // ProcessCommandArgsKey is the attribute Key conforming to the - // "process.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) as received - // by the process. On Linux-based systems (and some other Unixoid systems - // supporting procfs), can be set according to the list of null-delimited - // strings extracted from `proc/[pid]/cmdline`. For libc-based executables, - // this would be the full argv vector passed to `main`. - // - // Type: string[] - // RequirementLevel: ConditionallyRequired (See alternative attributes - // below.) - // Stability: stable - // Examples: 'cmd/otecol', '--config=config.yaml' - ProcessCommandArgsKey = attribute.Key("process.command_args") - - // ProcessOwnerKey is the attribute Key conforming to the "process.owner" - // semantic conventions. It represents the username of the user that owns - // the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'root' - ProcessOwnerKey = attribute.Key("process.owner") -) - -// ProcessPID returns an attribute KeyValue conforming to the "process.pid" -// semantic conventions. It represents the process identifier (PID). -func ProcessPID(val int) attribute.KeyValue { - return ProcessPIDKey.Int(val) -} - -// ProcessParentPID returns an attribute KeyValue conforming to the -// "process.parent_pid" semantic conventions. It represents the parent Process -// identifier (PID). -func ProcessParentPID(val int) attribute.KeyValue { - return ProcessParentPIDKey.Int(val) -} - -// ProcessExecutableName returns an attribute KeyValue conforming to the -// "process.executable.name" semantic conventions. It represents the name of -// the process executable. On Linux based systems, can be set to the `Name` in -// `proc/[pid]/status`. On Windows, can be set to the base name of -// `GetProcessImageFileNameW`. -func ProcessExecutableName(val string) attribute.KeyValue { - return ProcessExecutableNameKey.String(val) -} - -// ProcessExecutablePath returns an attribute KeyValue conforming to the -// "process.executable.path" semantic conventions. It represents the full path -// to the process executable. On Linux based systems, can be set to the target -// of `proc/[pid]/exe`. On Windows, can be set to the result of -// `GetProcessImageFileNameW`. -func ProcessExecutablePath(val string) attribute.KeyValue { - return ProcessExecutablePathKey.String(val) -} - -// ProcessCommand returns an attribute KeyValue conforming to the -// "process.command" semantic conventions. It represents the command used to -// launch the process (i.e. the command name). On Linux based systems, can be -// set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to -// the first parameter extracted from `GetCommandLineW`. -func ProcessCommand(val string) attribute.KeyValue { - return ProcessCommandKey.String(val) -} - -// ProcessCommandLine returns an attribute KeyValue conforming to the -// "process.command_line" semantic conventions. It represents the full command -// used to launch the process as a single string representing the full command. -// On Windows, can be set to the result of `GetCommandLineW`. Do not set this -// if you have to assemble it just for monitoring; use `process.command_args` -// instead. -func ProcessCommandLine(val string) attribute.KeyValue { - return ProcessCommandLineKey.String(val) -} - -// ProcessCommandArgs returns an attribute KeyValue conforming to the -// "process.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) as received by -// the process. On Linux-based systems (and some other Unixoid systems -// supporting procfs), can be set according to the list of null-delimited -// strings extracted from `proc/[pid]/cmdline`. For libc-based executables, -// this would be the full argv vector passed to `main`. -func ProcessCommandArgs(val ...string) attribute.KeyValue { - return ProcessCommandArgsKey.StringSlice(val) -} - -// ProcessOwner returns an attribute KeyValue conforming to the -// "process.owner" semantic conventions. It represents the username of the user -// that owns the process. -func ProcessOwner(val string) attribute.KeyValue { - return ProcessOwnerKey.String(val) -} - -// The single (language) runtime instance which is monitored. -const ( - // ProcessRuntimeNameKey is the attribute Key conforming to the - // "process.runtime.name" semantic conventions. It represents the name of - // the runtime of this process. For compiled native binaries, this SHOULD - // be the name of the compiler. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'OpenJDK Runtime Environment' - ProcessRuntimeNameKey = attribute.Key("process.runtime.name") - - // ProcessRuntimeVersionKey is the attribute Key conforming to the - // "process.runtime.version" semantic conventions. It represents the - // version of the runtime of this process, as returned by the runtime - // without modification. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '14.0.2' - ProcessRuntimeVersionKey = attribute.Key("process.runtime.version") - - // ProcessRuntimeDescriptionKey is the attribute Key conforming to the - // "process.runtime.description" semantic conventions. It represents an - // additional description about the runtime of the process, for example a - // specific vendor customization of the runtime environment. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0' - ProcessRuntimeDescriptionKey = attribute.Key("process.runtime.description") -) - -// ProcessRuntimeName returns an attribute KeyValue conforming to the -// "process.runtime.name" semantic conventions. It represents the name of the -// runtime of this process. For compiled native binaries, this SHOULD be the -// name of the compiler. -func ProcessRuntimeName(val string) attribute.KeyValue { - return ProcessRuntimeNameKey.String(val) -} - -// ProcessRuntimeVersion returns an attribute KeyValue conforming to the -// "process.runtime.version" semantic conventions. It represents the version of -// the runtime of this process, as returned by the runtime without -// modification. -func ProcessRuntimeVersion(val string) attribute.KeyValue { - return ProcessRuntimeVersionKey.String(val) -} - -// ProcessRuntimeDescription returns an attribute KeyValue conforming to the -// "process.runtime.description" semantic conventions. It represents an -// additional description about the runtime of the process, for example a -// specific vendor customization of the runtime environment. -func ProcessRuntimeDescription(val string) attribute.KeyValue { - return ProcessRuntimeDescriptionKey.String(val) -} - -// A service instance. -const ( - // ServiceNameKey is the attribute Key conforming to the "service.name" - // semantic conventions. It represents the logical name of the service. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'shoppingcart' - // Note: MUST be the same for all instances of horizontally scaled - // services. If the value was not specified, SDKs MUST fallback to - // `unknown_service:` concatenated with - // [`process.executable.name`](process.md#process), e.g. - // `unknown_service:bash`. If `process.executable.name` is not available, - // the value MUST be set to `unknown_service`. - ServiceNameKey = attribute.Key("service.name") - - // ServiceNamespaceKey is the attribute Key conforming to the - // "service.namespace" semantic conventions. It represents a namespace for - // `service.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Shop' - // Note: A string value having a meaning that helps to distinguish a group - // of services, for example the team name that owns a group of services. - // `service.name` is expected to be unique within the same namespace. If - // `service.namespace` is not specified in the Resource then `service.name` - // is expected to be unique for all services that have no explicit - // namespace defined (so the empty/unspecified namespace is simply one more - // valid namespace). Zero-length namespace string is assumed equal to - // unspecified namespace. - ServiceNamespaceKey = attribute.Key("service.namespace") - - // ServiceInstanceIDKey is the attribute Key conforming to the - // "service.instance.id" semantic conventions. It represents the string ID - // of the service instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '627cc493-f310-47de-96bd-71410b7dec09' - // Note: MUST be unique for each instance of the same - // `service.namespace,service.name` pair (in other words - // `service.namespace,service.name,service.instance.id` triplet MUST be - // globally unique). The ID helps to distinguish instances of the same - // service that exist at the same time (e.g. instances of a horizontally - // scaled service). It is preferable for the ID to be persistent and stay - // the same for the lifetime of the service instance, however it is - // acceptable that the ID is ephemeral and changes during important - // lifetime events for the service (e.g. service restarts). If the service - // has no inherent unique ID that can be used as the value of this - // attribute it is recommended to generate a random Version 1 or Version 4 - // RFC 4122 UUID (services aiming for reproducible UUIDs may also use - // Version 5, see RFC 4122 for more recommendations). - ServiceInstanceIDKey = attribute.Key("service.instance.id") - - // ServiceVersionKey is the attribute Key conforming to the - // "service.version" semantic conventions. It represents the version string - // of the service API or implementation. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2.0.0' - ServiceVersionKey = attribute.Key("service.version") -) - -// ServiceName returns an attribute KeyValue conforming to the -// "service.name" semantic conventions. It represents the logical name of the -// service. -func ServiceName(val string) attribute.KeyValue { - return ServiceNameKey.String(val) -} - -// ServiceNamespace returns an attribute KeyValue conforming to the -// "service.namespace" semantic conventions. It represents a namespace for -// `service.name`. -func ServiceNamespace(val string) attribute.KeyValue { - return ServiceNamespaceKey.String(val) -} - -// ServiceInstanceID returns an attribute KeyValue conforming to the -// "service.instance.id" semantic conventions. It represents the string ID of -// the service instance. -func ServiceInstanceID(val string) attribute.KeyValue { - return ServiceInstanceIDKey.String(val) -} - -// ServiceVersion returns an attribute KeyValue conforming to the -// "service.version" semantic conventions. It represents the version string of -// the service API or implementation. -func ServiceVersion(val string) attribute.KeyValue { - return ServiceVersionKey.String(val) -} - -// The telemetry SDK used to capture data recorded by the instrumentation -// libraries. -const ( - // TelemetrySDKNameKey is the attribute Key conforming to the - // "telemetry.sdk.name" semantic conventions. It represents the name of the - // telemetry SDK as defined above. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'opentelemetry' - TelemetrySDKNameKey = attribute.Key("telemetry.sdk.name") - - // TelemetrySDKLanguageKey is the attribute Key conforming to the - // "telemetry.sdk.language" semantic conventions. It represents the - // language of the telemetry SDK. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - TelemetrySDKLanguageKey = attribute.Key("telemetry.sdk.language") - - // TelemetrySDKVersionKey is the attribute Key conforming to the - // "telemetry.sdk.version" semantic conventions. It represents the version - // string of the telemetry SDK. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.2.3' - TelemetrySDKVersionKey = attribute.Key("telemetry.sdk.version") - - // TelemetryAutoVersionKey is the attribute Key conforming to the - // "telemetry.auto.version" semantic conventions. It represents the version - // string of the auto instrumentation agent, if used. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.2.3' - TelemetryAutoVersionKey = attribute.Key("telemetry.auto.version") -) - -var ( - // cpp - TelemetrySDKLanguageCPP = TelemetrySDKLanguageKey.String("cpp") - // dotnet - TelemetrySDKLanguageDotnet = TelemetrySDKLanguageKey.String("dotnet") - // erlang - TelemetrySDKLanguageErlang = TelemetrySDKLanguageKey.String("erlang") - // go - TelemetrySDKLanguageGo = TelemetrySDKLanguageKey.String("go") - // java - TelemetrySDKLanguageJava = TelemetrySDKLanguageKey.String("java") - // nodejs - TelemetrySDKLanguageNodejs = TelemetrySDKLanguageKey.String("nodejs") - // php - TelemetrySDKLanguagePHP = TelemetrySDKLanguageKey.String("php") - // python - TelemetrySDKLanguagePython = TelemetrySDKLanguageKey.String("python") - // ruby - TelemetrySDKLanguageRuby = TelemetrySDKLanguageKey.String("ruby") - // webjs - TelemetrySDKLanguageWebjs = TelemetrySDKLanguageKey.String("webjs") - // swift - TelemetrySDKLanguageSwift = TelemetrySDKLanguageKey.String("swift") -) - -// TelemetrySDKName returns an attribute KeyValue conforming to the -// "telemetry.sdk.name" semantic conventions. It represents the name of the -// telemetry SDK as defined above. -func TelemetrySDKName(val string) attribute.KeyValue { - return TelemetrySDKNameKey.String(val) -} - -// TelemetrySDKVersion returns an attribute KeyValue conforming to the -// "telemetry.sdk.version" semantic conventions. It represents the version -// string of the telemetry SDK. -func TelemetrySDKVersion(val string) attribute.KeyValue { - return TelemetrySDKVersionKey.String(val) -} - -// TelemetryAutoVersion returns an attribute KeyValue conforming to the -// "telemetry.auto.version" semantic conventions. It represents the version -// string of the auto instrumentation agent, if used. -func TelemetryAutoVersion(val string) attribute.KeyValue { - return TelemetryAutoVersionKey.String(val) -} - -// Resource describing the packaged software running the application code. Web -// engines are typically executed using process.runtime. -const ( - // WebEngineNameKey is the attribute Key conforming to the "webengine.name" - // semantic conventions. It represents the name of the web engine. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'WildFly' - WebEngineNameKey = attribute.Key("webengine.name") - - // WebEngineVersionKey is the attribute Key conforming to the - // "webengine.version" semantic conventions. It represents the version of - // the web engine. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '21.0.0' - WebEngineVersionKey = attribute.Key("webengine.version") - - // WebEngineDescriptionKey is the attribute Key conforming to the - // "webengine.description" semantic conventions. It represents the - // additional description of the web engine (e.g. detailed version and - // edition information). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - - // 2.2.2.Final' - WebEngineDescriptionKey = attribute.Key("webengine.description") -) - -// WebEngineName returns an attribute KeyValue conforming to the -// "webengine.name" semantic conventions. It represents the name of the web -// engine. -func WebEngineName(val string) attribute.KeyValue { - return WebEngineNameKey.String(val) -} - -// WebEngineVersion returns an attribute KeyValue conforming to the -// "webengine.version" semantic conventions. It represents the version of the -// web engine. -func WebEngineVersion(val string) attribute.KeyValue { - return WebEngineVersionKey.String(val) -} - -// WebEngineDescription returns an attribute KeyValue conforming to the -// "webengine.description" semantic conventions. It represents the additional -// description of the web engine (e.g. detailed version and edition -// information). -func WebEngineDescription(val string) attribute.KeyValue { - return WebEngineDescriptionKey.String(val) -} - -// Attributes used by non-OTLP exporters to represent OpenTelemetry Scope's -// concepts. -const ( - // OtelScopeNameKey is the attribute Key conforming to the - // "otel.scope.name" semantic conventions. It represents the name of the - // instrumentation scope - (`InstrumentationScope.Name` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'io.opentelemetry.contrib.mongodb' - OtelScopeNameKey = attribute.Key("otel.scope.name") - - // OtelScopeVersionKey is the attribute Key conforming to the - // "otel.scope.version" semantic conventions. It represents the version of - // the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.0.0' - OtelScopeVersionKey = attribute.Key("otel.scope.version") -) - -// OtelScopeName returns an attribute KeyValue conforming to the -// "otel.scope.name" semantic conventions. It represents the name of the -// instrumentation scope - (`InstrumentationScope.Name` in OTLP). -func OtelScopeName(val string) attribute.KeyValue { - return OtelScopeNameKey.String(val) -} - -// OtelScopeVersion returns an attribute KeyValue conforming to the -// "otel.scope.version" semantic conventions. It represents the version of the -// instrumentation scope - (`InstrumentationScope.Version` in OTLP). -func OtelScopeVersion(val string) attribute.KeyValue { - return OtelScopeVersionKey.String(val) -} - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry -// Scope's concepts. -const ( - // OtelLibraryNameKey is the attribute Key conforming to the - // "otel.library.name" semantic conventions. It represents the deprecated, - // use the `otel.scope.name` attribute. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'io.opentelemetry.contrib.mongodb' - OtelLibraryNameKey = attribute.Key("otel.library.name") - - // OtelLibraryVersionKey is the attribute Key conforming to the - // "otel.library.version" semantic conventions. It represents the - // deprecated, use the `otel.scope.version` attribute. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '1.0.0' - OtelLibraryVersionKey = attribute.Key("otel.library.version") -) - -// OtelLibraryName returns an attribute KeyValue conforming to the -// "otel.library.name" semantic conventions. It represents the deprecated, use -// the `otel.scope.name` attribute. -func OtelLibraryName(val string) attribute.KeyValue { - return OtelLibraryNameKey.String(val) -} - -// OtelLibraryVersion returns an attribute KeyValue conforming to the -// "otel.library.version" semantic conventions. It represents the deprecated, -// use the `otel.scope.version` attribute. -func OtelLibraryVersion(val string) attribute.KeyValue { - return OtelLibraryVersionKey.String(val) -} diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/schema.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/schema.go deleted file mode 100644 index 634a1dce0..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/schema.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -// SchemaURL is the schema URL that matches the version of the semantic conventions -// that this package defines. Semconv packages starting from v1.4.0 must declare -// non-empty schema URL in the form https://opentelemetry.io/schemas/ -const SchemaURL = "https://opentelemetry.io/schemas/1.17.0" diff --git a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/trace.go b/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/trace.go deleted file mode 100644 index 21497bb6b..000000000 --- a/constraint/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/trace.go +++ /dev/null @@ -1,3364 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.17.0" - -import "go.opentelemetry.io/otel/attribute" - -// The shared attributes used to report a single exception associated with a -// span or log. -const ( - // ExceptionTypeKey is the attribute Key conforming to the "exception.type" - // semantic conventions. It represents the type of the exception (its - // fully-qualified class name, if applicable). The dynamic type of the - // exception should be preferred over the static type in languages that - // support it. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'java.net.ConnectException', 'OSError' - ExceptionTypeKey = attribute.Key("exception.type") - - // ExceptionMessageKey is the attribute Key conforming to the - // "exception.message" semantic conventions. It represents the exception - // message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Division by zero', "Can't convert 'int' object to str - // implicitly" - ExceptionMessageKey = attribute.Key("exception.message") - - // ExceptionStacktraceKey is the attribute Key conforming to the - // "exception.stacktrace" semantic conventions. It represents a stacktrace - // as a string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Exception in thread "main" java.lang.RuntimeException: Test - // exception\\n at ' - // 'com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - ExceptionStacktraceKey = attribute.Key("exception.stacktrace") -) - -// ExceptionType returns an attribute KeyValue conforming to the -// "exception.type" semantic conventions. It represents the type of the -// exception (its fully-qualified class name, if applicable). The dynamic type -// of the exception should be preferred over the static type in languages that -// support it. -func ExceptionType(val string) attribute.KeyValue { - return ExceptionTypeKey.String(val) -} - -// ExceptionMessage returns an attribute KeyValue conforming to the -// "exception.message" semantic conventions. It represents the exception -// message. -func ExceptionMessage(val string) attribute.KeyValue { - return ExceptionMessageKey.String(val) -} - -// ExceptionStacktrace returns an attribute KeyValue conforming to the -// "exception.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func ExceptionStacktrace(val string) attribute.KeyValue { - return ExceptionStacktraceKey.String(val) -} - -// Attributes for Events represented using Log Records. -const ( - // EventNameKey is the attribute Key conforming to the "event.name" - // semantic conventions. It represents the name identifies the event. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'click', 'exception' - EventNameKey = attribute.Key("event.name") - - // EventDomainKey is the attribute Key conforming to the "event.domain" - // semantic conventions. It represents the domain identifies the business - // context for the events. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: Events across different domains may have same `event.name`, yet be - // unrelated events. - EventDomainKey = attribute.Key("event.domain") -) - -var ( - // Events from browser apps - EventDomainBrowser = EventDomainKey.String("browser") - // Events from mobile apps - EventDomainDevice = EventDomainKey.String("device") - // Events from Kubernetes - EventDomainK8S = EventDomainKey.String("k8s") -) - -// EventName returns an attribute KeyValue conforming to the "event.name" -// semantic conventions. It represents the name identifies the event. -func EventName(val string) attribute.KeyValue { - return EventNameKey.String(val) -} - -// Span attributes used by AWS Lambda (in addition to general `faas` -// attributes). -const ( - // AWSLambdaInvokedARNKey is the attribute Key conforming to the - // "aws.lambda.invoked_arn" semantic conventions. It represents the full - // invoked ARN as provided on the `Context` passed to the function - // (`Lambda-Runtime-Invoked-Function-ARN` header on the - // `/runtime/invocation/next` applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' - // Note: This may be different from `faas.id` if an alias is involved. - AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") -) - -// AWSLambdaInvokedARN returns an attribute KeyValue conforming to the -// "aws.lambda.invoked_arn" semantic conventions. It represents the full -// invoked ARN as provided on the `Context` passed to the function -// (`Lambda-Runtime-Invoked-Function-ARN` header on the -// `/runtime/invocation/next` applicable). -func AWSLambdaInvokedARN(val string) attribute.KeyValue { - return AWSLambdaInvokedARNKey.String(val) -} - -// Attributes for CloudEvents. CloudEvents is a specification on how to define -// event data in a standard way. These attributes can be attached to spans when -// performing operations with CloudEvents, regardless of the protocol being -// used. -const ( - // CloudeventsEventIDKey is the attribute Key conforming to the - // "cloudevents.event_id" semantic conventions. It represents the - // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) - // uniquely identifies the event. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' - CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") - - // CloudeventsEventSourceKey is the attribute Key conforming to the - // "cloudevents.event_source" semantic conventions. It represents the - // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) - // identifies the context in which an event happened. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'https://github.com/cloudevents', - // '/cloudevents/spec/pull/123', 'my-service' - CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") - - // CloudeventsEventSpecVersionKey is the attribute Key conforming to the - // "cloudevents.event_spec_version" semantic conventions. It represents the - // [version of the CloudEvents - // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) - // which the event uses. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '1.0' - CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") - - // CloudeventsEventTypeKey is the attribute Key conforming to the - // "cloudevents.event_type" semantic conventions. It represents the - // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) - // contains a value describing the type of event related to the originating - // occurrence. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'com.github.pull_request.opened', - // 'com.example.object.deleted.v2' - CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") - - // CloudeventsEventSubjectKey is the attribute Key conforming to the - // "cloudevents.event_subject" semantic conventions. It represents the - // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) - // of the event in the context of the event producer (identified by - // source). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'mynewfile.jpg' - CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") -) - -// CloudeventsEventID returns an attribute KeyValue conforming to the -// "cloudevents.event_id" semantic conventions. It represents the -// [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) -// uniquely identifies the event. -func CloudeventsEventID(val string) attribute.KeyValue { - return CloudeventsEventIDKey.String(val) -} - -// CloudeventsEventSource returns an attribute KeyValue conforming to the -// "cloudevents.event_source" semantic conventions. It represents the -// [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) -// identifies the context in which an event happened. -func CloudeventsEventSource(val string) attribute.KeyValue { - return CloudeventsEventSourceKey.String(val) -} - -// CloudeventsEventSpecVersion returns an attribute KeyValue conforming to -// the "cloudevents.event_spec_version" semantic conventions. It represents the -// [version of the CloudEvents -// specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) -// which the event uses. -func CloudeventsEventSpecVersion(val string) attribute.KeyValue { - return CloudeventsEventSpecVersionKey.String(val) -} - -// CloudeventsEventType returns an attribute KeyValue conforming to the -// "cloudevents.event_type" semantic conventions. It represents the -// [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) -// contains a value describing the type of event related to the originating -// occurrence. -func CloudeventsEventType(val string) attribute.KeyValue { - return CloudeventsEventTypeKey.String(val) -} - -// CloudeventsEventSubject returns an attribute KeyValue conforming to the -// "cloudevents.event_subject" semantic conventions. It represents the -// [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) -// of the event in the context of the event producer (identified by source). -func CloudeventsEventSubject(val string) attribute.KeyValue { - return CloudeventsEventSubjectKey.String(val) -} - -// Semantic conventions for the OpenTracing Shim -const ( - // OpentracingRefTypeKey is the attribute Key conforming to the - // "opentracing.ref_type" semantic conventions. It represents the - // parent-child Reference type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: The causal relationship between a child Span and a parent Span. - OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") -) - -var ( - // The parent Span depends on the child Span in some capacity - OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") - // The parent Span does not depend in any way on the result of the child Span - OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") -) - -// The attributes used to perform database client calls. -const ( - // DBSystemKey is the attribute Key conforming to the "db.system" semantic - // conventions. It represents an identifier for the database management - // system (DBMS) product being used. See below for a list of well-known - // identifiers. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - DBSystemKey = attribute.Key("db.system") - - // DBConnectionStringKey is the attribute Key conforming to the - // "db.connection_string" semantic conventions. It represents the - // connection string used to connect to the database. It is recommended to - // remove embedded credentials. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Server=(localdb)\\v11.0;Integrated Security=true;' - DBConnectionStringKey = attribute.Key("db.connection_string") - - // DBUserKey is the attribute Key conforming to the "db.user" semantic - // conventions. It represents the username for accessing the database. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'readonly_user', 'reporting_user' - DBUserKey = attribute.Key("db.user") - - // DBJDBCDriverClassnameKey is the attribute Key conforming to the - // "db.jdbc.driver_classname" semantic conventions. It represents the - // fully-qualified class name of the [Java Database Connectivity - // (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) - // driver used to connect. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'org.postgresql.Driver', - // 'com.microsoft.sqlserver.jdbc.SQLServerDriver' - DBJDBCDriverClassnameKey = attribute.Key("db.jdbc.driver_classname") - - // DBNameKey is the attribute Key conforming to the "db.name" semantic - // conventions. It represents the this attribute is used to report the name - // of the database being accessed. For commands that switch the database, - // this should be set to the target database (even if the command fails). - // - // Type: string - // RequirementLevel: ConditionallyRequired (If applicable.) - // Stability: stable - // Examples: 'customers', 'main' - // Note: In some SQL databases, the database name to be used is called - // "schema name". In case there are multiple layers that could be - // considered for database name (e.g. Oracle instance name and schema - // name), the database name to be used is the more specific layer (e.g. - // Oracle schema name). - DBNameKey = attribute.Key("db.name") - - // DBStatementKey is the attribute Key conforming to the "db.statement" - // semantic conventions. It represents the database statement being - // executed. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If applicable and not - // explicitly disabled via instrumentation configuration.) - // Stability: stable - // Examples: 'SELECT * FROM wuser_table', 'SET mykey "WuValue"' - // Note: The value may be sanitized to exclude sensitive information. - DBStatementKey = attribute.Key("db.statement") - - // DBOperationKey is the attribute Key conforming to the "db.operation" - // semantic conventions. It represents the name of the operation being - // executed, e.g. the [MongoDB command - // name](https://docs.mongodb.com/manual/reference/command/#database-operations) - // such as `findAndModify`, or the SQL keyword. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If `db.statement` is not - // applicable.) - // Stability: stable - // Examples: 'findAndModify', 'HMSET', 'SELECT' - // Note: When setting this to an SQL keyword, it is not recommended to - // attempt any client-side parsing of `db.statement` just to get this - // property, but it should be set if the operation name is provided by the - // library being instrumented. If the SQL statement has an ambiguous - // operation, or performs more than one operation, this value may be - // omitted. - DBOperationKey = attribute.Key("db.operation") -) - -var ( - // Some other SQL database. Fallback only. See notes - DBSystemOtherSQL = DBSystemKey.String("other_sql") - // Microsoft SQL Server - DBSystemMSSQL = DBSystemKey.String("mssql") - // MySQL - DBSystemMySQL = DBSystemKey.String("mysql") - // Oracle Database - DBSystemOracle = DBSystemKey.String("oracle") - // IBM DB2 - DBSystemDB2 = DBSystemKey.String("db2") - // PostgreSQL - DBSystemPostgreSQL = DBSystemKey.String("postgresql") - // Amazon Redshift - DBSystemRedshift = DBSystemKey.String("redshift") - // Apache Hive - DBSystemHive = DBSystemKey.String("hive") - // Cloudscape - DBSystemCloudscape = DBSystemKey.String("cloudscape") - // HyperSQL DataBase - DBSystemHSQLDB = DBSystemKey.String("hsqldb") - // Progress Database - DBSystemProgress = DBSystemKey.String("progress") - // SAP MaxDB - DBSystemMaxDB = DBSystemKey.String("maxdb") - // SAP HANA - DBSystemHanaDB = DBSystemKey.String("hanadb") - // Ingres - DBSystemIngres = DBSystemKey.String("ingres") - // FirstSQL - DBSystemFirstSQL = DBSystemKey.String("firstsql") - // EnterpriseDB - DBSystemEDB = DBSystemKey.String("edb") - // InterSystems Caché - DBSystemCache = DBSystemKey.String("cache") - // Adabas (Adaptable Database System) - DBSystemAdabas = DBSystemKey.String("adabas") - // Firebird - DBSystemFirebird = DBSystemKey.String("firebird") - // Apache Derby - DBSystemDerby = DBSystemKey.String("derby") - // FileMaker - DBSystemFilemaker = DBSystemKey.String("filemaker") - // Informix - DBSystemInformix = DBSystemKey.String("informix") - // InstantDB - DBSystemInstantDB = DBSystemKey.String("instantdb") - // InterBase - DBSystemInterbase = DBSystemKey.String("interbase") - // MariaDB - DBSystemMariaDB = DBSystemKey.String("mariadb") - // Netezza - DBSystemNetezza = DBSystemKey.String("netezza") - // Pervasive PSQL - DBSystemPervasive = DBSystemKey.String("pervasive") - // PointBase - DBSystemPointbase = DBSystemKey.String("pointbase") - // SQLite - DBSystemSqlite = DBSystemKey.String("sqlite") - // Sybase - DBSystemSybase = DBSystemKey.String("sybase") - // Teradata - DBSystemTeradata = DBSystemKey.String("teradata") - // Vertica - DBSystemVertica = DBSystemKey.String("vertica") - // H2 - DBSystemH2 = DBSystemKey.String("h2") - // ColdFusion IMQ - DBSystemColdfusion = DBSystemKey.String("coldfusion") - // Apache Cassandra - DBSystemCassandra = DBSystemKey.String("cassandra") - // Apache HBase - DBSystemHBase = DBSystemKey.String("hbase") - // MongoDB - DBSystemMongoDB = DBSystemKey.String("mongodb") - // Redis - DBSystemRedis = DBSystemKey.String("redis") - // Couchbase - DBSystemCouchbase = DBSystemKey.String("couchbase") - // CouchDB - DBSystemCouchDB = DBSystemKey.String("couchdb") - // Microsoft Azure Cosmos DB - DBSystemCosmosDB = DBSystemKey.String("cosmosdb") - // Amazon DynamoDB - DBSystemDynamoDB = DBSystemKey.String("dynamodb") - // Neo4j - DBSystemNeo4j = DBSystemKey.String("neo4j") - // Apache Geode - DBSystemGeode = DBSystemKey.String("geode") - // Elasticsearch - DBSystemElasticsearch = DBSystemKey.String("elasticsearch") - // Memcached - DBSystemMemcached = DBSystemKey.String("memcached") - // CockroachDB - DBSystemCockroachdb = DBSystemKey.String("cockroachdb") - // OpenSearch - DBSystemOpensearch = DBSystemKey.String("opensearch") - // ClickHouse - DBSystemClickhouse = DBSystemKey.String("clickhouse") -) - -// DBConnectionString returns an attribute KeyValue conforming to the -// "db.connection_string" semantic conventions. It represents the connection -// string used to connect to the database. It is recommended to remove embedded -// credentials. -func DBConnectionString(val string) attribute.KeyValue { - return DBConnectionStringKey.String(val) -} - -// DBUser returns an attribute KeyValue conforming to the "db.user" semantic -// conventions. It represents the username for accessing the database. -func DBUser(val string) attribute.KeyValue { - return DBUserKey.String(val) -} - -// DBJDBCDriverClassname returns an attribute KeyValue conforming to the -// "db.jdbc.driver_classname" semantic conventions. It represents the -// fully-qualified class name of the [Java Database Connectivity -// (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver -// used to connect. -func DBJDBCDriverClassname(val string) attribute.KeyValue { - return DBJDBCDriverClassnameKey.String(val) -} - -// DBName returns an attribute KeyValue conforming to the "db.name" semantic -// conventions. It represents the this attribute is used to report the name of -// the database being accessed. For commands that switch the database, this -// should be set to the target database (even if the command fails). -func DBName(val string) attribute.KeyValue { - return DBNameKey.String(val) -} - -// DBStatement returns an attribute KeyValue conforming to the -// "db.statement" semantic conventions. It represents the database statement -// being executed. -func DBStatement(val string) attribute.KeyValue { - return DBStatementKey.String(val) -} - -// DBOperation returns an attribute KeyValue conforming to the -// "db.operation" semantic conventions. It represents the name of the operation -// being executed, e.g. the [MongoDB command -// name](https://docs.mongodb.com/manual/reference/command/#database-operations) -// such as `findAndModify`, or the SQL keyword. -func DBOperation(val string) attribute.KeyValue { - return DBOperationKey.String(val) -} - -// Connection-level attributes for Microsoft SQL Server -const ( - // DBMSSQLInstanceNameKey is the attribute Key conforming to the - // "db.mssql.instance_name" semantic conventions. It represents the - // Microsoft SQL Server [instance - // name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) - // connecting to. This name is used to determine the port of a named - // instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MSSQLSERVER' - // Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no - // longer required (but still recommended if non-standard). - DBMSSQLInstanceNameKey = attribute.Key("db.mssql.instance_name") -) - -// DBMSSQLInstanceName returns an attribute KeyValue conforming to the -// "db.mssql.instance_name" semantic conventions. It represents the Microsoft -// SQL Server [instance -// name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) -// connecting to. This name is used to determine the port of a named instance. -func DBMSSQLInstanceName(val string) attribute.KeyValue { - return DBMSSQLInstanceNameKey.String(val) -} - -// Call-level attributes for Cassandra -const ( - // DBCassandraPageSizeKey is the attribute Key conforming to the - // "db.cassandra.page_size" semantic conventions. It represents the fetch - // size used for paging, i.e. how many rows will be returned at once. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 5000 - DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") - - // DBCassandraConsistencyLevelKey is the attribute Key conforming to the - // "db.cassandra.consistency_level" semantic conventions. It represents the - // consistency level of the query. Based on consistency values from - // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") - - // DBCassandraTableKey is the attribute Key conforming to the - // "db.cassandra.table" semantic conventions. It represents the name of the - // primary table that the operation is acting upon, including the keyspace - // name (if applicable). - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'mytable' - // Note: This mirrors the db.sql.table attribute but references cassandra - // rather than sql. It is not recommended to attempt any client-side - // parsing of `db.statement` just to get this property, but it should be - // set if it is provided by the library being instrumented. If the - // operation is acting upon an anonymous table, or more than one table, - // this value MUST NOT be set. - DBCassandraTableKey = attribute.Key("db.cassandra.table") - - // DBCassandraIdempotenceKey is the attribute Key conforming to the - // "db.cassandra.idempotence" semantic conventions. It represents the - // whether or not the query is idempotent. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") - - // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming - // to the "db.cassandra.speculative_execution_count" semantic conventions. - // It represents the number of times a query was speculatively executed. - // Not set or `0` if the query was not executed speculatively. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 0, 2 - DBCassandraSpeculativeExecutionCountKey = attribute.Key("db.cassandra.speculative_execution_count") - - // DBCassandraCoordinatorIDKey is the attribute Key conforming to the - // "db.cassandra.coordinator.id" semantic conventions. It represents the ID - // of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' - DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") - - // DBCassandraCoordinatorDCKey is the attribute Key conforming to the - // "db.cassandra.coordinator.dc" semantic conventions. It represents the - // data center of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'us-west-2' - DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") -) - -var ( - // all - DBCassandraConsistencyLevelAll = DBCassandraConsistencyLevelKey.String("all") - // each_quorum - DBCassandraConsistencyLevelEachQuorum = DBCassandraConsistencyLevelKey.String("each_quorum") - // quorum - DBCassandraConsistencyLevelQuorum = DBCassandraConsistencyLevelKey.String("quorum") - // local_quorum - DBCassandraConsistencyLevelLocalQuorum = DBCassandraConsistencyLevelKey.String("local_quorum") - // one - DBCassandraConsistencyLevelOne = DBCassandraConsistencyLevelKey.String("one") - // two - DBCassandraConsistencyLevelTwo = DBCassandraConsistencyLevelKey.String("two") - // three - DBCassandraConsistencyLevelThree = DBCassandraConsistencyLevelKey.String("three") - // local_one - DBCassandraConsistencyLevelLocalOne = DBCassandraConsistencyLevelKey.String("local_one") - // any - DBCassandraConsistencyLevelAny = DBCassandraConsistencyLevelKey.String("any") - // serial - DBCassandraConsistencyLevelSerial = DBCassandraConsistencyLevelKey.String("serial") - // local_serial - DBCassandraConsistencyLevelLocalSerial = DBCassandraConsistencyLevelKey.String("local_serial") -) - -// DBCassandraPageSize returns an attribute KeyValue conforming to the -// "db.cassandra.page_size" semantic conventions. It represents the fetch size -// used for paging, i.e. how many rows will be returned at once. -func DBCassandraPageSize(val int) attribute.KeyValue { - return DBCassandraPageSizeKey.Int(val) -} - -// DBCassandraTable returns an attribute KeyValue conforming to the -// "db.cassandra.table" semantic conventions. It represents the name of the -// primary table that the operation is acting upon, including the keyspace name -// (if applicable). -func DBCassandraTable(val string) attribute.KeyValue { - return DBCassandraTableKey.String(val) -} - -// DBCassandraIdempotence returns an attribute KeyValue conforming to the -// "db.cassandra.idempotence" semantic conventions. It represents the whether -// or not the query is idempotent. -func DBCassandraIdempotence(val bool) attribute.KeyValue { - return DBCassandraIdempotenceKey.Bool(val) -} - -// DBCassandraSpeculativeExecutionCount returns an attribute KeyValue -// conforming to the "db.cassandra.speculative_execution_count" semantic -// conventions. It represents the number of times a query was speculatively -// executed. Not set or `0` if the query was not executed speculatively. -func DBCassandraSpeculativeExecutionCount(val int) attribute.KeyValue { - return DBCassandraSpeculativeExecutionCountKey.Int(val) -} - -// DBCassandraCoordinatorID returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.id" semantic conventions. It represents the ID of -// the coordinating node for a query. -func DBCassandraCoordinatorID(val string) attribute.KeyValue { - return DBCassandraCoordinatorIDKey.String(val) -} - -// DBCassandraCoordinatorDC returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.dc" semantic conventions. It represents the data -// center of the coordinating node for a query. -func DBCassandraCoordinatorDC(val string) attribute.KeyValue { - return DBCassandraCoordinatorDCKey.String(val) -} - -// Call-level attributes for Redis -const ( - // DBRedisDBIndexKey is the attribute Key conforming to the - // "db.redis.database_index" semantic conventions. It represents the index - // of the database being accessed as used in the [`SELECT` - // command](https://redis.io/commands/select), provided as an integer. To - // be used instead of the generic `db.name` attribute. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If other than the default - // database (`0`).) - // Stability: stable - // Examples: 0, 1, 15 - DBRedisDBIndexKey = attribute.Key("db.redis.database_index") -) - -// DBRedisDBIndex returns an attribute KeyValue conforming to the -// "db.redis.database_index" semantic conventions. It represents the index of -// the database being accessed as used in the [`SELECT` -// command](https://redis.io/commands/select), provided as an integer. To be -// used instead of the generic `db.name` attribute. -func DBRedisDBIndex(val int) attribute.KeyValue { - return DBRedisDBIndexKey.Int(val) -} - -// Call-level attributes for MongoDB -const ( - // DBMongoDBCollectionKey is the attribute Key conforming to the - // "db.mongodb.collection" semantic conventions. It represents the - // collection being accessed within the database stated in `db.name`. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'customers', 'products' - DBMongoDBCollectionKey = attribute.Key("db.mongodb.collection") -) - -// DBMongoDBCollection returns an attribute KeyValue conforming to the -// "db.mongodb.collection" semantic conventions. It represents the collection -// being accessed within the database stated in `db.name`. -func DBMongoDBCollection(val string) attribute.KeyValue { - return DBMongoDBCollectionKey.String(val) -} - -// Call-level attributes for SQL databases -const ( - // DBSQLTableKey is the attribute Key conforming to the "db.sql.table" - // semantic conventions. It represents the name of the primary table that - // the operation is acting upon, including the database name (if - // applicable). - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'public.users', 'customers' - // Note: It is not recommended to attempt any client-side parsing of - // `db.statement` just to get this property, but it should be set if it is - // provided by the library being instrumented. If the operation is acting - // upon an anonymous table, or more than one table, this value MUST NOT be - // set. - DBSQLTableKey = attribute.Key("db.sql.table") -) - -// DBSQLTable returns an attribute KeyValue conforming to the "db.sql.table" -// semantic conventions. It represents the name of the primary table that the -// operation is acting upon, including the database name (if applicable). -func DBSQLTable(val string) attribute.KeyValue { - return DBSQLTableKey.String(val) -} - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry Span's -// concepts. -const ( - // OtelStatusCodeKey is the attribute Key conforming to the - // "otel.status_code" semantic conventions. It represents the name of the - // code, either "OK" or "ERROR". MUST NOT be set if the status code is - // UNSET. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - OtelStatusCodeKey = attribute.Key("otel.status_code") - - // OtelStatusDescriptionKey is the attribute Key conforming to the - // "otel.status_description" semantic conventions. It represents the - // description of the Status if it has a value, otherwise not set. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'resource not found' - OtelStatusDescriptionKey = attribute.Key("otel.status_description") -) - -var ( - // The operation has been validated by an Application developer or Operator to have completed successfully - OtelStatusCodeOk = OtelStatusCodeKey.String("OK") - // The operation contains an error - OtelStatusCodeError = OtelStatusCodeKey.String("ERROR") -) - -// OtelStatusDescription returns an attribute KeyValue conforming to the -// "otel.status_description" semantic conventions. It represents the -// description of the Status if it has a value, otherwise not set. -func OtelStatusDescription(val string) attribute.KeyValue { - return OtelStatusDescriptionKey.String(val) -} - -// This semantic convention describes an instance of a function that runs -// without provisioning or managing of servers (also known as serverless -// functions or Function as a Service (FaaS)) with spans. -const ( - // FaaSTriggerKey is the attribute Key conforming to the "faas.trigger" - // semantic conventions. It represents the type of the trigger which caused - // this function execution. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: For the server/consumer span on the incoming side, - // `faas.trigger` MUST be set. - // - // Clients invoking FaaS instances usually cannot set `faas.trigger`, - // since they would typically need to look in the payload to determine - // the event type. If clients set it, it should be the same as the - // trigger that corresponding incoming would have (i.e., this has - // nothing to do with the underlying transport used to make the API - // call to invoke the lambda, which is often HTTP). - FaaSTriggerKey = attribute.Key("faas.trigger") - - // FaaSExecutionKey is the attribute Key conforming to the "faas.execution" - // semantic conventions. It represents the execution ID of the current - // function execution. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'af9d5aa4-a685-4c5f-a22b-444f80b3cc28' - FaaSExecutionKey = attribute.Key("faas.execution") -) - -var ( - // A response to some data source operation such as a database or filesystem read/write - FaaSTriggerDatasource = FaaSTriggerKey.String("datasource") - // To provide an answer to an inbound HTTP request - FaaSTriggerHTTP = FaaSTriggerKey.String("http") - // A function is set to be executed when messages are sent to a messaging system - FaaSTriggerPubsub = FaaSTriggerKey.String("pubsub") - // A function is scheduled to be executed regularly - FaaSTriggerTimer = FaaSTriggerKey.String("timer") - // If none of the others apply - FaaSTriggerOther = FaaSTriggerKey.String("other") -) - -// FaaSExecution returns an attribute KeyValue conforming to the -// "faas.execution" semantic conventions. It represents the execution ID of the -// current function execution. -func FaaSExecution(val string) attribute.KeyValue { - return FaaSExecutionKey.String(val) -} - -// Semantic Convention for FaaS triggered as a response to some data source -// operation such as a database or filesystem read/write. -const ( - // FaaSDocumentCollectionKey is the attribute Key conforming to the - // "faas.document.collection" semantic conventions. It represents the name - // of the source on which the triggering operation was performed. For - // example, in Cloud Storage or S3 corresponds to the bucket name, and in - // Cosmos DB to the database name. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myBucketName', 'myDBName' - FaaSDocumentCollectionKey = attribute.Key("faas.document.collection") - - // FaaSDocumentOperationKey is the attribute Key conforming to the - // "faas.document.operation" semantic conventions. It represents the - // describes the type of the operation that was performed on the data. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - FaaSDocumentOperationKey = attribute.Key("faas.document.operation") - - // FaaSDocumentTimeKey is the attribute Key conforming to the - // "faas.document.time" semantic conventions. It represents a string - // containing the time when the data was accessed in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2020-01-23T13:47:06Z' - FaaSDocumentTimeKey = attribute.Key("faas.document.time") - - // FaaSDocumentNameKey is the attribute Key conforming to the - // "faas.document.name" semantic conventions. It represents the document - // name/table subjected to the operation. For example, in Cloud Storage or - // S3 is the name of the file, and in Cosmos DB the table name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'myFile.txt', 'myTableName' - FaaSDocumentNameKey = attribute.Key("faas.document.name") -) - -var ( - // When a new object is created - FaaSDocumentOperationInsert = FaaSDocumentOperationKey.String("insert") - // When an object is modified - FaaSDocumentOperationEdit = FaaSDocumentOperationKey.String("edit") - // When an object is deleted - FaaSDocumentOperationDelete = FaaSDocumentOperationKey.String("delete") -) - -// FaaSDocumentCollection returns an attribute KeyValue conforming to the -// "faas.document.collection" semantic conventions. It represents the name of -// the source on which the triggering operation was performed. For example, in -// Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the -// database name. -func FaaSDocumentCollection(val string) attribute.KeyValue { - return FaaSDocumentCollectionKey.String(val) -} - -// FaaSDocumentTime returns an attribute KeyValue conforming to the -// "faas.document.time" semantic conventions. It represents a string containing -// the time when the data was accessed in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSDocumentTime(val string) attribute.KeyValue { - return FaaSDocumentTimeKey.String(val) -} - -// FaaSDocumentName returns an attribute KeyValue conforming to the -// "faas.document.name" semantic conventions. It represents the document -// name/table subjected to the operation. For example, in Cloud Storage or S3 -// is the name of the file, and in Cosmos DB the table name. -func FaaSDocumentName(val string) attribute.KeyValue { - return FaaSDocumentNameKey.String(val) -} - -// Semantic Convention for FaaS scheduled to be executed regularly. -const ( - // FaaSTimeKey is the attribute Key conforming to the "faas.time" semantic - // conventions. It represents a string containing the function invocation - // time in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '2020-01-23T13:47:06Z' - FaaSTimeKey = attribute.Key("faas.time") - - // FaaSCronKey is the attribute Key conforming to the "faas.cron" semantic - // conventions. It represents a string containing the schedule period as - // [Cron - // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '0/5 * * * ? *' - FaaSCronKey = attribute.Key("faas.cron") -) - -// FaaSTime returns an attribute KeyValue conforming to the "faas.time" -// semantic conventions. It represents a string containing the function -// invocation time in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSTime(val string) attribute.KeyValue { - return FaaSTimeKey.String(val) -} - -// FaaSCron returns an attribute KeyValue conforming to the "faas.cron" -// semantic conventions. It represents a string containing the schedule period -// as [Cron -// Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). -func FaaSCron(val string) attribute.KeyValue { - return FaaSCronKey.String(val) -} - -// Contains additional attributes for incoming FaaS spans. -const ( - // FaaSColdstartKey is the attribute Key conforming to the "faas.coldstart" - // semantic conventions. It represents a boolean that is true if the - // serverless function is executed for the first time (aka cold-start). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - FaaSColdstartKey = attribute.Key("faas.coldstart") -) - -// FaaSColdstart returns an attribute KeyValue conforming to the -// "faas.coldstart" semantic conventions. It represents a boolean that is true -// if the serverless function is executed for the first time (aka cold-start). -func FaaSColdstart(val bool) attribute.KeyValue { - return FaaSColdstartKey.Bool(val) -} - -// Contains additional attributes for outgoing FaaS spans. -const ( - // FaaSInvokedNameKey is the attribute Key conforming to the - // "faas.invoked_name" semantic conventions. It represents the name of the - // invoked function. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'my-function' - // Note: SHOULD be equal to the `faas.name` resource attribute of the - // invoked function. - FaaSInvokedNameKey = attribute.Key("faas.invoked_name") - - // FaaSInvokedProviderKey is the attribute Key conforming to the - // "faas.invoked_provider" semantic conventions. It represents the cloud - // provider of the invoked function. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: SHOULD be equal to the `cloud.provider` resource attribute of the - // invoked function. - FaaSInvokedProviderKey = attribute.Key("faas.invoked_provider") - - // FaaSInvokedRegionKey is the attribute Key conforming to the - // "faas.invoked_region" semantic conventions. It represents the cloud - // region of the invoked function. - // - // Type: string - // RequirementLevel: ConditionallyRequired (For some cloud providers, like - // AWS or GCP, the region in which a function is hosted is essential to - // uniquely identify the function and also part of its endpoint. Since it's - // part of the endpoint being called, the region is always known to - // clients. In these cases, `faas.invoked_region` MUST be set accordingly. - // If the region is unknown to the client or not required for identifying - // the invoked function, setting `faas.invoked_region` is optional.) - // Stability: stable - // Examples: 'eu-central-1' - // Note: SHOULD be equal to the `cloud.region` resource attribute of the - // invoked function. - FaaSInvokedRegionKey = attribute.Key("faas.invoked_region") -) - -var ( - // Alibaba Cloud - FaaSInvokedProviderAlibabaCloud = FaaSInvokedProviderKey.String("alibaba_cloud") - // Amazon Web Services - FaaSInvokedProviderAWS = FaaSInvokedProviderKey.String("aws") - // Microsoft Azure - FaaSInvokedProviderAzure = FaaSInvokedProviderKey.String("azure") - // Google Cloud Platform - FaaSInvokedProviderGCP = FaaSInvokedProviderKey.String("gcp") - // Tencent Cloud - FaaSInvokedProviderTencentCloud = FaaSInvokedProviderKey.String("tencent_cloud") -) - -// FaaSInvokedName returns an attribute KeyValue conforming to the -// "faas.invoked_name" semantic conventions. It represents the name of the -// invoked function. -func FaaSInvokedName(val string) attribute.KeyValue { - return FaaSInvokedNameKey.String(val) -} - -// FaaSInvokedRegion returns an attribute KeyValue conforming to the -// "faas.invoked_region" semantic conventions. It represents the cloud region -// of the invoked function. -func FaaSInvokedRegion(val string) attribute.KeyValue { - return FaaSInvokedRegionKey.String(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetTransportKey is the attribute Key conforming to the "net.transport" - // semantic conventions. It represents the transport protocol used. See - // note below. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - NetTransportKey = attribute.Key("net.transport") - - // NetAppProtocolNameKey is the attribute Key conforming to the - // "net.app.protocol.name" semantic conventions. It represents the - // application layer protocol used. The value SHOULD be normalized to - // lowercase. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'amqp', 'http', 'mqtt' - NetAppProtocolNameKey = attribute.Key("net.app.protocol.name") - - // NetAppProtocolVersionKey is the attribute Key conforming to the - // "net.app.protocol.version" semantic conventions. It represents the - // version of the application layer protocol used. See note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '3.1.1' - // Note: `net.app.protocol.version` refers to the version of the protocol - // used and might be different from the protocol client's version. If the - // HTTP client used has a version of `0.27.2`, but sends HTTP version - // `1.1`, this attribute should be set to `1.1`. - NetAppProtocolVersionKey = attribute.Key("net.app.protocol.version") - - // NetSockPeerNameKey is the attribute Key conforming to the - // "net.sock.peer.name" semantic conventions. It represents the remote - // socket peer name. - // - // Type: string - // RequirementLevel: Recommended (If available and different from - // `net.peer.name` and if `net.sock.peer.addr` is set.) - // Stability: stable - // Examples: 'proxy.example.com' - NetSockPeerNameKey = attribute.Key("net.sock.peer.name") - - // NetSockPeerAddrKey is the attribute Key conforming to the - // "net.sock.peer.addr" semantic conventions. It represents the remote - // socket peer address: IPv4 or IPv6 for internet protocols, path for local - // communication, - // [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '127.0.0.1', '/tmp/mysql.sock' - NetSockPeerAddrKey = attribute.Key("net.sock.peer.addr") - - // NetSockPeerPortKey is the attribute Key conforming to the - // "net.sock.peer.port" semantic conventions. It represents the remote - // socket peer port. - // - // Type: int - // RequirementLevel: Recommended (If defined for the address family and if - // different than `net.peer.port` and if `net.sock.peer.addr` is set.) - // Stability: stable - // Examples: 16456 - NetSockPeerPortKey = attribute.Key("net.sock.peer.port") - - // NetSockFamilyKey is the attribute Key conforming to the - // "net.sock.family" semantic conventions. It represents the protocol - // [address - // family](https://man7.org/linux/man-pages/man7/address_families.7.html) - // which is used for communication. - // - // Type: Enum - // RequirementLevel: ConditionallyRequired (If different than `inet` and if - // any of `net.sock.peer.addr` or `net.sock.host.addr` are set. Consumers - // of telemetry SHOULD accept both IPv4 and IPv6 formats for the address in - // `net.sock.peer.addr` if `net.sock.family` is not set. This is to support - // instrumentations that follow previous versions of this document.) - // Stability: stable - // Examples: 'inet6', 'bluetooth' - NetSockFamilyKey = attribute.Key("net.sock.family") - - // NetPeerNameKey is the attribute Key conforming to the "net.peer.name" - // semantic conventions. It represents the logical remote hostname, see - // note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'example.com' - // Note: `net.peer.name` SHOULD NOT be set if capturing it would require an - // extra DNS lookup. - NetPeerNameKey = attribute.Key("net.peer.name") - - // NetPeerPortKey is the attribute Key conforming to the "net.peer.port" - // semantic conventions. It represents the logical remote port number - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 80, 8080, 443 - NetPeerPortKey = attribute.Key("net.peer.port") - - // NetHostNameKey is the attribute Key conforming to the "net.host.name" - // semantic conventions. It represents the logical local hostname or - // similar, see note below. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'localhost' - NetHostNameKey = attribute.Key("net.host.name") - - // NetHostPortKey is the attribute Key conforming to the "net.host.port" - // semantic conventions. It represents the logical local port number, - // preferably the one that the peer used to connect - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 8080 - NetHostPortKey = attribute.Key("net.host.port") - - // NetSockHostAddrKey is the attribute Key conforming to the - // "net.sock.host.addr" semantic conventions. It represents the local - // socket address. Useful in case of a multi-IP host. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '192.168.0.1' - NetSockHostAddrKey = attribute.Key("net.sock.host.addr") - - // NetSockHostPortKey is the attribute Key conforming to the - // "net.sock.host.port" semantic conventions. It represents the local - // socket port number. - // - // Type: int - // RequirementLevel: Recommended (If defined for the address family and if - // different than `net.host.port` and if `net.sock.host.addr` is set.) - // Stability: stable - // Examples: 35555 - NetSockHostPortKey = attribute.Key("net.sock.host.port") - - // NetHostConnectionTypeKey is the attribute Key conforming to the - // "net.host.connection.type" semantic conventions. It represents the - // internet connection type currently being used by the host. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'wifi' - NetHostConnectionTypeKey = attribute.Key("net.host.connection.type") - - // NetHostConnectionSubtypeKey is the attribute Key conforming to the - // "net.host.connection.subtype" semantic conventions. It represents the - // this describes more details regarding the connection.type. It may be the - // type of cell technology connection, but it could be used for describing - // details about a wifi connection. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'LTE' - NetHostConnectionSubtypeKey = attribute.Key("net.host.connection.subtype") - - // NetHostCarrierNameKey is the attribute Key conforming to the - // "net.host.carrier.name" semantic conventions. It represents the name of - // the mobile carrier. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'sprint' - NetHostCarrierNameKey = attribute.Key("net.host.carrier.name") - - // NetHostCarrierMccKey is the attribute Key conforming to the - // "net.host.carrier.mcc" semantic conventions. It represents the mobile - // carrier country code. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '310' - NetHostCarrierMccKey = attribute.Key("net.host.carrier.mcc") - - // NetHostCarrierMncKey is the attribute Key conforming to the - // "net.host.carrier.mnc" semantic conventions. It represents the mobile - // carrier network code. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '001' - NetHostCarrierMncKey = attribute.Key("net.host.carrier.mnc") - - // NetHostCarrierIccKey is the attribute Key conforming to the - // "net.host.carrier.icc" semantic conventions. It represents the ISO - // 3166-1 alpha-2 2-character country code associated with the mobile - // carrier network. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'DE' - NetHostCarrierIccKey = attribute.Key("net.host.carrier.icc") -) - -var ( - // ip_tcp - NetTransportTCP = NetTransportKey.String("ip_tcp") - // ip_udp - NetTransportUDP = NetTransportKey.String("ip_udp") - // Named or anonymous pipe. See note below - NetTransportPipe = NetTransportKey.String("pipe") - // In-process communication - NetTransportInProc = NetTransportKey.String("inproc") - // Something else (non IP-based) - NetTransportOther = NetTransportKey.String("other") -) - -var ( - // IPv4 address - NetSockFamilyInet = NetSockFamilyKey.String("inet") - // IPv6 address - NetSockFamilyInet6 = NetSockFamilyKey.String("inet6") - // Unix domain socket path - NetSockFamilyUnix = NetSockFamilyKey.String("unix") -) - -var ( - // wifi - NetHostConnectionTypeWifi = NetHostConnectionTypeKey.String("wifi") - // wired - NetHostConnectionTypeWired = NetHostConnectionTypeKey.String("wired") - // cell - NetHostConnectionTypeCell = NetHostConnectionTypeKey.String("cell") - // unavailable - NetHostConnectionTypeUnavailable = NetHostConnectionTypeKey.String("unavailable") - // unknown - NetHostConnectionTypeUnknown = NetHostConnectionTypeKey.String("unknown") -) - -var ( - // GPRS - NetHostConnectionSubtypeGprs = NetHostConnectionSubtypeKey.String("gprs") - // EDGE - NetHostConnectionSubtypeEdge = NetHostConnectionSubtypeKey.String("edge") - // UMTS - NetHostConnectionSubtypeUmts = NetHostConnectionSubtypeKey.String("umts") - // CDMA - NetHostConnectionSubtypeCdma = NetHostConnectionSubtypeKey.String("cdma") - // EVDO Rel. 0 - NetHostConnectionSubtypeEvdo0 = NetHostConnectionSubtypeKey.String("evdo_0") - // EVDO Rev. A - NetHostConnectionSubtypeEvdoA = NetHostConnectionSubtypeKey.String("evdo_a") - // CDMA2000 1XRTT - NetHostConnectionSubtypeCdma20001xrtt = NetHostConnectionSubtypeKey.String("cdma2000_1xrtt") - // HSDPA - NetHostConnectionSubtypeHsdpa = NetHostConnectionSubtypeKey.String("hsdpa") - // HSUPA - NetHostConnectionSubtypeHsupa = NetHostConnectionSubtypeKey.String("hsupa") - // HSPA - NetHostConnectionSubtypeHspa = NetHostConnectionSubtypeKey.String("hspa") - // IDEN - NetHostConnectionSubtypeIden = NetHostConnectionSubtypeKey.String("iden") - // EVDO Rev. B - NetHostConnectionSubtypeEvdoB = NetHostConnectionSubtypeKey.String("evdo_b") - // LTE - NetHostConnectionSubtypeLte = NetHostConnectionSubtypeKey.String("lte") - // EHRPD - NetHostConnectionSubtypeEhrpd = NetHostConnectionSubtypeKey.String("ehrpd") - // HSPAP - NetHostConnectionSubtypeHspap = NetHostConnectionSubtypeKey.String("hspap") - // GSM - NetHostConnectionSubtypeGsm = NetHostConnectionSubtypeKey.String("gsm") - // TD-SCDMA - NetHostConnectionSubtypeTdScdma = NetHostConnectionSubtypeKey.String("td_scdma") - // IWLAN - NetHostConnectionSubtypeIwlan = NetHostConnectionSubtypeKey.String("iwlan") - // 5G NR (New Radio) - NetHostConnectionSubtypeNr = NetHostConnectionSubtypeKey.String("nr") - // 5G NRNSA (New Radio Non-Standalone) - NetHostConnectionSubtypeNrnsa = NetHostConnectionSubtypeKey.String("nrnsa") - // LTE CA - NetHostConnectionSubtypeLteCa = NetHostConnectionSubtypeKey.String("lte_ca") -) - -// NetAppProtocolName returns an attribute KeyValue conforming to the -// "net.app.protocol.name" semantic conventions. It represents the application -// layer protocol used. The value SHOULD be normalized to lowercase. -func NetAppProtocolName(val string) attribute.KeyValue { - return NetAppProtocolNameKey.String(val) -} - -// NetAppProtocolVersion returns an attribute KeyValue conforming to the -// "net.app.protocol.version" semantic conventions. It represents the version -// of the application layer protocol used. See note below. -func NetAppProtocolVersion(val string) attribute.KeyValue { - return NetAppProtocolVersionKey.String(val) -} - -// NetSockPeerName returns an attribute KeyValue conforming to the -// "net.sock.peer.name" semantic conventions. It represents the remote socket -// peer name. -func NetSockPeerName(val string) attribute.KeyValue { - return NetSockPeerNameKey.String(val) -} - -// NetSockPeerAddr returns an attribute KeyValue conforming to the -// "net.sock.peer.addr" semantic conventions. It represents the remote socket -// peer address: IPv4 or IPv6 for internet protocols, path for local -// communication, -// [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). -func NetSockPeerAddr(val string) attribute.KeyValue { - return NetSockPeerAddrKey.String(val) -} - -// NetSockPeerPort returns an attribute KeyValue conforming to the -// "net.sock.peer.port" semantic conventions. It represents the remote socket -// peer port. -func NetSockPeerPort(val int) attribute.KeyValue { - return NetSockPeerPortKey.Int(val) -} - -// NetPeerName returns an attribute KeyValue conforming to the -// "net.peer.name" semantic conventions. It represents the logical remote -// hostname, see note below. -func NetPeerName(val string) attribute.KeyValue { - return NetPeerNameKey.String(val) -} - -// NetPeerPort returns an attribute KeyValue conforming to the -// "net.peer.port" semantic conventions. It represents the logical remote port -// number -func NetPeerPort(val int) attribute.KeyValue { - return NetPeerPortKey.Int(val) -} - -// NetHostName returns an attribute KeyValue conforming to the -// "net.host.name" semantic conventions. It represents the logical local -// hostname or similar, see note below. -func NetHostName(val string) attribute.KeyValue { - return NetHostNameKey.String(val) -} - -// NetHostPort returns an attribute KeyValue conforming to the -// "net.host.port" semantic conventions. It represents the logical local port -// number, preferably the one that the peer used to connect -func NetHostPort(val int) attribute.KeyValue { - return NetHostPortKey.Int(val) -} - -// NetSockHostAddr returns an attribute KeyValue conforming to the -// "net.sock.host.addr" semantic conventions. It represents the local socket -// address. Useful in case of a multi-IP host. -func NetSockHostAddr(val string) attribute.KeyValue { - return NetSockHostAddrKey.String(val) -} - -// NetSockHostPort returns an attribute KeyValue conforming to the -// "net.sock.host.port" semantic conventions. It represents the local socket -// port number. -func NetSockHostPort(val int) attribute.KeyValue { - return NetSockHostPortKey.Int(val) -} - -// NetHostCarrierName returns an attribute KeyValue conforming to the -// "net.host.carrier.name" semantic conventions. It represents the name of the -// mobile carrier. -func NetHostCarrierName(val string) attribute.KeyValue { - return NetHostCarrierNameKey.String(val) -} - -// NetHostCarrierMcc returns an attribute KeyValue conforming to the -// "net.host.carrier.mcc" semantic conventions. It represents the mobile -// carrier country code. -func NetHostCarrierMcc(val string) attribute.KeyValue { - return NetHostCarrierMccKey.String(val) -} - -// NetHostCarrierMnc returns an attribute KeyValue conforming to the -// "net.host.carrier.mnc" semantic conventions. It represents the mobile -// carrier network code. -func NetHostCarrierMnc(val string) attribute.KeyValue { - return NetHostCarrierMncKey.String(val) -} - -// NetHostCarrierIcc returns an attribute KeyValue conforming to the -// "net.host.carrier.icc" semantic conventions. It represents the ISO 3166-1 -// alpha-2 2-character country code associated with the mobile carrier network. -func NetHostCarrierIcc(val string) attribute.KeyValue { - return NetHostCarrierIccKey.String(val) -} - -// Operations that access some remote service. -const ( - // PeerServiceKey is the attribute Key conforming to the "peer.service" - // semantic conventions. It represents the - // [`service.name`](../../resource/semantic_conventions/README.md#service) - // of the remote service. SHOULD be equal to the actual `service.name` - // resource attribute of the remote service if any. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'AuthTokenCache' - PeerServiceKey = attribute.Key("peer.service") -) - -// PeerService returns an attribute KeyValue conforming to the -// "peer.service" semantic conventions. It represents the -// [`service.name`](../../resource/semantic_conventions/README.md#service) of -// the remote service. SHOULD be equal to the actual `service.name` resource -// attribute of the remote service if any. -func PeerService(val string) attribute.KeyValue { - return PeerServiceKey.String(val) -} - -// These attributes may be used for any operation with an authenticated and/or -// authorized enduser. -const ( - // EnduserIDKey is the attribute Key conforming to the "enduser.id" - // semantic conventions. It represents the username or client_id extracted - // from the access token or - // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header - // in the inbound request from outside the system. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'username' - EnduserIDKey = attribute.Key("enduser.id") - - // EnduserRoleKey is the attribute Key conforming to the "enduser.role" - // semantic conventions. It represents the actual/assumed role the client - // is making the request under extracted from token or application security - // context. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'admin' - EnduserRoleKey = attribute.Key("enduser.role") - - // EnduserScopeKey is the attribute Key conforming to the "enduser.scope" - // semantic conventions. It represents the scopes or granted authorities - // the client currently possesses extracted from token or application - // security context. The value would come from the scope associated with an - // [OAuth 2.0 Access - // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute - // value in a [SAML 2.0 - // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'read:message, write:files' - EnduserScopeKey = attribute.Key("enduser.scope") -) - -// EnduserID returns an attribute KeyValue conforming to the "enduser.id" -// semantic conventions. It represents the username or client_id extracted from -// the access token or -// [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in -// the inbound request from outside the system. -func EnduserID(val string) attribute.KeyValue { - return EnduserIDKey.String(val) -} - -// EnduserRole returns an attribute KeyValue conforming to the -// "enduser.role" semantic conventions. It represents the actual/assumed role -// the client is making the request under extracted from token or application -// security context. -func EnduserRole(val string) attribute.KeyValue { - return EnduserRoleKey.String(val) -} - -// EnduserScope returns an attribute KeyValue conforming to the -// "enduser.scope" semantic conventions. It represents the scopes or granted -// authorities the client currently possesses extracted from token or -// application security context. The value would come from the scope associated -// with an [OAuth 2.0 Access -// Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute -// value in a [SAML 2.0 -// Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). -func EnduserScope(val string) attribute.KeyValue { - return EnduserScopeKey.String(val) -} - -// These attributes may be used for any operation to store information about a -// thread that started a span. -const ( - // ThreadIDKey is the attribute Key conforming to the "thread.id" semantic - // conventions. It represents the current "managed" thread ID (as opposed - // to OS thread ID). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - ThreadIDKey = attribute.Key("thread.id") - - // ThreadNameKey is the attribute Key conforming to the "thread.name" - // semantic conventions. It represents the current thread name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'main' - ThreadNameKey = attribute.Key("thread.name") -) - -// ThreadID returns an attribute KeyValue conforming to the "thread.id" -// semantic conventions. It represents the current "managed" thread ID (as -// opposed to OS thread ID). -func ThreadID(val int) attribute.KeyValue { - return ThreadIDKey.Int(val) -} - -// ThreadName returns an attribute KeyValue conforming to the "thread.name" -// semantic conventions. It represents the current thread name. -func ThreadName(val string) attribute.KeyValue { - return ThreadNameKey.String(val) -} - -// These attributes allow to report this unit of code and therefore to provide -// more context about the span. -const ( - // CodeFunctionKey is the attribute Key conforming to the "code.function" - // semantic conventions. It represents the method or function name, or - // equivalent (usually rightmost part of the code unit's name). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'serveRequest' - CodeFunctionKey = attribute.Key("code.function") - - // CodeNamespaceKey is the attribute Key conforming to the "code.namespace" - // semantic conventions. It represents the "namespace" within which - // `code.function` is defined. Usually the qualified class or module name, - // such that `code.namespace` + some separator + `code.function` form a - // unique identifier for the code unit. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'com.example.MyHTTPService' - CodeNamespaceKey = attribute.Key("code.namespace") - - // CodeFilepathKey is the attribute Key conforming to the "code.filepath" - // semantic conventions. It represents the source code file name that - // identifies the code unit as uniquely as possible (preferably an absolute - // file path). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/usr/local/MyApplication/content_root/app/index.php' - CodeFilepathKey = attribute.Key("code.filepath") - - // CodeLineNumberKey is the attribute Key conforming to the "code.lineno" - // semantic conventions. It represents the line number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - CodeLineNumberKey = attribute.Key("code.lineno") - - // CodeColumnKey is the attribute Key conforming to the "code.column" - // semantic conventions. It represents the column number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 16 - CodeColumnKey = attribute.Key("code.column") -) - -// CodeFunction returns an attribute KeyValue conforming to the -// "code.function" semantic conventions. It represents the method or function -// name, or equivalent (usually rightmost part of the code unit's name). -func CodeFunction(val string) attribute.KeyValue { - return CodeFunctionKey.String(val) -} - -// CodeNamespace returns an attribute KeyValue conforming to the -// "code.namespace" semantic conventions. It represents the "namespace" within -// which `code.function` is defined. Usually the qualified class or module -// name, such that `code.namespace` + some separator + `code.function` form a -// unique identifier for the code unit. -func CodeNamespace(val string) attribute.KeyValue { - return CodeNamespaceKey.String(val) -} - -// CodeFilepath returns an attribute KeyValue conforming to the -// "code.filepath" semantic conventions. It represents the source code file -// name that identifies the code unit as uniquely as possible (preferably an -// absolute file path). -func CodeFilepath(val string) attribute.KeyValue { - return CodeFilepathKey.String(val) -} - -// CodeLineNumber returns an attribute KeyValue conforming to the "code.lineno" -// semantic conventions. It represents the line number in `code.filepath` best -// representing the operation. It SHOULD point within the code unit named in -// `code.function`. -func CodeLineNumber(val int) attribute.KeyValue { - return CodeLineNumberKey.Int(val) -} - -// CodeColumn returns an attribute KeyValue conforming to the "code.column" -// semantic conventions. It represents the column number in `code.filepath` -// best representing the operation. It SHOULD point within the code unit named -// in `code.function`. -func CodeColumn(val int) attribute.KeyValue { - return CodeColumnKey.Int(val) -} - -// Semantic conventions for HTTP client and server Spans. -const ( - // HTTPMethodKey is the attribute Key conforming to the "http.method" - // semantic conventions. It represents the hTTP request method. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'GET', 'POST', 'HEAD' - HTTPMethodKey = attribute.Key("http.method") - - // HTTPStatusCodeKey is the attribute Key conforming to the - // "http.status_code" semantic conventions. It represents the [HTTP - // response status code](https://tools.ietf.org/html/rfc7231#section-6). - // - // Type: int - // RequirementLevel: ConditionallyRequired (If and only if one was - // received/sent.) - // Stability: stable - // Examples: 200 - HTTPStatusCodeKey = attribute.Key("http.status_code") - - // HTTPFlavorKey is the attribute Key conforming to the "http.flavor" - // semantic conventions. It represents the kind of HTTP protocol used. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Note: If `net.transport` is not specified, it can be assumed to be - // `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is - // assumed. - HTTPFlavorKey = attribute.Key("http.flavor") - - // HTTPUserAgentKey is the attribute Key conforming to the - // "http.user_agent" semantic conventions. It represents the value of the - // [HTTP - // User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) - // header sent by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'CERN-LineMode/2.15 libwww/2.17b3' - HTTPUserAgentKey = attribute.Key("http.user_agent") - - // HTTPRequestContentLengthKey is the attribute Key conforming to the - // "http.request_content_length" semantic conventions. It represents the - // size of the request payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3495 - HTTPRequestContentLengthKey = attribute.Key("http.request_content_length") - - // HTTPResponseContentLengthKey is the attribute Key conforming to the - // "http.response_content_length" semantic conventions. It represents the - // size of the response payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3495 - HTTPResponseContentLengthKey = attribute.Key("http.response_content_length") -) - -var ( - // HTTP/1.0 - HTTPFlavorHTTP10 = HTTPFlavorKey.String("1.0") - // HTTP/1.1 - HTTPFlavorHTTP11 = HTTPFlavorKey.String("1.1") - // HTTP/2 - HTTPFlavorHTTP20 = HTTPFlavorKey.String("2.0") - // HTTP/3 - HTTPFlavorHTTP30 = HTTPFlavorKey.String("3.0") - // SPDY protocol - HTTPFlavorSPDY = HTTPFlavorKey.String("SPDY") - // QUIC protocol - HTTPFlavorQUIC = HTTPFlavorKey.String("QUIC") -) - -// HTTPMethod returns an attribute KeyValue conforming to the "http.method" -// semantic conventions. It represents the hTTP request method. -func HTTPMethod(val string) attribute.KeyValue { - return HTTPMethodKey.String(val) -} - -// HTTPStatusCode returns an attribute KeyValue conforming to the -// "http.status_code" semantic conventions. It represents the [HTTP response -// status code](https://tools.ietf.org/html/rfc7231#section-6). -func HTTPStatusCode(val int) attribute.KeyValue { - return HTTPStatusCodeKey.Int(val) -} - -// HTTPUserAgent returns an attribute KeyValue conforming to the -// "http.user_agent" semantic conventions. It represents the value of the [HTTP -// User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) -// header sent by the client. -func HTTPUserAgent(val string) attribute.KeyValue { - return HTTPUserAgentKey.String(val) -} - -// HTTPRequestContentLength returns an attribute KeyValue conforming to the -// "http.request_content_length" semantic conventions. It represents the size -// of the request payload body in bytes. This is the number of bytes -// transferred excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPRequestContentLength(val int) attribute.KeyValue { - return HTTPRequestContentLengthKey.Int(val) -} - -// HTTPResponseContentLength returns an attribute KeyValue conforming to the -// "http.response_content_length" semantic conventions. It represents the size -// of the response payload body in bytes. This is the number of bytes -// transferred excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPResponseContentLength(val int) attribute.KeyValue { - return HTTPResponseContentLengthKey.Int(val) -} - -// Semantic Convention for HTTP Client -const ( - // HTTPURLKey is the attribute Key conforming to the "http.url" semantic - // conventions. It represents the full HTTP request URL in the form - // `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is - // not transmitted over HTTP, but if it is known, it should be included - // nevertheless. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv' - // Note: `http.url` MUST NOT contain credentials passed via URL in form of - // `https://username:password@www.example.com/`. In such case the - // attribute's value should be `https://www.example.com/`. - HTTPURLKey = attribute.Key("http.url") - - // HTTPResendCountKey is the attribute Key conforming to the - // "http.resend_count" semantic conventions. It represents the ordinal - // number of request resending attempt (for any reason, including - // redirects). - // - // Type: int - // RequirementLevel: Recommended (if and only if request was retried.) - // Stability: stable - // Examples: 3 - // Note: The resend count SHOULD be updated each time an HTTP request gets - // resent by the client, regardless of what was the cause of the resending - // (e.g. redirection, authorization failure, 503 Server Unavailable, - // network issues, or any other). - HTTPResendCountKey = attribute.Key("http.resend_count") -) - -// HTTPURL returns an attribute KeyValue conforming to the "http.url" -// semantic conventions. It represents the full HTTP request URL in the form -// `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not -// transmitted over HTTP, but if it is known, it should be included -// nevertheless. -func HTTPURL(val string) attribute.KeyValue { - return HTTPURLKey.String(val) -} - -// HTTPResendCount returns an attribute KeyValue conforming to the -// "http.resend_count" semantic conventions. It represents the ordinal number -// of request resending attempt (for any reason, including redirects). -func HTTPResendCount(val int) attribute.KeyValue { - return HTTPResendCountKey.Int(val) -} - -// Semantic Convention for HTTP Server -const ( - // HTTPSchemeKey is the attribute Key conforming to the "http.scheme" - // semantic conventions. It represents the URI scheme identifying the used - // protocol. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'http', 'https' - HTTPSchemeKey = attribute.Key("http.scheme") - - // HTTPTargetKey is the attribute Key conforming to the "http.target" - // semantic conventions. It represents the full request target as passed in - // a HTTP request line or equivalent. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: '/path/12314/?q=ddds' - HTTPTargetKey = attribute.Key("http.target") - - // HTTPRouteKey is the attribute Key conforming to the "http.route" - // semantic conventions. It represents the matched route (path template in - // the format used by the respective server framework). See note below - // - // Type: string - // RequirementLevel: ConditionallyRequired (If and only if it's available) - // Stability: stable - // Examples: '/users/:userID?', '{controller}/{action}/{id?}' - // Note: 'http.route' MUST NOT be populated when this is not supported by - // the HTTP server framework as the route attribute should have - // low-cardinality and the URI path can NOT substitute it. - HTTPRouteKey = attribute.Key("http.route") - - // HTTPClientIPKey is the attribute Key conforming to the "http.client_ip" - // semantic conventions. It represents the IP address of the original - // client behind all proxies, if known (e.g. from - // [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '83.164.160.102' - // Note: This is not necessarily the same as `net.sock.peer.addr`, which - // would - // identify the network-level peer, which may be a proxy. - // - // This attribute should be set when a source of information different - // from the one used for `net.sock.peer.addr`, is available even if that - // other - // source just confirms the same value as `net.sock.peer.addr`. - // Rationale: For `net.sock.peer.addr`, one typically does not know if it - // comes from a proxy, reverse proxy, or the actual client. Setting - // `http.client_ip` when it's the same as `net.sock.peer.addr` means that - // one is at least somewhat confident that the address is not that of - // the closest proxy. - HTTPClientIPKey = attribute.Key("http.client_ip") -) - -// HTTPScheme returns an attribute KeyValue conforming to the "http.scheme" -// semantic conventions. It represents the URI scheme identifying the used -// protocol. -func HTTPScheme(val string) attribute.KeyValue { - return HTTPSchemeKey.String(val) -} - -// HTTPTarget returns an attribute KeyValue conforming to the "http.target" -// semantic conventions. It represents the full request target as passed in a -// HTTP request line or equivalent. -func HTTPTarget(val string) attribute.KeyValue { - return HTTPTargetKey.String(val) -} - -// HTTPRoute returns an attribute KeyValue conforming to the "http.route" -// semantic conventions. It represents the matched route (path template in the -// format used by the respective server framework). See note below -func HTTPRoute(val string) attribute.KeyValue { - return HTTPRouteKey.String(val) -} - -// HTTPClientIP returns an attribute KeyValue conforming to the -// "http.client_ip" semantic conventions. It represents the IP address of the -// original client behind all proxies, if known (e.g. from -// [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). -func HTTPClientIP(val string) attribute.KeyValue { - return HTTPClientIPKey.String(val) -} - -// Attributes that exist for multiple DynamoDB request types. -const ( - // AWSDynamoDBTableNamesKey is the attribute Key conforming to the - // "aws.dynamodb.table_names" semantic conventions. It represents the keys - // in the `RequestItems` object field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Users', 'Cats' - AWSDynamoDBTableNamesKey = attribute.Key("aws.dynamodb.table_names") - - // AWSDynamoDBConsumedCapacityKey is the attribute Key conforming to the - // "aws.dynamodb.consumed_capacity" semantic conventions. It represents the - // JSON-serialized value of each item in the `ConsumedCapacity` response - // field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "CapacityUnits": number, "GlobalSecondaryIndexes": { - // "string" : { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "LocalSecondaryIndexes": { "string" : - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "ReadCapacityUnits": number, "Table": - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number }, "TableName": "string", - // "WriteCapacityUnits": number }' - AWSDynamoDBConsumedCapacityKey = attribute.Key("aws.dynamodb.consumed_capacity") - - // AWSDynamoDBItemCollectionMetricsKey is the attribute Key conforming to - // the "aws.dynamodb.item_collection_metrics" semantic conventions. It - // represents the JSON-serialized value of the `ItemCollectionMetrics` - // response field. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "string" : [ { "ItemCollectionKey": { "string" : { "B": - // blob, "BOOL": boolean, "BS": [ blob ], "L": [ "AttributeValue" ], "M": { - // "string" : "AttributeValue" }, "N": "string", "NS": [ "string" ], - // "NULL": boolean, "S": "string", "SS": [ "string" ] } }, - // "SizeEstimateRangeGB": [ number ] } ] }' - AWSDynamoDBItemCollectionMetricsKey = attribute.Key("aws.dynamodb.item_collection_metrics") - - // AWSDynamoDBProvisionedReadCapacityKey is the attribute Key conforming to - // the "aws.dynamodb.provisioned_read_capacity" semantic conventions. It - // represents the value of the `ProvisionedThroughput.ReadCapacityUnits` - // request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: stable - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedReadCapacityKey = attribute.Key("aws.dynamodb.provisioned_read_capacity") - - // AWSDynamoDBProvisionedWriteCapacityKey is the attribute Key conforming - // to the "aws.dynamodb.provisioned_write_capacity" semantic conventions. - // It represents the value of the - // `ProvisionedThroughput.WriteCapacityUnits` request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: stable - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedWriteCapacityKey = attribute.Key("aws.dynamodb.provisioned_write_capacity") - - // AWSDynamoDBConsistentReadKey is the attribute Key conforming to the - // "aws.dynamodb.consistent_read" semantic conventions. It represents the - // value of the `ConsistentRead` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - AWSDynamoDBConsistentReadKey = attribute.Key("aws.dynamodb.consistent_read") - - // AWSDynamoDBProjectionKey is the attribute Key conforming to the - // "aws.dynamodb.projection" semantic conventions. It represents the value - // of the `ProjectionExpression` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Title', 'Title, Price, Color', 'Title, Description, - // RelatedItems, ProductReviews' - AWSDynamoDBProjectionKey = attribute.Key("aws.dynamodb.projection") - - // AWSDynamoDBLimitKey is the attribute Key conforming to the - // "aws.dynamodb.limit" semantic conventions. It represents the value of - // the `Limit` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBLimitKey = attribute.Key("aws.dynamodb.limit") - - // AWSDynamoDBAttributesToGetKey is the attribute Key conforming to the - // "aws.dynamodb.attributes_to_get" semantic conventions. It represents the - // value of the `AttributesToGet` request parameter. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'lives', 'id' - AWSDynamoDBAttributesToGetKey = attribute.Key("aws.dynamodb.attributes_to_get") - - // AWSDynamoDBIndexNameKey is the attribute Key conforming to the - // "aws.dynamodb.index_name" semantic conventions. It represents the value - // of the `IndexName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'name_to_group' - AWSDynamoDBIndexNameKey = attribute.Key("aws.dynamodb.index_name") - - // AWSDynamoDBSelectKey is the attribute Key conforming to the - // "aws.dynamodb.select" semantic conventions. It represents the value of - // the `Select` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ALL_ATTRIBUTES', 'COUNT' - AWSDynamoDBSelectKey = attribute.Key("aws.dynamodb.select") -) - -// AWSDynamoDBTableNames returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_names" semantic conventions. It represents the keys in -// the `RequestItems` object field. -func AWSDynamoDBTableNames(val ...string) attribute.KeyValue { - return AWSDynamoDBTableNamesKey.StringSlice(val) -} - -// AWSDynamoDBConsumedCapacity returns an attribute KeyValue conforming to -// the "aws.dynamodb.consumed_capacity" semantic conventions. It represents the -// JSON-serialized value of each item in the `ConsumedCapacity` response field. -func AWSDynamoDBConsumedCapacity(val ...string) attribute.KeyValue { - return AWSDynamoDBConsumedCapacityKey.StringSlice(val) -} - -// AWSDynamoDBItemCollectionMetrics returns an attribute KeyValue conforming -// to the "aws.dynamodb.item_collection_metrics" semantic conventions. It -// represents the JSON-serialized value of the `ItemCollectionMetrics` response -// field. -func AWSDynamoDBItemCollectionMetrics(val string) attribute.KeyValue { - return AWSDynamoDBItemCollectionMetricsKey.String(val) -} - -// AWSDynamoDBProvisionedReadCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_read_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.ReadCapacityUnits` request parameter. -func AWSDynamoDBProvisionedReadCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedReadCapacityKey.Float64(val) -} - -// AWSDynamoDBProvisionedWriteCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_write_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.WriteCapacityUnits` request parameter. -func AWSDynamoDBProvisionedWriteCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedWriteCapacityKey.Float64(val) -} - -// AWSDynamoDBConsistentRead returns an attribute KeyValue conforming to the -// "aws.dynamodb.consistent_read" semantic conventions. It represents the value -// of the `ConsistentRead` request parameter. -func AWSDynamoDBConsistentRead(val bool) attribute.KeyValue { - return AWSDynamoDBConsistentReadKey.Bool(val) -} - -// AWSDynamoDBProjection returns an attribute KeyValue conforming to the -// "aws.dynamodb.projection" semantic conventions. It represents the value of -// the `ProjectionExpression` request parameter. -func AWSDynamoDBProjection(val string) attribute.KeyValue { - return AWSDynamoDBProjectionKey.String(val) -} - -// AWSDynamoDBLimit returns an attribute KeyValue conforming to the -// "aws.dynamodb.limit" semantic conventions. It represents the value of the -// `Limit` request parameter. -func AWSDynamoDBLimit(val int) attribute.KeyValue { - return AWSDynamoDBLimitKey.Int(val) -} - -// AWSDynamoDBAttributesToGet returns an attribute KeyValue conforming to -// the "aws.dynamodb.attributes_to_get" semantic conventions. It represents the -// value of the `AttributesToGet` request parameter. -func AWSDynamoDBAttributesToGet(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributesToGetKey.StringSlice(val) -} - -// AWSDynamoDBIndexName returns an attribute KeyValue conforming to the -// "aws.dynamodb.index_name" semantic conventions. It represents the value of -// the `IndexName` request parameter. -func AWSDynamoDBIndexName(val string) attribute.KeyValue { - return AWSDynamoDBIndexNameKey.String(val) -} - -// AWSDynamoDBSelect returns an attribute KeyValue conforming to the -// "aws.dynamodb.select" semantic conventions. It represents the value of the -// `Select` request parameter. -func AWSDynamoDBSelect(val string) attribute.KeyValue { - return AWSDynamoDBSelectKey.String(val) -} - -// DynamoDB.CreateTable -const ( - // AWSDynamoDBGlobalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.global_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `GlobalSecondaryIndexes` request field - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "IndexName": "string", "KeySchema": [ { "AttributeName": - // "string", "KeyType": "string" } ], "Projection": { "NonKeyAttributes": [ - // "string" ], "ProjectionType": "string" }, "ProvisionedThroughput": { - // "ReadCapacityUnits": number, "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexesKey = attribute.Key("aws.dynamodb.global_secondary_indexes") - - // AWSDynamoDBLocalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.local_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `LocalSecondaryIndexes` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "IndexARN": "string", "IndexName": "string", - // "IndexSizeBytes": number, "ItemCount": number, "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" } }' - AWSDynamoDBLocalSecondaryIndexesKey = attribute.Key("aws.dynamodb.local_secondary_indexes") -) - -// AWSDynamoDBGlobalSecondaryIndexes returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_indexes" semantic -// conventions. It represents the JSON-serialized value of each item of the -// `GlobalSecondaryIndexes` request field -func AWSDynamoDBGlobalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexesKey.StringSlice(val) -} - -// AWSDynamoDBLocalSecondaryIndexes returns an attribute KeyValue conforming -// to the "aws.dynamodb.local_secondary_indexes" semantic conventions. It -// represents the JSON-serialized value of each item of the -// `LocalSecondaryIndexes` request field. -func AWSDynamoDBLocalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBLocalSecondaryIndexesKey.StringSlice(val) -} - -// DynamoDB.ListTables -const ( - // AWSDynamoDBExclusiveStartTableKey is the attribute Key conforming to the - // "aws.dynamodb.exclusive_start_table" semantic conventions. It represents - // the value of the `ExclusiveStartTableName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Users', 'CatsTable' - AWSDynamoDBExclusiveStartTableKey = attribute.Key("aws.dynamodb.exclusive_start_table") - - // AWSDynamoDBTableCountKey is the attribute Key conforming to the - // "aws.dynamodb.table_count" semantic conventions. It represents the the - // number of items in the `TableNames` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 20 - AWSDynamoDBTableCountKey = attribute.Key("aws.dynamodb.table_count") -) - -// AWSDynamoDBExclusiveStartTable returns an attribute KeyValue conforming -// to the "aws.dynamodb.exclusive_start_table" semantic conventions. It -// represents the value of the `ExclusiveStartTableName` request parameter. -func AWSDynamoDBExclusiveStartTable(val string) attribute.KeyValue { - return AWSDynamoDBExclusiveStartTableKey.String(val) -} - -// AWSDynamoDBTableCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_count" semantic conventions. It represents the the -// number of items in the `TableNames` response parameter. -func AWSDynamoDBTableCount(val int) attribute.KeyValue { - return AWSDynamoDBTableCountKey.Int(val) -} - -// DynamoDB.Query -const ( - // AWSDynamoDBScanForwardKey is the attribute Key conforming to the - // "aws.dynamodb.scan_forward" semantic conventions. It represents the - // value of the `ScanIndexForward` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - AWSDynamoDBScanForwardKey = attribute.Key("aws.dynamodb.scan_forward") -) - -// AWSDynamoDBScanForward returns an attribute KeyValue conforming to the -// "aws.dynamodb.scan_forward" semantic conventions. It represents the value of -// the `ScanIndexForward` request parameter. -func AWSDynamoDBScanForward(val bool) attribute.KeyValue { - return AWSDynamoDBScanForwardKey.Bool(val) -} - -// DynamoDB.Scan -const ( - // AWSDynamoDBSegmentKey is the attribute Key conforming to the - // "aws.dynamodb.segment" semantic conventions. It represents the value of - // the `Segment` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBSegmentKey = attribute.Key("aws.dynamodb.segment") - - // AWSDynamoDBTotalSegmentsKey is the attribute Key conforming to the - // "aws.dynamodb.total_segments" semantic conventions. It represents the - // value of the `TotalSegments` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 100 - AWSDynamoDBTotalSegmentsKey = attribute.Key("aws.dynamodb.total_segments") - - // AWSDynamoDBCountKey is the attribute Key conforming to the - // "aws.dynamodb.count" semantic conventions. It represents the value of - // the `Count` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 10 - AWSDynamoDBCountKey = attribute.Key("aws.dynamodb.count") - - // AWSDynamoDBScannedCountKey is the attribute Key conforming to the - // "aws.dynamodb.scanned_count" semantic conventions. It represents the - // value of the `ScannedCount` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 50 - AWSDynamoDBScannedCountKey = attribute.Key("aws.dynamodb.scanned_count") -) - -// AWSDynamoDBSegment returns an attribute KeyValue conforming to the -// "aws.dynamodb.segment" semantic conventions. It represents the value of the -// `Segment` request parameter. -func AWSDynamoDBSegment(val int) attribute.KeyValue { - return AWSDynamoDBSegmentKey.Int(val) -} - -// AWSDynamoDBTotalSegments returns an attribute KeyValue conforming to the -// "aws.dynamodb.total_segments" semantic conventions. It represents the value -// of the `TotalSegments` request parameter. -func AWSDynamoDBTotalSegments(val int) attribute.KeyValue { - return AWSDynamoDBTotalSegmentsKey.Int(val) -} - -// AWSDynamoDBCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.count" semantic conventions. It represents the value of the -// `Count` response parameter. -func AWSDynamoDBCount(val int) attribute.KeyValue { - return AWSDynamoDBCountKey.Int(val) -} - -// AWSDynamoDBScannedCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.scanned_count" semantic conventions. It represents the value -// of the `ScannedCount` response parameter. -func AWSDynamoDBScannedCount(val int) attribute.KeyValue { - return AWSDynamoDBScannedCountKey.Int(val) -} - -// DynamoDB.UpdateTable -const ( - // AWSDynamoDBAttributeDefinitionsKey is the attribute Key conforming to - // the "aws.dynamodb.attribute_definitions" semantic conventions. It - // represents the JSON-serialized value of each item in the - // `AttributeDefinitions` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "AttributeName": "string", "AttributeType": "string" }' - AWSDynamoDBAttributeDefinitionsKey = attribute.Key("aws.dynamodb.attribute_definitions") - - // AWSDynamoDBGlobalSecondaryIndexUpdatesKey is the attribute Key - // conforming to the "aws.dynamodb.global_secondary_index_updates" semantic - // conventions. It represents the JSON-serialized value of each item in the - // the `GlobalSecondaryIndexUpdates` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: '{ "Create": { "IndexName": "string", "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" }, - // "ProvisionedThroughput": { "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexUpdatesKey = attribute.Key("aws.dynamodb.global_secondary_index_updates") -) - -// AWSDynamoDBAttributeDefinitions returns an attribute KeyValue conforming -// to the "aws.dynamodb.attribute_definitions" semantic conventions. It -// represents the JSON-serialized value of each item in the -// `AttributeDefinitions` request field. -func AWSDynamoDBAttributeDefinitions(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributeDefinitionsKey.StringSlice(val) -} - -// AWSDynamoDBGlobalSecondaryIndexUpdates returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_index_updates" semantic -// conventions. It represents the JSON-serialized value of each item in the the -// `GlobalSecondaryIndexUpdates` request field. -func AWSDynamoDBGlobalSecondaryIndexUpdates(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexUpdatesKey.StringSlice(val) -} - -// Semantic conventions to apply when instrumenting the GraphQL implementation. -// They map GraphQL operations to attributes on a Span. -const ( - // GraphqlOperationNameKey is the attribute Key conforming to the - // "graphql.operation.name" semantic conventions. It represents the name of - // the operation being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'findBookByID' - GraphqlOperationNameKey = attribute.Key("graphql.operation.name") - - // GraphqlOperationTypeKey is the attribute Key conforming to the - // "graphql.operation.type" semantic conventions. It represents the type of - // the operation being executed. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'query', 'mutation', 'subscription' - GraphqlOperationTypeKey = attribute.Key("graphql.operation.type") - - // GraphqlDocumentKey is the attribute Key conforming to the - // "graphql.document" semantic conventions. It represents the GraphQL - // document being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'query findBookByID { bookByID(id: ?) { name } }' - // Note: The value may be sanitized to exclude sensitive information. - GraphqlDocumentKey = attribute.Key("graphql.document") -) - -var ( - // GraphQL query - GraphqlOperationTypeQuery = GraphqlOperationTypeKey.String("query") - // GraphQL mutation - GraphqlOperationTypeMutation = GraphqlOperationTypeKey.String("mutation") - // GraphQL subscription - GraphqlOperationTypeSubscription = GraphqlOperationTypeKey.String("subscription") -) - -// GraphqlOperationName returns an attribute KeyValue conforming to the -// "graphql.operation.name" semantic conventions. It represents the name of the -// operation being executed. -func GraphqlOperationName(val string) attribute.KeyValue { - return GraphqlOperationNameKey.String(val) -} - -// GraphqlDocument returns an attribute KeyValue conforming to the -// "graphql.document" semantic conventions. It represents the GraphQL document -// being executed. -func GraphqlDocument(val string) attribute.KeyValue { - return GraphqlDocumentKey.String(val) -} - -// Semantic convention describing per-message attributes populated on messaging -// spans or links. -const ( - // MessagingMessageIDKey is the attribute Key conforming to the - // "messaging.message.id" semantic conventions. It represents a value used - // by the messaging system as an identifier for the message, represented as - // a string. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '452a7c7c7c7048c2f887f61572b18fc2' - MessagingMessageIDKey = attribute.Key("messaging.message.id") - - // MessagingMessageConversationIDKey is the attribute Key conforming to the - // "messaging.message.conversation_id" semantic conventions. It represents - // the [conversation ID](#conversations) identifying the conversation to - // which the message belongs, represented as a string. Sometimes called - // "Correlation ID". - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyConversationID' - MessagingMessageConversationIDKey = attribute.Key("messaging.message.conversation_id") - - // MessagingMessagePayloadSizeBytesKey is the attribute Key conforming to - // the "messaging.message.payload_size_bytes" semantic conventions. It - // represents the (uncompressed) size of the message payload in bytes. Also - // use this attribute if it is unknown whether the compressed or - // uncompressed payload size is reported. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2738 - MessagingMessagePayloadSizeBytesKey = attribute.Key("messaging.message.payload_size_bytes") - - // MessagingMessagePayloadCompressedSizeBytesKey is the attribute Key - // conforming to the "messaging.message.payload_compressed_size_bytes" - // semantic conventions. It represents the compressed size of the message - // payload in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2048 - MessagingMessagePayloadCompressedSizeBytesKey = attribute.Key("messaging.message.payload_compressed_size_bytes") -) - -// MessagingMessageID returns an attribute KeyValue conforming to the -// "messaging.message.id" semantic conventions. It represents a value used by -// the messaging system as an identifier for the message, represented as a -// string. -func MessagingMessageID(val string) attribute.KeyValue { - return MessagingMessageIDKey.String(val) -} - -// MessagingMessageConversationID returns an attribute KeyValue conforming -// to the "messaging.message.conversation_id" semantic conventions. It -// represents the [conversation ID](#conversations) identifying the -// conversation to which the message belongs, represented as a string. -// Sometimes called "Correlation ID". -func MessagingMessageConversationID(val string) attribute.KeyValue { - return MessagingMessageConversationIDKey.String(val) -} - -// MessagingMessagePayloadSizeBytes returns an attribute KeyValue conforming -// to the "messaging.message.payload_size_bytes" semantic conventions. It -// represents the (uncompressed) size of the message payload in bytes. Also use -// this attribute if it is unknown whether the compressed or uncompressed -// payload size is reported. -func MessagingMessagePayloadSizeBytes(val int) attribute.KeyValue { - return MessagingMessagePayloadSizeBytesKey.Int(val) -} - -// MessagingMessagePayloadCompressedSizeBytes returns an attribute KeyValue -// conforming to the "messaging.message.payload_compressed_size_bytes" semantic -// conventions. It represents the compressed size of the message payload in -// bytes. -func MessagingMessagePayloadCompressedSizeBytes(val int) attribute.KeyValue { - return MessagingMessagePayloadCompressedSizeBytesKey.Int(val) -} - -// Semantic convention for attributes that describe messaging destination on -// broker -const ( - // MessagingDestinationNameKey is the attribute Key conforming to the - // "messaging.destination.name" semantic conventions. It represents the - // message destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyQueue', 'MyTopic' - // Note: Destination name SHOULD uniquely identify a specific queue, topic - // or other entity within the broker. If - // the broker does not have such notion, the destination name SHOULD - // uniquely identify the broker. - MessagingDestinationNameKey = attribute.Key("messaging.destination.name") - - // MessagingDestinationKindKey is the attribute Key conforming to the - // "messaging.destination.kind" semantic conventions. It represents the - // kind of message destination - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingDestinationKindKey = attribute.Key("messaging.destination.kind") - - // MessagingDestinationTemplateKey is the attribute Key conforming to the - // "messaging.destination.template" semantic conventions. It represents the - // low cardinality representation of the messaging destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/customers/{customerID}' - // Note: Destination names could be constructed from templates. An example - // would be a destination name involving a user name or product id. - // Although the destination name in this case is of high cardinality, the - // underlying template is of low cardinality and can be effectively used - // for grouping and aggregation. - MessagingDestinationTemplateKey = attribute.Key("messaging.destination.template") - - // MessagingDestinationTemporaryKey is the attribute Key conforming to the - // "messaging.destination.temporary" semantic conventions. It represents a - // boolean that is true if the message destination is temporary and might - // not exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingDestinationTemporaryKey = attribute.Key("messaging.destination.temporary") - - // MessagingDestinationAnonymousKey is the attribute Key conforming to the - // "messaging.destination.anonymous" semantic conventions. It represents a - // boolean that is true if the message destination is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingDestinationAnonymousKey = attribute.Key("messaging.destination.anonymous") -) - -var ( - // A message sent to a queue - MessagingDestinationKindQueue = MessagingDestinationKindKey.String("queue") - // A message sent to a topic - MessagingDestinationKindTopic = MessagingDestinationKindKey.String("topic") -) - -// MessagingDestinationName returns an attribute KeyValue conforming to the -// "messaging.destination.name" semantic conventions. It represents the message -// destination name -func MessagingDestinationName(val string) attribute.KeyValue { - return MessagingDestinationNameKey.String(val) -} - -// MessagingDestinationTemplate returns an attribute KeyValue conforming to -// the "messaging.destination.template" semantic conventions. It represents the -// low cardinality representation of the messaging destination name -func MessagingDestinationTemplate(val string) attribute.KeyValue { - return MessagingDestinationTemplateKey.String(val) -} - -// MessagingDestinationTemporary returns an attribute KeyValue conforming to -// the "messaging.destination.temporary" semantic conventions. It represents a -// boolean that is true if the message destination is temporary and might not -// exist anymore after messages are processed. -func MessagingDestinationTemporary(val bool) attribute.KeyValue { - return MessagingDestinationTemporaryKey.Bool(val) -} - -// MessagingDestinationAnonymous returns an attribute KeyValue conforming to -// the "messaging.destination.anonymous" semantic conventions. It represents a -// boolean that is true if the message destination is anonymous (could be -// unnamed or have auto-generated name). -func MessagingDestinationAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationAnonymousKey.Bool(val) -} - -// Semantic convention for attributes that describe messaging source on broker -const ( - // MessagingSourceNameKey is the attribute Key conforming to the - // "messaging.source.name" semantic conventions. It represents the message - // source name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'MyQueue', 'MyTopic' - // Note: Source name SHOULD uniquely identify a specific queue, topic, or - // other entity within the broker. If - // the broker does not have such notion, the source name SHOULD uniquely - // identify the broker. - MessagingSourceNameKey = attribute.Key("messaging.source.name") - - // MessagingSourceKindKey is the attribute Key conforming to the - // "messaging.source.kind" semantic conventions. It represents the kind of - // message source - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingSourceKindKey = attribute.Key("messaging.source.kind") - - // MessagingSourceTemplateKey is the attribute Key conforming to the - // "messaging.source.template" semantic conventions. It represents the low - // cardinality representation of the messaging source name - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/customers/{customerID}' - // Note: Source names could be constructed from templates. An example would - // be a source name involving a user name or product id. Although the - // source name in this case is of high cardinality, the underlying template - // is of low cardinality and can be effectively used for grouping and - // aggregation. - MessagingSourceTemplateKey = attribute.Key("messaging.source.template") - - // MessagingSourceTemporaryKey is the attribute Key conforming to the - // "messaging.source.temporary" semantic conventions. It represents a - // boolean that is true if the message source is temporary and might not - // exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingSourceTemporaryKey = attribute.Key("messaging.source.temporary") - - // MessagingSourceAnonymousKey is the attribute Key conforming to the - // "messaging.source.anonymous" semantic conventions. It represents a - // boolean that is true if the message source is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: stable - MessagingSourceAnonymousKey = attribute.Key("messaging.source.anonymous") -) - -var ( - // A message received from a queue - MessagingSourceKindQueue = MessagingSourceKindKey.String("queue") - // A message received from a topic - MessagingSourceKindTopic = MessagingSourceKindKey.String("topic") -) - -// MessagingSourceName returns an attribute KeyValue conforming to the -// "messaging.source.name" semantic conventions. It represents the message -// source name -func MessagingSourceName(val string) attribute.KeyValue { - return MessagingSourceNameKey.String(val) -} - -// MessagingSourceTemplate returns an attribute KeyValue conforming to the -// "messaging.source.template" semantic conventions. It represents the low -// cardinality representation of the messaging source name -func MessagingSourceTemplate(val string) attribute.KeyValue { - return MessagingSourceTemplateKey.String(val) -} - -// MessagingSourceTemporary returns an attribute KeyValue conforming to the -// "messaging.source.temporary" semantic conventions. It represents a boolean -// that is true if the message source is temporary and might not exist anymore -// after messages are processed. -func MessagingSourceTemporary(val bool) attribute.KeyValue { - return MessagingSourceTemporaryKey.Bool(val) -} - -// MessagingSourceAnonymous returns an attribute KeyValue conforming to the -// "messaging.source.anonymous" semantic conventions. It represents a boolean -// that is true if the message source is anonymous (could be unnamed or have -// auto-generated name). -func MessagingSourceAnonymous(val bool) attribute.KeyValue { - return MessagingSourceAnonymousKey.Bool(val) -} - -// General attributes used in messaging systems. -const ( - // MessagingSystemKey is the attribute Key conforming to the - // "messaging.system" semantic conventions. It represents a string - // identifying the messaging system. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'kafka', 'rabbitmq', 'rocketmq', 'activemq', 'AmazonSQS' - MessagingSystemKey = attribute.Key("messaging.system") - - // MessagingOperationKey is the attribute Key conforming to the - // "messaging.operation" semantic conventions. It represents a string - // identifying the kind of messaging operation as defined in the [Operation - // names](#operation-names) section above. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - // Note: If a custom value is used, it MUST be of low cardinality. - MessagingOperationKey = attribute.Key("messaging.operation") - - // MessagingBatchMessageCountKey is the attribute Key conforming to the - // "messaging.batch.message_count" semantic conventions. It represents the - // number of messages sent, received, or processed in the scope of the - // batching operation. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the span describes an - // operation on a batch of messages.) - // Stability: stable - // Examples: 0, 1, 2 - // Note: Instrumentations SHOULD NOT set `messaging.batch.message_count` on - // spans that operate with a single message. When a messaging client - // library supports both batch and single-message API for the same - // operation, instrumentations SHOULD use `messaging.batch.message_count` - // for batching APIs and SHOULD NOT use it for single-message APIs. - MessagingBatchMessageCountKey = attribute.Key("messaging.batch.message_count") -) - -var ( - // publish - MessagingOperationPublish = MessagingOperationKey.String("publish") - // receive - MessagingOperationReceive = MessagingOperationKey.String("receive") - // process - MessagingOperationProcess = MessagingOperationKey.String("process") -) - -// MessagingSystem returns an attribute KeyValue conforming to the -// "messaging.system" semantic conventions. It represents a string identifying -// the messaging system. -func MessagingSystem(val string) attribute.KeyValue { - return MessagingSystemKey.String(val) -} - -// MessagingBatchMessageCount returns an attribute KeyValue conforming to -// the "messaging.batch.message_count" semantic conventions. It represents the -// number of messages sent, received, or processed in the scope of the batching -// operation. -func MessagingBatchMessageCount(val int) attribute.KeyValue { - return MessagingBatchMessageCountKey.Int(val) -} - -// Semantic convention for a consumer of messages received from a messaging -// system -const ( - // MessagingConsumerIDKey is the attribute Key conforming to the - // "messaging.consumer.id" semantic conventions. It represents the - // identifier for the consumer receiving a message. For Kafka, set it to - // `{messaging.kafka.consumer.group} - {messaging.kafka.client_id}`, if - // both are present, or only `messaging.kafka.consumer.group`. For brokers, - // such as RabbitMQ and Artemis, set it to the `client_id` of the client - // consuming the message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'mygroup - client-6' - MessagingConsumerIDKey = attribute.Key("messaging.consumer.id") -) - -// MessagingConsumerID returns an attribute KeyValue conforming to the -// "messaging.consumer.id" semantic conventions. It represents the identifier -// for the consumer receiving a message. For Kafka, set it to -// `{messaging.kafka.consumer.group} - {messaging.kafka.client_id}`, if both -// are present, or only `messaging.kafka.consumer.group`. For brokers, such as -// RabbitMQ and Artemis, set it to the `client_id` of the client consuming the -// message. -func MessagingConsumerID(val string) attribute.KeyValue { - return MessagingConsumerIDKey.String(val) -} - -// Attributes for RabbitMQ -const ( - // MessagingRabbitmqDestinationRoutingKeyKey is the attribute Key - // conforming to the "messaging.rabbitmq.destination.routing_key" semantic - // conventions. It represents the rabbitMQ message routing key. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If not empty.) - // Stability: stable - // Examples: 'myKey' - MessagingRabbitmqDestinationRoutingKeyKey = attribute.Key("messaging.rabbitmq.destination.routing_key") -) - -// MessagingRabbitmqDestinationRoutingKey returns an attribute KeyValue -// conforming to the "messaging.rabbitmq.destination.routing_key" semantic -// conventions. It represents the rabbitMQ message routing key. -func MessagingRabbitmqDestinationRoutingKey(val string) attribute.KeyValue { - return MessagingRabbitmqDestinationRoutingKeyKey.String(val) -} - -// Attributes for Apache Kafka -const ( - // MessagingKafkaMessageKeyKey is the attribute Key conforming to the - // "messaging.kafka.message.key" semantic conventions. It represents the - // message keys in Kafka are used for grouping alike messages to ensure - // they're processed on the same partition. They differ from - // `messaging.message.id` in that they're not unique. If the key is `null`, - // the attribute MUST NOT be set. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'myKey' - // Note: If the key type is not string, it's string representation has to - // be supplied for the attribute. If the key has no unambiguous, canonical - // string form, don't include its value. - MessagingKafkaMessageKeyKey = attribute.Key("messaging.kafka.message.key") - - // MessagingKafkaConsumerGroupKey is the attribute Key conforming to the - // "messaging.kafka.consumer.group" semantic conventions. It represents the - // name of the Kafka Consumer Group that is handling the message. Only - // applies to consumers, not producers. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'my-group' - MessagingKafkaConsumerGroupKey = attribute.Key("messaging.kafka.consumer.group") - - // MessagingKafkaClientIDKey is the attribute Key conforming to the - // "messaging.kafka.client_id" semantic conventions. It represents the - // client ID for the Consumer or Producer that is handling the message. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'client-5' - MessagingKafkaClientIDKey = attribute.Key("messaging.kafka.client_id") - - // MessagingKafkaDestinationPartitionKey is the attribute Key conforming to - // the "messaging.kafka.destination.partition" semantic conventions. It - // represents the partition the message is sent to. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2 - MessagingKafkaDestinationPartitionKey = attribute.Key("messaging.kafka.destination.partition") - - // MessagingKafkaSourcePartitionKey is the attribute Key conforming to the - // "messaging.kafka.source.partition" semantic conventions. It represents - // the partition the message is received from. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 2 - MessagingKafkaSourcePartitionKey = attribute.Key("messaging.kafka.source.partition") - - // MessagingKafkaMessageOffsetKey is the attribute Key conforming to the - // "messaging.kafka.message.offset" semantic conventions. It represents the - // offset of a record in the corresponding Kafka partition. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 42 - MessagingKafkaMessageOffsetKey = attribute.Key("messaging.kafka.message.offset") - - // MessagingKafkaMessageTombstoneKey is the attribute Key conforming to the - // "messaging.kafka.message.tombstone" semantic conventions. It represents - // a boolean that is true if the message is a tombstone. - // - // Type: boolean - // RequirementLevel: ConditionallyRequired (If value is `true`. When - // missing, the value is assumed to be `false`.) - // Stability: stable - MessagingKafkaMessageTombstoneKey = attribute.Key("messaging.kafka.message.tombstone") -) - -// MessagingKafkaMessageKey returns an attribute KeyValue conforming to the -// "messaging.kafka.message.key" semantic conventions. It represents the -// message keys in Kafka are used for grouping alike messages to ensure they're -// processed on the same partition. They differ from `messaging.message.id` in -// that they're not unique. If the key is `null`, the attribute MUST NOT be -// set. -func MessagingKafkaMessageKey(val string) attribute.KeyValue { - return MessagingKafkaMessageKeyKey.String(val) -} - -// MessagingKafkaConsumerGroup returns an attribute KeyValue conforming to -// the "messaging.kafka.consumer.group" semantic conventions. It represents the -// name of the Kafka Consumer Group that is handling the message. Only applies -// to consumers, not producers. -func MessagingKafkaConsumerGroup(val string) attribute.KeyValue { - return MessagingKafkaConsumerGroupKey.String(val) -} - -// MessagingKafkaClientID returns an attribute KeyValue conforming to the -// "messaging.kafka.client_id" semantic conventions. It represents the client -// ID for the Consumer or Producer that is handling the message. -func MessagingKafkaClientID(val string) attribute.KeyValue { - return MessagingKafkaClientIDKey.String(val) -} - -// MessagingKafkaDestinationPartition returns an attribute KeyValue -// conforming to the "messaging.kafka.destination.partition" semantic -// conventions. It represents the partition the message is sent to. -func MessagingKafkaDestinationPartition(val int) attribute.KeyValue { - return MessagingKafkaDestinationPartitionKey.Int(val) -} - -// MessagingKafkaSourcePartition returns an attribute KeyValue conforming to -// the "messaging.kafka.source.partition" semantic conventions. It represents -// the partition the message is received from. -func MessagingKafkaSourcePartition(val int) attribute.KeyValue { - return MessagingKafkaSourcePartitionKey.Int(val) -} - -// MessagingKafkaMessageOffset returns an attribute KeyValue conforming to -// the "messaging.kafka.message.offset" semantic conventions. It represents the -// offset of a record in the corresponding Kafka partition. -func MessagingKafkaMessageOffset(val int) attribute.KeyValue { - return MessagingKafkaMessageOffsetKey.Int(val) -} - -// MessagingKafkaMessageTombstone returns an attribute KeyValue conforming -// to the "messaging.kafka.message.tombstone" semantic conventions. It -// represents a boolean that is true if the message is a tombstone. -func MessagingKafkaMessageTombstone(val bool) attribute.KeyValue { - return MessagingKafkaMessageTombstoneKey.Bool(val) -} - -// Attributes for Apache RocketMQ -const ( - // MessagingRocketmqNamespaceKey is the attribute Key conforming to the - // "messaging.rocketmq.namespace" semantic conventions. It represents the - // namespace of RocketMQ resources, resources in different namespaces are - // individual. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myNamespace' - MessagingRocketmqNamespaceKey = attribute.Key("messaging.rocketmq.namespace") - - // MessagingRocketmqClientGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.client_group" semantic conventions. It represents - // the name of the RocketMQ producer/consumer group that is handling the - // message. The client type is identified by the SpanKind. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myConsumerGroup' - MessagingRocketmqClientGroupKey = attribute.Key("messaging.rocketmq.client_group") - - // MessagingRocketmqClientIDKey is the attribute Key conforming to the - // "messaging.rocketmq.client_id" semantic conventions. It represents the - // unique identifier for each client. - // - // Type: string - // RequirementLevel: Required - // Stability: stable - // Examples: 'myhost@8742@s8083jm' - MessagingRocketmqClientIDKey = attribute.Key("messaging.rocketmq.client_id") - - // MessagingRocketmqMessageDeliveryTimestampKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delivery_timestamp" - // semantic conventions. It represents the timestamp in milliseconds that - // the delay message is expected to be delivered to consumer. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the message type is delay - // and delay time level is not specified.) - // Stability: stable - // Examples: 1665987217045 - MessagingRocketmqMessageDeliveryTimestampKey = attribute.Key("messaging.rocketmq.message.delivery_timestamp") - - // MessagingRocketmqMessageDelayTimeLevelKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delay_time_level" semantic - // conventions. It represents the delay time level for delay message, which - // determines the message delay time. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If the message type is delay - // and delivery timestamp is not specified.) - // Stability: stable - // Examples: 3 - MessagingRocketmqMessageDelayTimeLevelKey = attribute.Key("messaging.rocketmq.message.delay_time_level") - - // MessagingRocketmqMessageGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.message.group" semantic conventions. It represents - // the it is essential for FIFO message. Messages that belong to the same - // message group are always processed one by one within the same consumer - // group. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If the message type is FIFO.) - // Stability: stable - // Examples: 'myMessageGroup' - MessagingRocketmqMessageGroupKey = attribute.Key("messaging.rocketmq.message.group") - - // MessagingRocketmqMessageTypeKey is the attribute Key conforming to the - // "messaging.rocketmq.message.type" semantic conventions. It represents - // the type of message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingRocketmqMessageTypeKey = attribute.Key("messaging.rocketmq.message.type") - - // MessagingRocketmqMessageTagKey is the attribute Key conforming to the - // "messaging.rocketmq.message.tag" semantic conventions. It represents the - // secondary classifier of message besides topic. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'tagA' - MessagingRocketmqMessageTagKey = attribute.Key("messaging.rocketmq.message.tag") - - // MessagingRocketmqMessageKeysKey is the attribute Key conforming to the - // "messaging.rocketmq.message.keys" semantic conventions. It represents - // the key(s) of message, another way to mark message besides message id. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: stable - // Examples: 'keyA', 'keyB' - MessagingRocketmqMessageKeysKey = attribute.Key("messaging.rocketmq.message.keys") - - // MessagingRocketmqConsumptionModelKey is the attribute Key conforming to - // the "messaging.rocketmq.consumption_model" semantic conventions. It - // represents the model of message consumption. This only applies to - // consumer spans. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - MessagingRocketmqConsumptionModelKey = attribute.Key("messaging.rocketmq.consumption_model") -) - -var ( - // Normal message - MessagingRocketmqMessageTypeNormal = MessagingRocketmqMessageTypeKey.String("normal") - // FIFO message - MessagingRocketmqMessageTypeFifo = MessagingRocketmqMessageTypeKey.String("fifo") - // Delay message - MessagingRocketmqMessageTypeDelay = MessagingRocketmqMessageTypeKey.String("delay") - // Transaction message - MessagingRocketmqMessageTypeTransaction = MessagingRocketmqMessageTypeKey.String("transaction") -) - -var ( - // Clustering consumption model - MessagingRocketmqConsumptionModelClustering = MessagingRocketmqConsumptionModelKey.String("clustering") - // Broadcasting consumption model - MessagingRocketmqConsumptionModelBroadcasting = MessagingRocketmqConsumptionModelKey.String("broadcasting") -) - -// MessagingRocketmqNamespace returns an attribute KeyValue conforming to -// the "messaging.rocketmq.namespace" semantic conventions. It represents the -// namespace of RocketMQ resources, resources in different namespaces are -// individual. -func MessagingRocketmqNamespace(val string) attribute.KeyValue { - return MessagingRocketmqNamespaceKey.String(val) -} - -// MessagingRocketmqClientGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.client_group" semantic conventions. It represents -// the name of the RocketMQ producer/consumer group that is handling the -// message. The client type is identified by the SpanKind. -func MessagingRocketmqClientGroup(val string) attribute.KeyValue { - return MessagingRocketmqClientGroupKey.String(val) -} - -// MessagingRocketmqClientID returns an attribute KeyValue conforming to the -// "messaging.rocketmq.client_id" semantic conventions. It represents the -// unique identifier for each client. -func MessagingRocketmqClientID(val string) attribute.KeyValue { - return MessagingRocketmqClientIDKey.String(val) -} - -// MessagingRocketmqMessageDeliveryTimestamp returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delivery_timestamp" semantic -// conventions. It represents the timestamp in milliseconds that the delay -// message is expected to be delivered to consumer. -func MessagingRocketmqMessageDeliveryTimestamp(val int) attribute.KeyValue { - return MessagingRocketmqMessageDeliveryTimestampKey.Int(val) -} - -// MessagingRocketmqMessageDelayTimeLevel returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delay_time_level" semantic -// conventions. It represents the delay time level for delay message, which -// determines the message delay time. -func MessagingRocketmqMessageDelayTimeLevel(val int) attribute.KeyValue { - return MessagingRocketmqMessageDelayTimeLevelKey.Int(val) -} - -// MessagingRocketmqMessageGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.group" semantic conventions. It represents -// the it is essential for FIFO message. Messages that belong to the same -// message group are always processed one by one within the same consumer -// group. -func MessagingRocketmqMessageGroup(val string) attribute.KeyValue { - return MessagingRocketmqMessageGroupKey.String(val) -} - -// MessagingRocketmqMessageTag returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.tag" semantic conventions. It represents the -// secondary classifier of message besides topic. -func MessagingRocketmqMessageTag(val string) attribute.KeyValue { - return MessagingRocketmqMessageTagKey.String(val) -} - -// MessagingRocketmqMessageKeys returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.keys" semantic conventions. It represents -// the key(s) of message, another way to mark message besides message id. -func MessagingRocketmqMessageKeys(val ...string) attribute.KeyValue { - return MessagingRocketmqMessageKeysKey.StringSlice(val) -} - -// Semantic conventions for remote procedure calls. -const ( - // RPCSystemKey is the attribute Key conforming to the "rpc.system" - // semantic conventions. It represents a string identifying the remoting - // system. See below for a list of well-known identifiers. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - RPCSystemKey = attribute.Key("rpc.system") - - // RPCServiceKey is the attribute Key conforming to the "rpc.service" - // semantic conventions. It represents the full (logical) name of the - // service being called, including its package name, if applicable. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'myservice.EchoService' - // Note: This is the logical name of the service from the RPC interface - // perspective, which can be different from the name of any implementing - // class. The `code.namespace` attribute may be used to store the latter - // (despite the attribute name, it may include a class name; e.g., class - // with method actually executing the call on the server side, RPC client - // stub class on the client side). - RPCServiceKey = attribute.Key("rpc.service") - - // RPCMethodKey is the attribute Key conforming to the "rpc.method" - // semantic conventions. It represents the name of the (logical) method - // being called, must be equal to the $method part in the span name. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'exampleMethod' - // Note: This is the logical name of the method from the RPC interface - // perspective, which can be different from the name of any implementing - // method/function. The `code.function` attribute may be used to store the - // latter (e.g., method actually executing the call on the server side, RPC - // client stub method on the client side). - RPCMethodKey = attribute.Key("rpc.method") -) - -var ( - // gRPC - RPCSystemGRPC = RPCSystemKey.String("grpc") - // Java RMI - RPCSystemJavaRmi = RPCSystemKey.String("java_rmi") - // .NET WCF - RPCSystemDotnetWcf = RPCSystemKey.String("dotnet_wcf") - // Apache Dubbo - RPCSystemApacheDubbo = RPCSystemKey.String("apache_dubbo") -) - -// RPCService returns an attribute KeyValue conforming to the "rpc.service" -// semantic conventions. It represents the full (logical) name of the service -// being called, including its package name, if applicable. -func RPCService(val string) attribute.KeyValue { - return RPCServiceKey.String(val) -} - -// RPCMethod returns an attribute KeyValue conforming to the "rpc.method" -// semantic conventions. It represents the name of the (logical) method being -// called, must be equal to the $method part in the span name. -func RPCMethod(val string) attribute.KeyValue { - return RPCMethodKey.String(val) -} - -// Tech-specific attributes for gRPC. -const ( - // RPCGRPCStatusCodeKey is the attribute Key conforming to the - // "rpc.grpc.status_code" semantic conventions. It represents the [numeric - // status - // code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of - // the gRPC request. - // - // Type: Enum - // RequirementLevel: Required - // Stability: stable - RPCGRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") -) - -var ( - // OK - RPCGRPCStatusCodeOk = RPCGRPCStatusCodeKey.Int(0) - // CANCELLED - RPCGRPCStatusCodeCancelled = RPCGRPCStatusCodeKey.Int(1) - // UNKNOWN - RPCGRPCStatusCodeUnknown = RPCGRPCStatusCodeKey.Int(2) - // INVALID_ARGUMENT - RPCGRPCStatusCodeInvalidArgument = RPCGRPCStatusCodeKey.Int(3) - // DEADLINE_EXCEEDED - RPCGRPCStatusCodeDeadlineExceeded = RPCGRPCStatusCodeKey.Int(4) - // NOT_FOUND - RPCGRPCStatusCodeNotFound = RPCGRPCStatusCodeKey.Int(5) - // ALREADY_EXISTS - RPCGRPCStatusCodeAlreadyExists = RPCGRPCStatusCodeKey.Int(6) - // PERMISSION_DENIED - RPCGRPCStatusCodePermissionDenied = RPCGRPCStatusCodeKey.Int(7) - // RESOURCE_EXHAUSTED - RPCGRPCStatusCodeResourceExhausted = RPCGRPCStatusCodeKey.Int(8) - // FAILED_PRECONDITION - RPCGRPCStatusCodeFailedPrecondition = RPCGRPCStatusCodeKey.Int(9) - // ABORTED - RPCGRPCStatusCodeAborted = RPCGRPCStatusCodeKey.Int(10) - // OUT_OF_RANGE - RPCGRPCStatusCodeOutOfRange = RPCGRPCStatusCodeKey.Int(11) - // UNIMPLEMENTED - RPCGRPCStatusCodeUnimplemented = RPCGRPCStatusCodeKey.Int(12) - // INTERNAL - RPCGRPCStatusCodeInternal = RPCGRPCStatusCodeKey.Int(13) - // UNAVAILABLE - RPCGRPCStatusCodeUnavailable = RPCGRPCStatusCodeKey.Int(14) - // DATA_LOSS - RPCGRPCStatusCodeDataLoss = RPCGRPCStatusCodeKey.Int(15) - // UNAUTHENTICATED - RPCGRPCStatusCodeUnauthenticated = RPCGRPCStatusCodeKey.Int(16) -) - -// Tech-specific attributes for [JSON RPC](https://www.jsonrpc.org/). -const ( - // RPCJsonrpcVersionKey is the attribute Key conforming to the - // "rpc.jsonrpc.version" semantic conventions. It represents the protocol - // version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 - // does not specify this, the value can be omitted. - // - // Type: string - // RequirementLevel: ConditionallyRequired (If other than the default - // version (`1.0`)) - // Stability: stable - // Examples: '2.0', '1.0' - RPCJsonrpcVersionKey = attribute.Key("rpc.jsonrpc.version") - - // RPCJsonrpcRequestIDKey is the attribute Key conforming to the - // "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` - // property of request or response. Since protocol allows id to be int, - // string, `null` or missing (for notifications), value is expected to be - // cast to string for simplicity. Use empty string in case of `null` value. - // Omit entirely if this is a notification. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10', 'request-7', '' - RPCJsonrpcRequestIDKey = attribute.Key("rpc.jsonrpc.request_id") - - // RPCJsonrpcErrorCodeKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_code" semantic conventions. It represents the - // `error.code` property of response if it is an error response. - // - // Type: int - // RequirementLevel: ConditionallyRequired (If response is not successful.) - // Stability: stable - // Examples: -32700, 100 - RPCJsonrpcErrorCodeKey = attribute.Key("rpc.jsonrpc.error_code") - - // RPCJsonrpcErrorMessageKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_message" semantic conventions. It represents the - // `error.message` property of response if it is an error response. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'Parse error', 'User already exists' - RPCJsonrpcErrorMessageKey = attribute.Key("rpc.jsonrpc.error_message") -) - -// RPCJsonrpcVersion returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.version" semantic conventions. It represents the protocol -// version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 -// does not specify this, the value can be omitted. -func RPCJsonrpcVersion(val string) attribute.KeyValue { - return RPCJsonrpcVersionKey.String(val) -} - -// RPCJsonrpcRequestID returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` -// property of request or response. Since protocol allows id to be int, string, -// `null` or missing (for notifications), value is expected to be cast to -// string for simplicity. Use empty string in case of `null` value. Omit -// entirely if this is a notification. -func RPCJsonrpcRequestID(val string) attribute.KeyValue { - return RPCJsonrpcRequestIDKey.String(val) -} - -// RPCJsonrpcErrorCode returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_code" semantic conventions. It represents the -// `error.code` property of response if it is an error response. -func RPCJsonrpcErrorCode(val int) attribute.KeyValue { - return RPCJsonrpcErrorCodeKey.Int(val) -} - -// RPCJsonrpcErrorMessage returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_message" semantic conventions. It represents the -// `error.message` property of response if it is an error response. -func RPCJsonrpcErrorMessage(val string) attribute.KeyValue { - return RPCJsonrpcErrorMessageKey.String(val) -} diff --git a/constraint/vendor/gopkg.in/yaml.v3/LICENSE b/constraint/vendor/gopkg.in/yaml.v3/LICENSE deleted file mode 100644 index 2683e4bb1..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/README.md b/constraint/vendor/gopkg.in/yaml.v3/README.md deleted file mode 100644 index 08eb1babd..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/apic.go b/constraint/vendor/gopkg.in/yaml.v3/apic.go deleted file mode 100644 index ae7d049f1..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/decode.go b/constraint/vendor/gopkg.in/yaml.v3/decode.go deleted file mode 100644 index 0173b6982..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/emitterc.go b/constraint/vendor/gopkg.in/yaml.v3/emitterc.go deleted file mode 100644 index 0f47c9ca8..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/encode.go b/constraint/vendor/gopkg.in/yaml.v3/encode.go deleted file mode 100644 index de9e72a3e..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/parserc.go b/constraint/vendor/gopkg.in/yaml.v3/parserc.go deleted file mode 100644 index 268558a0d..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/readerc.go b/constraint/vendor/gopkg.in/yaml.v3/readerc.go deleted file mode 100644 index b7de0a89c..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/resolve.go b/constraint/vendor/gopkg.in/yaml.v3/resolve.go deleted file mode 100644 index 64ae88805..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/scannerc.go b/constraint/vendor/gopkg.in/yaml.v3/scannerc.go deleted file mode 100644 index ca0070108..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/sorter.go b/constraint/vendor/gopkg.in/yaml.v3/sorter.go deleted file mode 100644 index 9210ece7e..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/writerc.go b/constraint/vendor/gopkg.in/yaml.v3/writerc.go deleted file mode 100644 index b8a116bf9..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/yaml.go b/constraint/vendor/gopkg.in/yaml.v3/yaml.go deleted file mode 100644 index 8cec6da48..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/yamlh.go b/constraint/vendor/gopkg.in/yaml.v3/yamlh.go deleted file mode 100644 index 7c6d00770..000000000 --- a/constraint/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/constraint/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/constraint/vendor/gopkg.in/yaml.v3/yamlprivateh.go deleted file mode 100644 index e88f9c54a..000000000 --- a/constraint/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/constraint/vendor/k8s.io/api/admission/v1/types.go b/constraint/vendor/k8s.io/api/admission/v1/types.go index 34cbf2f59..f9a79ecd7 100644 --- a/constraint/vendor/k8s.io/api/admission/v1/types.go +++ b/constraint/vendor/k8s.io/api/admission/v1/types.go @@ -28,7 +28,7 @@ import ( // AdmissionReview describes an admission review request/response. type AdmissionReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // request describes the attributes for the admission request. // +optional Request *AdmissionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1/generated.proto b/constraint/vendor/k8s.io/api/admissionregistration/v1/generated.proto index 89c1475b2..718b7c14e 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1/generated.proto @@ -872,6 +872,7 @@ message TypeChecking { } // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" message ValidatingAdmissionPolicy { // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional @@ -926,7 +927,7 @@ message ValidatingAdmissionPolicyBindingSpec { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string policyName = 1; // paramRef specifies the parameter resource used to configure the admission control policy. @@ -985,7 +986,7 @@ message ValidatingAdmissionPolicyBindingSpec { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string validationActions = 4; } @@ -1099,6 +1100,9 @@ message ValidatingAdmissionPolicyStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 3; } diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1/types.go b/constraint/vendor/k8s.io/api/admissionregistration/v1/types.go index f7a07b645..8047d5c5f 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1/types.go +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1/types.go @@ -139,8 +139,9 @@ const ( // +k8s:prerelease-lifecycle-gen:introduced=1.30 // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" type ValidatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -167,6 +168,9 @@ type ValidatingAdmissionPolicyStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" protobuf:"bytes,3,rep,name=conditions"` } @@ -199,7 +203,7 @@ type ExpressionWarning struct { // ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy. type ValidatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -447,7 +451,7 @@ type AuditAnnotation struct { // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -461,7 +465,7 @@ type ValidatingAdmissionPolicyBinding struct { // ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding. type ValidatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -476,7 +480,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required PolicyName string `json:"policyName,omitempty" protobuf:"bytes,1,rep,name=policyName"` // paramRef specifies the parameter resource used to configure the admission control policy. @@ -535,7 +539,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required ValidationActions []ValidationAction `json:"validationActions,omitempty" protobuf:"bytes,4,rep,name=validationActions"` } @@ -714,7 +718,7 @@ type NamedRuleWithOperations struct { // +optional ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,1,rep,name=resourceNames"` // RuleWithOperations is a tuple of Operations and Resources. - RuleWithOperations `json:",inline" protobuf:"bytes,2,opt,name=ruleWithOperations"` + RuleWithOperations `json:"" protobuf:"bytes,2,opt,name=ruleWithOperations"` } // +genclient @@ -724,7 +728,7 @@ type NamedRuleWithOperations struct { // ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. type ValidatingWebhookConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -742,7 +746,7 @@ type ValidatingWebhookConfiguration struct { // ValidatingWebhookConfigurationList is a list of ValidatingWebhookConfiguration. type ValidatingWebhookConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -758,7 +762,7 @@ type ValidatingWebhookConfigurationList struct { // MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object. type MutatingWebhookConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -776,7 +780,7 @@ type MutatingWebhookConfiguration struct { // MutatingWebhookConfigurationList is a list of MutatingWebhookConfiguration. type MutatingWebhookConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1110,7 +1114,7 @@ type MutatingWebhook struct { // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1123,7 +1127,7 @@ type MutatingAdmissionPolicy struct { // MutatingAdmissionPolicyList is a list of MutatingAdmissionPolicy. type MutatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1383,7 +1387,7 @@ type JSONPatch struct { // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1396,7 +1400,7 @@ type MutatingAdmissionPolicyBinding struct { // MutatingAdmissionPolicyBindingList is a list of MutatingAdmissionPolicyBinding. type MutatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1458,7 +1462,7 @@ type RuleWithOperations struct { Operations []OperationType `json:"operations,omitempty" protobuf:"bytes,1,rep,name=operations,casttype=OperationType"` // Rule is embedded, it describes other criteria of the rule, like // APIGroups, APIVersions, Resources, etc. - Rule `json:",inline" protobuf:"bytes,2,opt,name=rule"` + Rule `json:"" protobuf:"bytes,2,opt,name=rule"` } // OperationType specifies an operation for a request. diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/generated.proto index 57c7cd2b1..8802ac92d 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/generated.proto @@ -594,6 +594,7 @@ message TypeChecking { } // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" message ValidatingAdmissionPolicy { // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional @@ -648,7 +649,7 @@ message ValidatingAdmissionPolicyBindingSpec { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string policyName = 1; // paramRef specifies the parameter resource used to configure the admission control policy. @@ -707,7 +708,7 @@ message ValidatingAdmissionPolicyBindingSpec { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string validationActions = 4; } @@ -821,6 +822,9 @@ message ValidatingAdmissionPolicyStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 3; } diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/types.go b/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/types.go index 6a789b2d7..39ff0abdc 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1alpha1/types.go @@ -81,8 +81,9 @@ const ( // +k8s:prerelease-lifecycle-gen:introduced=1.26 // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" type ValidatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -109,6 +110,9 @@ type ValidatingAdmissionPolicyStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" protobuf:"bytes,3,rep,name=conditions"` } @@ -138,7 +142,7 @@ type ExpressionWarning struct { // ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy. type ValidatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -387,7 +391,7 @@ type AuditAnnotation struct { // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -401,7 +405,7 @@ type ValidatingAdmissionPolicyBinding struct { // ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding. type ValidatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -416,7 +420,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required PolicyName string `json:"policyName,omitempty" protobuf:"bytes,1,rep,name=policyName"` // paramRef specifies the parameter resource used to configure the admission control policy. @@ -475,7 +479,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required ValidationActions []ValidationAction `json:"validationActions,omitempty" protobuf:"bytes,4,rep,name=validationActions"` } @@ -652,7 +656,7 @@ type NamedRuleWithOperations struct { // +optional ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,1,rep,name=resourceNames"` // RuleWithOperations is a tuple of Operations and Resources. - RuleWithOperations `json:",inline" protobuf:"bytes,2,opt,name=ruleWithOperations"` + RuleWithOperations `json:"" protobuf:"bytes,2,opt,name=ruleWithOperations"` } // RuleWithOperations is a tuple of Operations and Resources. It is recommended to make @@ -679,7 +683,7 @@ const ( // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -692,7 +696,7 @@ type MutatingAdmissionPolicy struct { // MutatingAdmissionPolicyList is a list of MutatingAdmissionPolicy. type MutatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -967,7 +971,7 @@ const ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -980,7 +984,7 @@ type MutatingAdmissionPolicyBinding struct { // MutatingAdmissionPolicyBindingList is a list of MutatingAdmissionPolicyBinding. type MutatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/generated.proto index 5fcb74f8b..465429231 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/generated.proto @@ -820,6 +820,7 @@ message TypeChecking { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.28 // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" message ValidatingAdmissionPolicy { // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional @@ -874,7 +875,7 @@ message ValidatingAdmissionPolicyBindingSpec { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string policyName = 1; // paramRef specifies the parameter resource used to configure the admission control policy. @@ -933,7 +934,7 @@ message ValidatingAdmissionPolicyBindingSpec { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string validationActions = 4; } @@ -1049,6 +1050,9 @@ message ValidatingAdmissionPolicyStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 3; } diff --git a/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/types.go b/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/types.go index 734a606f4..1fb6728fc 100644 --- a/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/admissionregistration/v1beta1/types.go @@ -93,8 +93,9 @@ const ( // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.28 // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. +// +k8s:supportsSubresource="/status" type ValidatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -121,6 +122,9 @@ type ValidatingAdmissionPolicyStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" protobuf:"bytes,3,rep,name=conditions"` } @@ -152,7 +156,7 @@ type ExpressionWarning struct { // +k8s:prerelease-lifecycle-gen:introduced=1.28 // ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy. type ValidatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -400,7 +404,7 @@ type AuditAnnotation struct { // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -414,7 +418,7 @@ type ValidatingAdmissionPolicyBinding struct { // ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding. type ValidatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -429,7 +433,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // If the referenced resource does not exist, this binding is considered invalid and will be ignored // Required. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required PolicyName string `json:"policyName,omitempty" protobuf:"bytes,1,rep,name=policyName"` // paramRef specifies the parameter resource used to configure the admission control policy. @@ -488,7 +492,7 @@ type ValidatingAdmissionPolicyBindingSpec struct { // Required. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required ValidationActions []ValidationAction `json:"validationActions,omitempty" protobuf:"bytes,4,rep,name=validationActions"` } @@ -667,7 +671,7 @@ type NamedRuleWithOperations struct { // +optional ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,1,rep,name=resourceNames"` // RuleWithOperations is a tuple of Operations and Resources. - RuleWithOperations `json:",inline" protobuf:"bytes,2,opt,name=ruleWithOperations"` + RuleWithOperations `json:"" protobuf:"bytes,2,opt,name=ruleWithOperations"` } // +genclient @@ -681,7 +685,7 @@ type NamedRuleWithOperations struct { // ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. // Deprecated in v1.16, planned for removal in v1.19. Use admissionregistration.k8s.io/v1 ValidatingWebhookConfiguration instead. type ValidatingWebhookConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -702,7 +706,7 @@ type ValidatingWebhookConfiguration struct { // ValidatingWebhookConfigurationList is a list of ValidatingWebhookConfiguration. type ValidatingWebhookConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -722,7 +726,7 @@ type ValidatingWebhookConfigurationList struct { // MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object. // Deprecated in v1.16, planned for removal in v1.19. Use admissionregistration.k8s.io/v1 MutatingWebhookConfiguration instead. type MutatingWebhookConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -743,7 +747,7 @@ type MutatingWebhookConfiguration struct { // MutatingWebhookConfigurationList is a list of MutatingWebhookConfiguration. type MutatingWebhookConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1213,7 +1217,7 @@ type MatchCondition struct { // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1227,7 +1231,7 @@ type MutatingAdmissionPolicy struct { // MutatingAdmissionPolicyList is a list of MutatingAdmissionPolicy. type MutatingAdmissionPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1488,7 +1492,7 @@ type JSONPatch struct { // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBinding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1502,7 +1506,7 @@ type MutatingAdmissionPolicyBinding struct { // MutatingAdmissionPolicyBindingList is a list of MutatingAdmissionPolicyBinding. type MutatingAdmissionPolicyBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2/generated.proto b/constraint/vendor/k8s.io/api/apidiscovery/v2/generated.proto index 7f58048e1..e42fec471 100644 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2/generated.proto +++ b/constraint/vendor/k8s.io/api/apidiscovery/v2/generated.proto @@ -38,12 +38,14 @@ message APIGroupDiscovery { // name is allowed to be "" to represent the legacy, ungroupified resources. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // versions are the versions supported in this group. They are sorted in descending order of preference, // with the preferred version being the first entry. // +listType=map // +listMapKey=version + // +optional repeated APIVersionDiscovery versions = 2; } @@ -58,6 +60,7 @@ message APIGroupDiscoveryList { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; // items is the list of groups for discovery. The groups are listed in priority order. + // +optional repeated APIGroupDiscovery items = 2; } @@ -67,40 +70,48 @@ message APIResourceDiscovery { // for this resource across all versions in the API group. // Resources with non-empty groups are located at /apis/// // Resources with empty groups are located at /api/v1/ + // +optional optional string resource = 1; // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. // APIs may return other objects types at their discretion, such as error conditions, requests for alternate representations, or other operation specific behavior. // This value will be null or empty if an APIService reports subresources but supports no operations on the parent resource + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind responseKind = 2; // scope indicates the scope of a resource, either Cluster or Namespaced + // +optional optional string scope = 3; // singularResource is the singular name of the resource. This allows clients to handle plural and singular opaquely. // For many clients the singular form of the resource will be more understandable to users reading messages and should be used when integrating the name of the resource into a sentence. // The command line tool kubectl, for example, allows use of the singular resource name in place of plurals. // The singular form of a resource should always be an optional element - when in doubt use the canonical resource name. + // +optional optional string singularResource = 4; // verbs is a list of supported API operation types (this includes // but is not limited to get, list, watch, create, update, patch, // delete, deletecollection, and proxy). // +listType=set + // +optional repeated string verbs = 5; // shortNames is a list of suggested short names of the resource. // +listType=set + // +optional repeated string shortNames = 6; // categories is a list of the grouped resources this resource belongs to (e.g. 'all'). // Clients may use this to simplify acting on multiple resource types at once. // +listType=set + // +optional repeated string categories = 7; // subresources is a list of subresources provided by this resource. Subresources are located at /apis////name-of-instance/ // +listType=map // +listMapKey=subresource + // +optional repeated APISubresourceDiscovery subresources = 8; } @@ -108,10 +119,12 @@ message APIResourceDiscovery { message APISubresourceDiscovery { // subresource is the name of the subresource. This is used in the URL path and is the unique identifier // for this resource across all versions. + // +optional optional string subresource = 1; // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. // Some subresources do not return normal resources, these will have null or empty return types. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind responseKind = 2; // acceptedTypes describes the kinds that this endpoint accepts. @@ -122,6 +135,7 @@ message APISubresourceDiscovery { // +listMapKey=group // +listMapKey=version // +listMapKey=kind + // +optional repeated .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind acceptedTypes = 3; // verbs is a list of supported API operation types (this includes @@ -131,17 +145,20 @@ message APISubresourceDiscovery { // should expect the behavior of standard verbs to align with // Kubernetes interaction conventions. // +listType=set + // +optional repeated string verbs = 4; } // APIVersionDiscovery holds a list of APIResourceDiscovery types that are served for a particular version within an API Group. message APIVersionDiscovery { // version is the name of the version within a group version. + // +optional optional string version = 1; // resources is a list of APIResourceDiscovery objects for the corresponding group version. // +listType=map // +listMapKey=resource + // +optional repeated APIResourceDiscovery resources = 2; // freshness marks whether a group version's discovery document is up to date. @@ -151,6 +168,7 @@ message APIVersionDiscovery { // significantly out of date. Clients that require the latest // version of the discovery information be retrieved before // performing an operation should not use the aggregated document + // +optional optional string freshness = 3; } diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2/types.go b/constraint/vendor/k8s.io/api/apidiscovery/v2/types.go index 761bb6990..5cf6d9c55 100644 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2/types.go +++ b/constraint/vendor/k8s.io/api/apidiscovery/v2/types.go @@ -28,12 +28,13 @@ import ( // list of API resources (built-ins, Custom Resource Definitions, resources from aggregated servers) // that a cluster supports. type APIGroupDiscoveryList struct { - v1.TypeMeta `json:",inline"` + v1.TypeMeta `json:""` // ResourceVersion will not be set, because this does not have a replayable ordering among multiple apiservers. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // items is the list of groups for discovery. The groups are listed in priority order. + // +optional Items []APIGroupDiscovery `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -44,28 +45,32 @@ type APIGroupDiscoveryList struct { // It contains a list of APIVersionDiscovery that holds a list of APIResourceDiscovery types served for a version. // Versions are in descending order of preference, with the first version being the preferred entry. type APIGroupDiscovery struct { - v1.TypeMeta `json:",inline"` + v1.TypeMeta `json:""` // metadata is standard object's metadata. // The only field completed will be name. For instance, resourceVersion will be empty. // name is the name of the API group whose discovery information is presented here. // name is allowed to be "" to represent the legacy, ungroupified resources. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // versions are the versions supported in this group. They are sorted in descending order of preference, // with the preferred version being the first entry. // +listType=map // +listMapKey=version + // +optional Versions []APIVersionDiscovery `json:"versions,omitempty" protobuf:"bytes,2,rep,name=versions"` } // APIVersionDiscovery holds a list of APIResourceDiscovery types that are served for a particular version within an API Group. type APIVersionDiscovery struct { // version is the name of the version within a group version. + // +optional Version string `json:"version" protobuf:"bytes,1,opt,name=version"` // resources is a list of APIResourceDiscovery objects for the corresponding group version. // +listType=map // +listMapKey=resource + // +optional Resources []APIResourceDiscovery `json:"resources,omitempty" protobuf:"bytes,2,rep,name=resources"` // freshness marks whether a group version's discovery document is up to date. // "Current" indicates the discovery document was recently @@ -74,6 +79,7 @@ type APIVersionDiscovery struct { // significantly out of date. Clients that require the latest // version of the discovery information be retrieved before // performing an operation should not use the aggregated document + // +optional Freshness DiscoveryFreshness `json:"freshness,omitempty" protobuf:"bytes,3,opt,name=freshness"` } @@ -83,33 +89,41 @@ type APIResourceDiscovery struct { // for this resource across all versions in the API group. // Resources with non-empty groups are located at /apis/// // Resources with empty groups are located at /api/v1/ + // +optional Resource string `json:"resource" protobuf:"bytes,1,opt,name=resource"` // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. // APIs may return other objects types at their discretion, such as error conditions, requests for alternate representations, or other operation specific behavior. // This value will be null or empty if an APIService reports subresources but supports no operations on the parent resource + // +optional ResponseKind *v1.GroupVersionKind `json:"responseKind,omitempty" protobuf:"bytes,2,opt,name=responseKind"` // scope indicates the scope of a resource, either Cluster or Namespaced + // +optional Scope ResourceScope `json:"scope" protobuf:"bytes,3,opt,name=scope"` // singularResource is the singular name of the resource. This allows clients to handle plural and singular opaquely. // For many clients the singular form of the resource will be more understandable to users reading messages and should be used when integrating the name of the resource into a sentence. // The command line tool kubectl, for example, allows use of the singular resource name in place of plurals. // The singular form of a resource should always be an optional element - when in doubt use the canonical resource name. + // +optional SingularResource string `json:"singularResource" protobuf:"bytes,4,opt,name=singularResource"` // verbs is a list of supported API operation types (this includes // but is not limited to get, list, watch, create, update, patch, // delete, deletecollection, and proxy). // +listType=set + // +optional Verbs []string `json:"verbs" protobuf:"bytes,5,opt,name=verbs"` // shortNames is a list of suggested short names of the resource. // +listType=set + // +optional ShortNames []string `json:"shortNames,omitempty" protobuf:"bytes,6,rep,name=shortNames"` // categories is a list of the grouped resources this resource belongs to (e.g. 'all'). // Clients may use this to simplify acting on multiple resource types at once. // +listType=set + // +optional Categories []string `json:"categories,omitempty" protobuf:"bytes,7,rep,name=categories"` // subresources is a list of subresources provided by this resource. Subresources are located at /apis////name-of-instance/ // +listType=map // +listMapKey=subresource + // +optional Subresources []APISubresourceDiscovery `json:"subresources,omitempty" protobuf:"bytes,8,rep,name=subresources"` } @@ -133,9 +147,11 @@ const ( type APISubresourceDiscovery struct { // subresource is the name of the subresource. This is used in the URL path and is the unique identifier // for this resource across all versions. + // +optional Subresource string `json:"subresource" protobuf:"bytes,1,opt,name=subresource"` // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. // Some subresources do not return normal resources, these will have null or empty return types. + // +optional ResponseKind *v1.GroupVersionKind `json:"responseKind,omitempty" protobuf:"bytes,2,opt,name=responseKind"` // acceptedTypes describes the kinds that this endpoint accepts. // Subresources may accept the standard content types or define @@ -145,6 +161,7 @@ type APISubresourceDiscovery struct { // +listMapKey=group // +listMapKey=version // +listMapKey=kind + // +optional AcceptedTypes []v1.GroupVersionKind `json:"acceptedTypes,omitempty" protobuf:"bytes,3,rep,name=acceptedTypes"` // verbs is a list of supported API operation types (this includes // but is not limited to get, list, watch, create, update, patch, @@ -153,5 +170,6 @@ type APISubresourceDiscovery struct { // should expect the behavior of standard verbs to align with // Kubernetes interaction conventions. // +listType=set + // +optional Verbs []string `json:"verbs" protobuf:"bytes,4,opt,name=verbs"` } diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.pb.go b/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.pb.go deleted file mode 100644 index 8994f570f..000000000 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.pb.go +++ /dev/null @@ -1,1537 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: k8s.io/api/apidiscovery/v2beta1/generated.proto - -package v2beta1 - -import ( - fmt "fmt" - - io "io" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - math_bits "math/bits" - reflect "reflect" - strings "strings" -) - -func (m *APIGroupDiscovery) Reset() { *m = APIGroupDiscovery{} } - -func (m *APIGroupDiscoveryList) Reset() { *m = APIGroupDiscoveryList{} } - -func (m *APIResourceDiscovery) Reset() { *m = APIResourceDiscovery{} } - -func (m *APISubresourceDiscovery) Reset() { *m = APISubresourceDiscovery{} } - -func (m *APIVersionDiscovery) Reset() { *m = APIVersionDiscovery{} } - -func (m *APIGroupDiscovery) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *APIGroupDiscovery) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *APIGroupDiscovery) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Versions) > 0 { - for iNdEx := len(m.Versions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Versions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *APIGroupDiscoveryList) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *APIGroupDiscoveryList) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *APIGroupDiscoveryList) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *APIResourceDiscovery) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *APIResourceDiscovery) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *APIResourceDiscovery) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Subresources) > 0 { - for iNdEx := len(m.Subresources) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Subresources[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.Categories) > 0 { - for iNdEx := len(m.Categories) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Categories[iNdEx]) - copy(dAtA[i:], m.Categories[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Categories[iNdEx]))) - i-- - dAtA[i] = 0x3a - } - } - if len(m.ShortNames) > 0 { - for iNdEx := len(m.ShortNames) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.ShortNames[iNdEx]) - copy(dAtA[i:], m.ShortNames[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.ShortNames[iNdEx]))) - i-- - dAtA[i] = 0x32 - } - } - if len(m.Verbs) > 0 { - for iNdEx := len(m.Verbs) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Verbs[iNdEx]) - copy(dAtA[i:], m.Verbs[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Verbs[iNdEx]))) - i-- - dAtA[i] = 0x2a - } - } - i -= len(m.SingularResource) - copy(dAtA[i:], m.SingularResource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.SingularResource))) - i-- - dAtA[i] = 0x22 - i -= len(m.Scope) - copy(dAtA[i:], m.Scope) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Scope))) - i-- - dAtA[i] = 0x1a - if m.ResponseKind != nil { - { - size, err := m.ResponseKind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - i -= len(m.Resource) - copy(dAtA[i:], m.Resource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Resource))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *APISubresourceDiscovery) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *APISubresourceDiscovery) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *APISubresourceDiscovery) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Verbs) > 0 { - for iNdEx := len(m.Verbs) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Verbs[iNdEx]) - copy(dAtA[i:], m.Verbs[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Verbs[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if len(m.AcceptedTypes) > 0 { - for iNdEx := len(m.AcceptedTypes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AcceptedTypes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if m.ResponseKind != nil { - { - size, err := m.ResponseKind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - i -= len(m.Subresource) - copy(dAtA[i:], m.Subresource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Subresource))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *APIVersionDiscovery) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *APIVersionDiscovery) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *APIVersionDiscovery) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - i -= len(m.Freshness) - copy(dAtA[i:], m.Freshness) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Freshness))) - i-- - dAtA[i] = 0x1a - if len(m.Resources) > 0 { - for iNdEx := len(m.Resources) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Resources[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - i -= len(m.Version) - copy(dAtA[i:], m.Version) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Version))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *APIGroupDiscovery) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ObjectMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Versions) > 0 { - for _, e := range m.Versions { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *APIGroupDiscoveryList) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ListMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Items) > 0 { - for _, e := range m.Items { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *APIResourceDiscovery) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Resource) - n += 1 + l + sovGenerated(uint64(l)) - if m.ResponseKind != nil { - l = m.ResponseKind.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.Scope) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.SingularResource) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Verbs) > 0 { - for _, s := range m.Verbs { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - if len(m.ShortNames) > 0 { - for _, s := range m.ShortNames { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - if len(m.Categories) > 0 { - for _, s := range m.Categories { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - if len(m.Subresources) > 0 { - for _, e := range m.Subresources { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *APISubresourceDiscovery) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Subresource) - n += 1 + l + sovGenerated(uint64(l)) - if m.ResponseKind != nil { - l = m.ResponseKind.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.AcceptedTypes) > 0 { - for _, e := range m.AcceptedTypes { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - if len(m.Verbs) > 0 { - for _, s := range m.Verbs { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *APIVersionDiscovery) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Version) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Resources) > 0 { - for _, e := range m.Resources { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - l = len(m.Freshness) - n += 1 + l + sovGenerated(uint64(l)) - return n -} - -func sovGenerated(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenerated(x uint64) (n int) { - return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *APIGroupDiscovery) String() string { - if this == nil { - return "nil" - } - repeatedStringForVersions := "[]APIVersionDiscovery{" - for _, f := range this.Versions { - repeatedStringForVersions += strings.Replace(strings.Replace(f.String(), "APIVersionDiscovery", "APIVersionDiscovery", 1), `&`, ``, 1) + "," - } - repeatedStringForVersions += "}" - s := strings.Join([]string{`&APIGroupDiscovery{`, - `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Versions:` + repeatedStringForVersions + `,`, - `}`, - }, "") - return s -} -func (this *APIGroupDiscoveryList) String() string { - if this == nil { - return "nil" - } - repeatedStringForItems := "[]APIGroupDiscovery{" - for _, f := range this.Items { - repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "APIGroupDiscovery", "APIGroupDiscovery", 1), `&`, ``, 1) + "," - } - repeatedStringForItems += "}" - s := strings.Join([]string{`&APIGroupDiscoveryList{`, - `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, - `Items:` + repeatedStringForItems + `,`, - `}`, - }, "") - return s -} -func (this *APIResourceDiscovery) String() string { - if this == nil { - return "nil" - } - repeatedStringForSubresources := "[]APISubresourceDiscovery{" - for _, f := range this.Subresources { - repeatedStringForSubresources += strings.Replace(strings.Replace(f.String(), "APISubresourceDiscovery", "APISubresourceDiscovery", 1), `&`, ``, 1) + "," - } - repeatedStringForSubresources += "}" - s := strings.Join([]string{`&APIResourceDiscovery{`, - `Resource:` + fmt.Sprintf("%v", this.Resource) + `,`, - `ResponseKind:` + strings.Replace(fmt.Sprintf("%v", this.ResponseKind), "GroupVersionKind", "v1.GroupVersionKind", 1) + `,`, - `Scope:` + fmt.Sprintf("%v", this.Scope) + `,`, - `SingularResource:` + fmt.Sprintf("%v", this.SingularResource) + `,`, - `Verbs:` + fmt.Sprintf("%v", this.Verbs) + `,`, - `ShortNames:` + fmt.Sprintf("%v", this.ShortNames) + `,`, - `Categories:` + fmt.Sprintf("%v", this.Categories) + `,`, - `Subresources:` + repeatedStringForSubresources + `,`, - `}`, - }, "") - return s -} -func (this *APISubresourceDiscovery) String() string { - if this == nil { - return "nil" - } - repeatedStringForAcceptedTypes := "[]GroupVersionKind{" - for _, f := range this.AcceptedTypes { - repeatedStringForAcceptedTypes += fmt.Sprintf("%v", f) + "," - } - repeatedStringForAcceptedTypes += "}" - s := strings.Join([]string{`&APISubresourceDiscovery{`, - `Subresource:` + fmt.Sprintf("%v", this.Subresource) + `,`, - `ResponseKind:` + strings.Replace(fmt.Sprintf("%v", this.ResponseKind), "GroupVersionKind", "v1.GroupVersionKind", 1) + `,`, - `AcceptedTypes:` + repeatedStringForAcceptedTypes + `,`, - `Verbs:` + fmt.Sprintf("%v", this.Verbs) + `,`, - `}`, - }, "") - return s -} -func (this *APIVersionDiscovery) String() string { - if this == nil { - return "nil" - } - repeatedStringForResources := "[]APIResourceDiscovery{" - for _, f := range this.Resources { - repeatedStringForResources += strings.Replace(strings.Replace(f.String(), "APIResourceDiscovery", "APIResourceDiscovery", 1), `&`, ``, 1) + "," - } - repeatedStringForResources += "}" - s := strings.Join([]string{`&APIVersionDiscovery{`, - `Version:` + fmt.Sprintf("%v", this.Version) + `,`, - `Resources:` + repeatedStringForResources + `,`, - `Freshness:` + fmt.Sprintf("%v", this.Freshness) + `,`, - `}`, - }, "") - return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *APIGroupDiscovery) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: APIGroupDiscovery: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: APIGroupDiscovery: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Versions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Versions = append(m.Versions, APIVersionDiscovery{}) - if err := m.Versions[len(m.Versions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *APIGroupDiscoveryList) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: APIGroupDiscoveryList: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: APIGroupDiscoveryList: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Items = append(m.Items, APIGroupDiscovery{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *APIResourceDiscovery) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: APIResourceDiscovery: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: APIResourceDiscovery: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Resource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResponseKind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ResponseKind == nil { - m.ResponseKind = &v1.GroupVersionKind{} - } - if err := m.ResponseKind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Scope", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Scope = ResourceScope(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SingularResource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SingularResource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Verbs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Verbs = append(m.Verbs, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShortNames", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ShortNames = append(m.ShortNames, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Categories", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Categories = append(m.Categories, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subresources", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subresources = append(m.Subresources, APISubresourceDiscovery{}) - if err := m.Subresources[len(m.Subresources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *APISubresourceDiscovery) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: APISubresourceDiscovery: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: APISubresourceDiscovery: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subresource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subresource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResponseKind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ResponseKind == nil { - m.ResponseKind = &v1.GroupVersionKind{} - } - if err := m.ResponseKind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AcceptedTypes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AcceptedTypes = append(m.AcceptedTypes, v1.GroupVersionKind{}) - if err := m.AcceptedTypes[len(m.AcceptedTypes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Verbs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Verbs = append(m.Verbs, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *APIVersionDiscovery) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: APIVersionDiscovery: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: APIVersionDiscovery: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Version = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Resources = append(m.Resources, APIResourceDiscovery{}) - if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Freshness", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Freshness = DiscoveryFreshness(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenerated(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenerated - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenerated - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenerated - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") -) diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.proto b/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.proto deleted file mode 100644 index f81449e6a..000000000 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/generated.proto +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -// This file was autogenerated by go-to-protobuf. Do not edit it manually! - -syntax = "proto2"; - -package k8s.io.api.apidiscovery.v2beta1; - -import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; - -// Package-wide variables from generator "generated". -option go_package = "k8s.io/api/apidiscovery/v2beta1"; - -// APIGroupDiscovery holds information about which resources are being served for all version of the API Group. -// It contains a list of APIVersionDiscovery that holds a list of APIResourceDiscovery types served for a version. -// Versions are in descending order of preference, with the first version being the preferred entry. -message APIGroupDiscovery { - // metadata is standard object's metadata. - // The only field completed will be name. For instance, resourceVersion will be empty. - // name is the name of the API group whose discovery information is presented here. - // name is allowed to be "" to represent the legacy, ungroupified resources. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - - // versions are the versions supported in this group. They are sorted in descending order of preference, - // with the preferred version being the first entry. - // +listType=map - // +listMapKey=version - repeated APIVersionDiscovery versions = 2; -} - -// APIGroupDiscoveryList is a resource containing a list of APIGroupDiscovery. -// This is one of the types able to be returned from the /api and /apis endpoint and contains an aggregated -// list of API resources (built-ins, Custom Resource Definitions, resources from aggregated servers) -// that a cluster supports. -message APIGroupDiscoveryList { - // ResourceVersion will not be set, because this does not have a replayable ordering among multiple apiservers. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; - - // items is the list of groups for discovery. The groups are listed in priority order. - repeated APIGroupDiscovery items = 2; -} - -// APIResourceDiscovery provides information about an API resource for discovery. -message APIResourceDiscovery { - // resource is the plural name of the resource. This is used in the URL path and is the unique identifier - // for this resource across all versions in the API group. - // Resources with non-empty groups are located at /apis/// - // Resources with empty groups are located at /api/v1/ - optional string resource = 1; - - // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. - // APIs may return other objects types at their discretion, such as error conditions, requests for alternate representations, or other operation specific behavior. - // This value will be null or empty if an APIService reports subresources but supports no operations on the parent resource - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind responseKind = 2; - - // scope indicates the scope of a resource, either Cluster or Namespaced - optional string scope = 3; - - // singularResource is the singular name of the resource. This allows clients to handle plural and singular opaquely. - // For many clients the singular form of the resource will be more understandable to users reading messages and should be used when integrating the name of the resource into a sentence. - // The command line tool kubectl, for example, allows use of the singular resource name in place of plurals. - // The singular form of a resource should always be an optional element - when in doubt use the canonical resource name. - optional string singularResource = 4; - - // verbs is a list of supported API operation types (this includes - // but is not limited to get, list, watch, create, update, patch, - // delete, deletecollection, and proxy). - // +listType=set - repeated string verbs = 5; - - // shortNames is a list of suggested short names of the resource. - // +listType=set - repeated string shortNames = 6; - - // categories is a list of the grouped resources this resource belongs to (e.g. 'all'). - // Clients may use this to simplify acting on multiple resource types at once. - // +listType=set - repeated string categories = 7; - - // subresources is a list of subresources provided by this resource. Subresources are located at /apis////name-of-instance/ - // +listType=map - // +listMapKey=subresource - repeated APISubresourceDiscovery subresources = 8; -} - -// APISubresourceDiscovery provides information about an API subresource for discovery. -message APISubresourceDiscovery { - // subresource is the name of the subresource. This is used in the URL path and is the unique identifier - // for this resource across all versions. - optional string subresource = 1; - - // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. - // Some subresources do not return normal resources, these will have null or empty return types. - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind responseKind = 2; - - // acceptedTypes describes the kinds that this endpoint accepts. - // Subresources may accept the standard content types or define - // custom negotiation schemes. The list may not be exhaustive for - // all operations. - // +listType=map - // +listMapKey=group - // +listMapKey=version - // +listMapKey=kind - repeated .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind acceptedTypes = 3; - - // verbs is a list of supported API operation types (this includes - // but is not limited to get, list, watch, create, update, patch, - // delete, deletecollection, and proxy). Subresources may define - // custom verbs outside the standard Kubernetes verb set. Clients - // should expect the behavior of standard verbs to align with - // Kubernetes interaction conventions. - // +listType=set - repeated string verbs = 4; -} - -// APIVersionDiscovery holds a list of APIResourceDiscovery types that are served for a particular version within an API Group. -message APIVersionDiscovery { - // version is the name of the version within a group version. - optional string version = 1; - - // resources is a list of APIResourceDiscovery objects for the corresponding group version. - // +listType=map - // +listMapKey=resource - repeated APIResourceDiscovery resources = 2; - - // freshness marks whether a group version's discovery document is up to date. - // "Current" indicates the discovery document was recently - // refreshed. "Stale" indicates the discovery document could not - // be retrieved and the returned discovery document may be - // significantly out of date. Clients that require the latest - // version of the discovery information be retrieved before - // performing an operation should not use the aggregated document - optional string freshness = 3; -} - diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/types.go b/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/types.go deleted file mode 100644 index 306264da4..000000000 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/types.go +++ /dev/null @@ -1,163 +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 v2beta1 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:prerelease-lifecycle-gen:introduced=1.26 -// +k8s:prerelease-lifecycle-gen:deprecated=1.32 -// +k8s:prerelease-lifecycle-gen:removed=1.35 -// The deprecate and remove versions stated above are rough estimates and may be subject to change. We are estimating v2 types will be available in 1.28 and will support 4 versions where both v2beta1 and v2 are supported before deprecation. - -// APIGroupDiscoveryList is a resource containing a list of APIGroupDiscovery. -// This is one of the types able to be returned from the /api and /apis endpoint and contains an aggregated -// list of API resources (built-ins, Custom Resource Definitions, resources from aggregated servers) -// that a cluster supports. -type APIGroupDiscoveryList struct { - v1.TypeMeta `json:",inline"` - // ResourceVersion will not be set, because this does not have a replayable ordering among multiple apiservers. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // +optional - v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // items is the list of groups for discovery. The groups are listed in priority order. - Items []APIGroupDiscovery `json:"items" protobuf:"bytes,2,rep,name=items"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:prerelease-lifecycle-gen:introduced=1.26 -// +k8s:prerelease-lifecycle-gen:deprecated=1.32 -// +k8s:prerelease-lifecycle-gen:removed=1.35 -// The deprecate and remove versions stated above are rough estimates and may be subject to change. We are estimating v2 types will be available in 1.28 and will support 4 versions where both v2beta1 and v2 are supported before deprecation. - -// APIGroupDiscovery holds information about which resources are being served for all version of the API Group. -// It contains a list of APIVersionDiscovery that holds a list of APIResourceDiscovery types served for a version. -// Versions are in descending order of preference, with the first version being the preferred entry. -type APIGroupDiscovery struct { - v1.TypeMeta `json:",inline"` - // metadata is standard object's metadata. - // The only field completed will be name. For instance, resourceVersion will be empty. - // name is the name of the API group whose discovery information is presented here. - // name is allowed to be "" to represent the legacy, ungroupified resources. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // +optional - v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // versions are the versions supported in this group. They are sorted in descending order of preference, - // with the preferred version being the first entry. - // +listType=map - // +listMapKey=version - Versions []APIVersionDiscovery `json:"versions,omitempty" protobuf:"bytes,2,rep,name=versions"` -} - -// APIVersionDiscovery holds a list of APIResourceDiscovery types that are served for a particular version within an API Group. -type APIVersionDiscovery struct { - // version is the name of the version within a group version. - Version string `json:"version" protobuf:"bytes,1,opt,name=version"` - // resources is a list of APIResourceDiscovery objects for the corresponding group version. - // +listType=map - // +listMapKey=resource - Resources []APIResourceDiscovery `json:"resources,omitempty" protobuf:"bytes,2,rep,name=resources"` - // freshness marks whether a group version's discovery document is up to date. - // "Current" indicates the discovery document was recently - // refreshed. "Stale" indicates the discovery document could not - // be retrieved and the returned discovery document may be - // significantly out of date. Clients that require the latest - // version of the discovery information be retrieved before - // performing an operation should not use the aggregated document - Freshness DiscoveryFreshness `json:"freshness,omitempty" protobuf:"bytes,3,opt,name=freshness"` -} - -// APIResourceDiscovery provides information about an API resource for discovery. -type APIResourceDiscovery struct { - // resource is the plural name of the resource. This is used in the URL path and is the unique identifier - // for this resource across all versions in the API group. - // Resources with non-empty groups are located at /apis/// - // Resources with empty groups are located at /api/v1/ - Resource string `json:"resource" protobuf:"bytes,1,opt,name=resource"` - // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. - // APIs may return other objects types at their discretion, such as error conditions, requests for alternate representations, or other operation specific behavior. - // This value will be null or empty if an APIService reports subresources but supports no operations on the parent resource - ResponseKind *v1.GroupVersionKind `json:"responseKind,omitempty" protobuf:"bytes,2,opt,name=responseKind"` - // scope indicates the scope of a resource, either Cluster or Namespaced - Scope ResourceScope `json:"scope" protobuf:"bytes,3,opt,name=scope"` - // singularResource is the singular name of the resource. This allows clients to handle plural and singular opaquely. - // For many clients the singular form of the resource will be more understandable to users reading messages and should be used when integrating the name of the resource into a sentence. - // The command line tool kubectl, for example, allows use of the singular resource name in place of plurals. - // The singular form of a resource should always be an optional element - when in doubt use the canonical resource name. - SingularResource string `json:"singularResource" protobuf:"bytes,4,opt,name=singularResource"` - // verbs is a list of supported API operation types (this includes - // but is not limited to get, list, watch, create, update, patch, - // delete, deletecollection, and proxy). - // +listType=set - Verbs []string `json:"verbs" protobuf:"bytes,5,opt,name=verbs"` - // shortNames is a list of suggested short names of the resource. - // +listType=set - ShortNames []string `json:"shortNames,omitempty" protobuf:"bytes,6,rep,name=shortNames"` - // categories is a list of the grouped resources this resource belongs to (e.g. 'all'). - // Clients may use this to simplify acting on multiple resource types at once. - // +listType=set - Categories []string `json:"categories,omitempty" protobuf:"bytes,7,rep,name=categories"` - // subresources is a list of subresources provided by this resource. Subresources are located at /apis////name-of-instance/ - // +listType=map - // +listMapKey=subresource - Subresources []APISubresourceDiscovery `json:"subresources,omitempty" protobuf:"bytes,8,rep,name=subresources"` -} - -// ResourceScope is an enum defining the different scopes available to a resource. -type ResourceScope string - -const ( - ScopeCluster ResourceScope = "Cluster" - ScopeNamespace ResourceScope = "Namespaced" -) - -// DiscoveryFreshness is an enum defining whether the Discovery document published by an apiservice is up to date (fresh). -type DiscoveryFreshness string - -const ( - DiscoveryFreshnessCurrent DiscoveryFreshness = "Current" - DiscoveryFreshnessStale DiscoveryFreshness = "Stale" -) - -// APISubresourceDiscovery provides information about an API subresource for discovery. -type APISubresourceDiscovery struct { - // subresource is the name of the subresource. This is used in the URL path and is the unique identifier - // for this resource across all versions. - Subresource string `json:"subresource" protobuf:"bytes,1,opt,name=subresource"` - // responseKind describes the group, version, and kind of the serialization schema for the object type this endpoint typically returns. - // Some subresources do not return normal resources, these will have null or empty return types. - ResponseKind *v1.GroupVersionKind `json:"responseKind,omitempty" protobuf:"bytes,2,opt,name=responseKind"` - // acceptedTypes describes the kinds that this endpoint accepts. - // Subresources may accept the standard content types or define - // custom negotiation schemes. The list may not be exhaustive for - // all operations. - // +listType=map - // +listMapKey=group - // +listMapKey=version - // +listMapKey=kind - AcceptedTypes []v1.GroupVersionKind `json:"acceptedTypes,omitempty" protobuf:"bytes,3,rep,name=acceptedTypes"` - // verbs is a list of supported API operation types (this includes - // but is not limited to get, list, watch, create, update, patch, - // delete, deletecollection, and proxy). Subresources may define - // custom verbs outside the standard Kubernetes verb set. Clients - // should expect the behavior of standard verbs to align with - // Kubernetes interaction conventions. - // +listType=set - Verbs []string `json:"verbs" protobuf:"bytes,4,opt,name=verbs"` -} diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.deepcopy.go deleted file mode 100644 index cf8f98c6f..000000000 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.deepcopy.go +++ /dev/null @@ -1,190 +0,0 @@ -//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 deepcopy-gen. DO NOT EDIT. - -package v2beta1 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIGroupDiscovery) DeepCopyInto(out *APIGroupDiscovery) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]APIVersionDiscovery, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIGroupDiscovery. -func (in *APIGroupDiscovery) DeepCopy() *APIGroupDiscovery { - if in == nil { - return nil - } - out := new(APIGroupDiscovery) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIGroupDiscovery) 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 *APIGroupDiscoveryList) DeepCopyInto(out *APIGroupDiscoveryList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIGroupDiscovery, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIGroupDiscoveryList. -func (in *APIGroupDiscoveryList) DeepCopy() *APIGroupDiscoveryList { - if in == nil { - return nil - } - out := new(APIGroupDiscoveryList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIGroupDiscoveryList) 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 *APIResourceDiscovery) DeepCopyInto(out *APIResourceDiscovery) { - *out = *in - if in.ResponseKind != nil { - in, out := &in.ResponseKind, &out.ResponseKind - *out = new(v1.GroupVersionKind) - **out = **in - } - if in.Verbs != nil { - in, out := &in.Verbs, &out.Verbs - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.ShortNames != nil { - in, out := &in.ShortNames, &out.ShortNames - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Categories != nil { - in, out := &in.Categories, &out.Categories - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Subresources != nil { - in, out := &in.Subresources, &out.Subresources - *out = make([]APISubresourceDiscovery, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIResourceDiscovery. -func (in *APIResourceDiscovery) DeepCopy() *APIResourceDiscovery { - if in == nil { - return nil - } - out := new(APIResourceDiscovery) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APISubresourceDiscovery) DeepCopyInto(out *APISubresourceDiscovery) { - *out = *in - if in.ResponseKind != nil { - in, out := &in.ResponseKind, &out.ResponseKind - *out = new(v1.GroupVersionKind) - **out = **in - } - if in.AcceptedTypes != nil { - in, out := &in.AcceptedTypes, &out.AcceptedTypes - *out = make([]v1.GroupVersionKind, len(*in)) - copy(*out, *in) - } - if in.Verbs != nil { - in, out := &in.Verbs, &out.Verbs - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APISubresourceDiscovery. -func (in *APISubresourceDiscovery) DeepCopy() *APISubresourceDiscovery { - if in == nil { - return nil - } - out := new(APISubresourceDiscovery) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIVersionDiscovery) DeepCopyInto(out *APIVersionDiscovery) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]APIResourceDiscovery, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIVersionDiscovery. -func (in *APIVersionDiscovery) DeepCopy() *APIVersionDiscovery { - if in == nil { - return nil - } - out := new(APIVersionDiscovery) - in.DeepCopyInto(out) - return out -} diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.prerelease-lifecycle.go deleted file mode 100644 index aa8f15fb4..000000000 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.prerelease-lifecycle.go +++ /dev/null @@ -1,58 +0,0 @@ -//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 prerelease-lifecycle-gen. DO NOT EDIT. - -package v2beta1 - -// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. -func (in *APIGroupDiscovery) APILifecycleIntroduced() (major, minor int) { - return 1, 26 -} - -// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. -func (in *APIGroupDiscovery) APILifecycleDeprecated() (major, minor int) { - return 1, 32 -} - -// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. -func (in *APIGroupDiscovery) APILifecycleRemoved() (major, minor int) { - return 1, 35 -} - -// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. -func (in *APIGroupDiscoveryList) APILifecycleIntroduced() (major, minor int) { - return 1, 26 -} - -// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. -func (in *APIGroupDiscoveryList) APILifecycleDeprecated() (major, minor int) { - return 1, 32 -} - -// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. -func (in *APIGroupDiscoveryList) APILifecycleRemoved() (major, minor int) { - return 1, 35 -} diff --git a/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto index e8f8c339d..73f007a65 100644 --- a/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/generated.proto @@ -55,6 +55,7 @@ message ServerStorageVersion { } // Storage version of a specific resource. +// +k8s:supportsSubresource="/status" message StorageVersion { // metadata is the standard object metadata. // The name is .. diff --git a/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/types.go b/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/types.go index 69c21fd3c..f30cc5381 100644 --- a/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/apiserverinternal/v1alpha1/types.go @@ -25,8 +25,9 @@ import ( // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // Storage version of a specific resource. +// +k8s:supportsSubresource="/status" type StorageVersion struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata. // The name is .. // +required @@ -135,7 +136,7 @@ type StorageVersionCondition struct { // A list of StorageVersions. type StorageVersionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/apps/v1/generated.proto b/constraint/vendor/k8s.io/api/apps/v1/generated.proto index 42d5415c2..0c55e2ebc 100644 --- a/constraint/vendor/k8s.io/api/apps/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/apps/v1/generated.proto @@ -46,9 +46,11 @@ message ControllerRevision { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Data is the serialized representation of the state. + // +required optional .k8s.io.apimachinery.pkg.runtime.RawExtension data = 2; // Revision indicates the revision of the state represented by Data. + // +optional optional int64 revision = 3; } @@ -63,6 +65,7 @@ message ControllerRevisionList { } // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" message DaemonSet { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -71,7 +74,7 @@ message DaemonSet { // The desired behavior of this daemon set. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional DaemonSetSpec spec = 2; // The current status of this daemon set. This data may be @@ -86,9 +89,11 @@ message DaemonSet { // DaemonSetCondition describes the state of a DaemonSet at a certain point. message DaemonSetCondition { // Type of DaemonSet condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // Last time the condition transitioned from one status to another. @@ -121,6 +126,7 @@ message DaemonSetSpec { // Must match in order to be controlled. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 1; // An object that describes the pod that will be created. @@ -129,6 +135,7 @@ message DaemonSetSpec { // selector is specified). // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 2; // An update strategy to replace existing DaemonSet pods with new pods. @@ -221,6 +228,8 @@ message DaemonSetUpdateStrategy { } // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message Deployment { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -228,7 +237,7 @@ message Deployment { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the Deployment. - // +optional + // +required optional DeploymentSpec spec = 2; // Most recently observed status of the Deployment. @@ -239,21 +248,27 @@ message Deployment { // DeploymentCondition describes the state of a deployment at a certain point. message DeploymentCondition { // Type of deployment condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // The last time this condition was updated. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastUpdateTime = 6; // Last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 7; // The reason for the condition's last transition. + // +optional optional string reason = 4; // A human readable message indicating details about the transition. + // +optional optional string message = 5; } @@ -277,10 +292,12 @@ message DeploymentSpec { // Label selector for pods. Existing ReplicaSets whose pods are // selected by this will be the ones affected by this deployment. // It must match the pod template's labels. + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // The deployment strategy to use to replace existing pods with new ones. @@ -309,6 +326,7 @@ message DeploymentSpec { // process failed deployments and a condition with a ProgressDeadlineExceeded // reason will be surfaced in the deployment status. Note that progress will // not be estimated during the time a deployment is paused. Defaults to 600s. + // +optional optional int32 progressDeadlineSeconds = 9; } @@ -377,6 +395,8 @@ message DeploymentStrategy { } // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message ReplicaSet { // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -387,7 +407,7 @@ message ReplicaSet { // Spec defines the specification of the desired behavior of the ReplicaSet. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional ReplicaSetSpec spec = 2; // Status is the most recently observed status of the ReplicaSet. @@ -402,9 +422,11 @@ message ReplicaSet { // ReplicaSetCondition describes the state of a replica set at a certain point. message ReplicaSetCondition { // Type of replica set condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // The last time the condition transitioned from one status to another. @@ -451,6 +473,7 @@ message ReplicaSetSpec { // Label keys and values that must match in order to be controlled by this replica set. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // Template is the object that describes the pod that will be created if @@ -598,6 +621,8 @@ message RollingUpdateStatefulSetStrategy { // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message StatefulSet { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -605,7 +630,7 @@ message StatefulSet { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines the desired identities of pods in this set. - // +optional + // +required optional StatefulSetSpec spec = 2; // Status is the current status of Pods in this StatefulSet. This data @@ -617,9 +642,11 @@ message StatefulSet { // StatefulSetCondition describes the state of a statefulset at a certain point. message StatefulSetCondition { // Type of statefulset condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // Last time the condition transitioned from one status to another. @@ -668,6 +695,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional optional string whenDeleted = 1; // WhenScaled specifies what happens to PVCs created from StatefulSet @@ -675,6 +703,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional optional string whenScaled = 2; } @@ -691,6 +720,9 @@ message StatefulSetSpec { // selector is a label query over pods that should match the replica count. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // template is the object that describes the pod that will be created if @@ -700,6 +732,7 @@ message StatefulSetSpec { // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". // The only allowed template.spec.restartPolicy value is "Always". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -710,6 +743,9 @@ message StatefulSetSpec { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType // +listType=atomic repeated .k8s.io.api.core.v1.PersistentVolumeClaim volumeClaimTemplates = 4; @@ -719,6 +755,8 @@ message StatefulSetSpec { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string serviceName = 5; // podManagementPolicy controls how pods are created during initial scale up, @@ -730,17 +768,21 @@ message StatefulSetSpec { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string podManagementPolicy = 6; // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional optional StatefulSetUpdateStrategy updateStrategy = 7; // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional optional int32 revisionHistoryLimit = 8; // Minimum number of seconds for which a newly created pod should be ready diff --git a/constraint/vendor/k8s.io/api/apps/v1/types.go b/constraint/vendor/k8s.io/api/apps/v1/types.go index b8989c140..c43afb881 100644 --- a/constraint/vendor/k8s.io/api/apps/v1/types.go +++ b/constraint/vendor/k8s.io/api/apps/v1/types.go @@ -46,15 +46,17 @@ const ( // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type StatefulSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // 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" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired identities of pods in this set. - // +optional + // +required Spec StatefulSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current status of Pods in this StatefulSet. This data @@ -104,12 +106,22 @@ const ( // strategy, new Pods will be created from the specification version indicated // by the StatefulSet's updateRevision. RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate" - // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version - // tracking and ordered rolling restarts are disabled. Pods are recreated - // from the StatefulSetSpec when they are manually deleted. When a scale - // operation is performed with this strategy,specification version indicated - // by the StatefulSet's currentRevision. + // OnDeleteStatefulSetStrategyType disables ordered rolling restarts. Version + // tracking is done on a best-effort basis - the controller will try to + // eventually converge StatefulSet's currentRevision with updateRevision. + // Pods are recreated from the StatefulSetSpec when they are manually deleted. + // When a scale operation is performed with this strategy, new Pods will be + // created from the specification version indicated by the StatefulSet's updateRevision. OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete" + // RecreateStatefulSetStrategyType indicates that all existing pods will be + // deleted and fully terminated before any new-revision pods are created. + // This ensures that old and new revision Pods never run at the same time. + // This is an alpha type and requires enabling StatefulSetRecreateStrategy feature gate. + // Switching to the Recreate strategy is allowed when the feature gate is enabled, + // and switching away from it to a different update strategy is also allowed. + // + // +featureGate=StatefulSetRecreateStrategy + RecreateStatefulSetStrategyType StatefulSetUpdateStrategyType = "Recreate" ) // RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType. @@ -158,12 +170,14 @@ type StatefulSetPersistentVolumeClaimRetentionPolicy struct { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional WhenDeleted PersistentVolumeClaimRetentionPolicyType `json:"whenDeleted,omitempty" protobuf:"bytes,1,opt,name=whenDeleted,casttype=PersistentVolumeClaimRetentionPolicyType"` // WhenScaled specifies what happens to PVCs created from StatefulSet // VolumeClaimTemplates when the StatefulSet is scaled down. The default // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional WhenScaled PersistentVolumeClaimRetentionPolicyType `json:"whenScaled,omitempty" protobuf:"bytes,2,opt,name=whenScaled,casttype=PersistentVolumeClaimRetentionPolicyType"` } @@ -195,6 +209,9 @@ type StatefulSetSpec struct { // selector is a label query over pods that should match the replica count. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // template is the object that describes the pod that will be created if @@ -204,6 +221,7 @@ type StatefulSetSpec struct { // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". // The only allowed template.spec.restartPolicy value is "Always". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -214,6 +232,9 @@ type StatefulSetSpec struct { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType // +listType=atomic VolumeClaimTemplates []v1.PersistentVolumeClaim `json:"volumeClaimTemplates,omitempty" protobuf:"bytes,4,rep,name=volumeClaimTemplates"` @@ -223,6 +244,8 @@ type StatefulSetSpec struct { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional ServiceName string `json:"serviceName" protobuf:"bytes,5,opt,name=serviceName"` // podManagementPolicy controls how pods are created during initial scale up, @@ -234,17 +257,21 @@ type StatefulSetSpec struct { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional PodManagementPolicy PodManagementPolicyType `json:"podManagementPolicy,omitempty" protobuf:"bytes,6,opt,name=podManagementPolicy,casttype=PodManagementPolicyType"` // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional UpdateStrategy StatefulSetUpdateStrategy `json:"updateStrategy,omitempty" protobuf:"bytes,7,opt,name=updateStrategy"` // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,8,opt,name=revisionHistoryLimit"` // Minimum number of seconds for which a newly created pod should be ready @@ -319,11 +346,19 @@ type StatefulSetStatus struct { type StatefulSetConditionType string +const ( + // StatefulSetProgressing means the StatefulSet is progressing through an update. + // This condition is an alpha type and requires enabling StatefulSetRecreateStrategy feature gate. + StatefulSetProgressing StatefulSetConditionType = "Progressing" +) + // StatefulSetCondition describes the state of a statefulset at a certain point. type StatefulSetCondition struct { // Type of statefulset condition. + // +optional Type StatefulSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // Last time the condition transitioned from one status to another. // +optional @@ -341,7 +376,7 @@ type StatefulSetCondition struct { // StatefulSetList is a collection of StatefulSets. type StatefulSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -359,15 +394,17 @@ type StatefulSetList struct { // +k8s:prerelease-lifecycle-gen:introduced=1.9 // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type Deployment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // 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" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the Deployment. - // +optional + // +required Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the Deployment. @@ -385,10 +422,12 @@ type DeploymentSpec struct { // Label selector for pods. Existing ReplicaSets whose pods are // selected by this will be the ones affected by this deployment. // It must match the pod template's labels. + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // The deployment strategy to use to replace existing pods with new ones. @@ -417,6 +456,7 @@ type DeploymentSpec struct { // process failed deployments and a condition with a ProgressDeadlineExceeded // reason will be surfaced in the deployment status. Note that progress will // not be estimated during the time a deployment is paused. Defaults to 600s. + // +optional ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty" protobuf:"varint,9,opt,name=progressDeadlineSeconds"` } @@ -552,16 +592,22 @@ const ( // DeploymentCondition describes the state of a deployment at a certain point. type DeploymentCondition struct { // Type of deployment condition. + // +optional Type DeploymentConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DeploymentConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // The last time this condition was updated. + // +optional LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,6,opt,name=lastUpdateTime"` // Last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,7,opt,name=lastTransitionTime"` // The reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // A human readable message indicating details about the transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -570,7 +616,7 @@ type DeploymentCondition struct { // DeploymentList is a list of Deployments. type DeploymentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -652,6 +698,7 @@ type DaemonSetSpec struct { // Must match in order to be controlled. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,1,opt,name=selector"` // An object that describes the pod that will be created. @@ -660,6 +707,7 @@ type DaemonSetSpec struct { // selector is specified). // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,2,opt,name=template"` // An update strategy to replace existing DaemonSet pods with new pods. @@ -743,8 +791,10 @@ type DaemonSetConditionType string // DaemonSetCondition describes the state of a DaemonSet at a certain point. type DaemonSetCondition struct { // Type of DaemonSet condition. + // +optional Type DaemonSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DaemonSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // Last time the condition transitioned from one status to another. // +optional @@ -762,8 +812,9 @@ type DaemonSetCondition struct { // +k8s:prerelease-lifecycle-gen:introduced=1.9 // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" type DaemonSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -771,7 +822,7 @@ type DaemonSet struct { // The desired behavior of this daemon set. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec DaemonSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // The current status of this daemon set. This data may be @@ -795,7 +846,7 @@ const ( // DaemonSetList is a collection of daemon sets. type DaemonSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -813,8 +864,10 @@ type DaemonSetList struct { // +k8s:prerelease-lifecycle-gen:introduced=1.9 // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type ReplicaSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -825,7 +878,7 @@ type ReplicaSet struct { // Spec defines the specification of the desired behavior of the ReplicaSet. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec ReplicaSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the most recently observed status of the ReplicaSet. @@ -842,7 +895,7 @@ type ReplicaSet struct { // ReplicaSetList is a collection of ReplicaSets. type ReplicaSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -872,6 +925,7 @@ type ReplicaSetSpec struct { // Label keys and values that must match in order to be controlled by this replica set. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // Template is the object that describes the pod that will be created if @@ -932,8 +986,10 @@ const ( // ReplicaSetCondition describes the state of a replica set at a certain point. type ReplicaSetCondition struct { // Type of replica set condition. + // +optional Type ReplicaSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=ReplicaSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // The last time the condition transitioned from one status to another. // +optional @@ -960,16 +1016,18 @@ type ReplicaSetCondition struct { // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevision struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // 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" protobuf:"bytes,1,opt,name=metadata"` // Data is the serialized representation of the state. - Data runtime.RawExtension `json:"data,omitempty" protobuf:"bytes,2,opt,name=data"` + // +required + Data runtime.RawExtension `json:"data" protobuf:"bytes,2,opt,name=data"` // Revision indicates the revision of the state represented by Data. + // +optional Revision int64 `json:"revision" protobuf:"varint,3,opt,name=revision"` } @@ -978,7 +1036,7 @@ type ControllerRevision struct { // ControllerRevisionList is a resource containing a list of ControllerRevision objects. type ControllerRevisionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/apps/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/apps/v1beta1/generated.proto index c6f0628e0..9d2388334 100644 --- a/constraint/vendor/k8s.io/api/apps/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/apps/v1beta1/generated.proto @@ -48,9 +48,11 @@ message ControllerRevision { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // data is the serialized representation of the state. + // +required optional .k8s.io.apimachinery.pkg.runtime.RawExtension data = 2; // revision indicates the revision of the state represented by Data. + // +optional optional int64 revision = 3; } @@ -67,13 +69,15 @@ message ControllerRevisionList { // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message Deployment { // Standard object metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the Deployment. - // +optional + // +required optional DeploymentSpec spec = 2; // Most recently observed status of the Deployment. @@ -84,21 +88,27 @@ message Deployment { // DeploymentCondition describes the state of a deployment at a certain point. message DeploymentCondition { // Type of deployment condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // The last time this condition was updated. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastUpdateTime = 6; // Last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 7; // The reason for the condition's last transition. + // +optional optional string reason = 4; // A human readable message indicating details about the transition. + // +optional optional string message = 5; } @@ -116,6 +126,7 @@ message DeploymentList { // DeploymentRollback stores the information required to rollback a deployment. message DeploymentRollback { // Required: This must match the Name of a deployment. + // +required optional string name = 1; // The annotations to be updated to a deployment @@ -123,6 +134,7 @@ message DeploymentRollback { map updatedAnnotations = 2; // The config of this deployment rollback. + // +optional optional RollbackConfig rollbackTo = 3; } @@ -140,6 +152,7 @@ message DeploymentSpec { // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // The deployment strategy to use to replace existing pods with new ones. @@ -284,6 +297,7 @@ message RollingUpdateStatefulSetStrategy { // for updates. During a rolling update, all pods from ordinal Replicas-1 to // Partition are updated. All pods from ordinal Partition-1 to 0 remain untouched. // This is helpful in being able to do a canary based deployment. The default value is 0. + // +optional optional int32 partition = 1; // maxUnavailable is the maximum number of pods that can be unavailable during the update. @@ -303,6 +317,7 @@ message RollingUpdateStatefulSetStrategy { message Scale { // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -318,15 +333,16 @@ message Scale { message ScaleSpec { // replicas is the number of observed instances of the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 replicas = 1; } // ScaleStatus represents the current status of a scale subresource. message ScaleStatus { // replias is the actual number of observed instances of the scaled object. + // +optional optional int32 replicas = 1; // selector is a label query over pods that should match the replicas count. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ @@ -352,12 +368,14 @@ message ScaleStatus { // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message StatefulSet { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines the desired identities of pods in this set. - // +optional + // +required optional StatefulSetSpec spec = 2; // Status is the current status of Pods in this StatefulSet. This data @@ -369,9 +387,11 @@ message StatefulSet { // StatefulSetCondition describes the state of a statefulset at a certain point. message StatefulSetCondition { // Type of statefulset condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // Last time the condition transitioned from one status to another. @@ -417,6 +437,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional optional string whenDeleted = 1; // whenScaled specifies what happens to PVCs created from StatefulSet @@ -424,6 +445,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional optional string whenScaled = 2; } @@ -438,9 +460,11 @@ message StatefulSetSpec { optional int32 replicas = 1; // selector is a label query over pods that should match the replica count. - // If empty, defaulted to labels on the pod template. + // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - // +optional + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // template is the object that describes the pod that will be created if @@ -449,6 +473,7 @@ message StatefulSetSpec { // of the StatefulSet. Each pod will be named with the format // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -459,7 +484,10 @@ message StatefulSetSpec { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType repeated .k8s.io.api.core.v1.PersistentVolumeClaim volumeClaimTemplates = 4; // serviceName is the name of the service that governs this StatefulSet. @@ -468,6 +496,8 @@ message StatefulSetSpec { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string serviceName = 5; // podManagementPolicy controls how pods are created during initial scale up, @@ -479,17 +509,21 @@ message StatefulSetSpec { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string podManagementPolicy = 6; // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional optional StatefulSetUpdateStrategy updateStrategy = 7; // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional optional int32 revisionHistoryLimit = 8; // minReadySeconds is the minimum number of seconds for which a newly created pod should be ready @@ -567,9 +601,11 @@ message StatefulSetStatus { // necessary to perform the update for the indicated strategy. message StatefulSetUpdateStrategy { // Type indicates the type of the StatefulSetUpdateStrategy. + // +optional optional string type = 1; // RollingUpdate is used to communicate parameters when Type is RollingUpdateStatefulSetStrategyType. + // +optional optional RollingUpdateStatefulSetStrategy rollingUpdate = 2; } diff --git a/constraint/vendor/k8s.io/api/apps/v1beta1/types.go b/constraint/vendor/k8s.io/api/apps/v1beta1/types.go index 4e67338e3..9960ac0b3 100644 --- a/constraint/vendor/k8s.io/api/apps/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/apps/v1beta1/types.go @@ -33,15 +33,16 @@ const ( type ScaleSpec struct { // replicas is the number of observed instances of the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } // ScaleStatus represents the current status of a scale subresource. type ScaleStatus struct { // replias is the actual number of observed instances of the scaled object. + // +optional Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // selector is a label query over pods that should match the replicas count. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ @@ -67,9 +68,10 @@ type ScaleStatus struct { // Scale represents a scaling request for a resource. type Scale struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -97,13 +99,15 @@ type Scale struct { // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type StatefulSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired identities of pods in this set. - // +optional + // +required Spec StatefulSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current status of Pods in this StatefulSet. This data @@ -132,8 +136,10 @@ const ( // necessary to perform the update for the indicated strategy. type StatefulSetUpdateStrategy struct { // Type indicates the type of the StatefulSetUpdateStrategy. + // +optional Type StatefulSetUpdateStrategyType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetStrategyType"` // RollingUpdate is used to communicate parameters when Type is RollingUpdateStatefulSetStrategyType. + // +optional RollingUpdate *RollingUpdateStatefulSetStrategy `json:"rollingUpdate,omitempty" protobuf:"bytes,2,opt,name=rollingUpdate"` } @@ -148,11 +154,12 @@ const ( // strategy, new Pods will be created from the specification version indicated // by the StatefulSet's updateRevision. RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate" - // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version - // tracking and ordered rolling restarts are disabled. Pods are recreated - // from the StatefulSetSpec when they are manually deleted. When a scale - // operation is performed with this strategy,specification version indicated - // by the StatefulSet's currentRevision. + // OnDeleteStatefulSetStrategyType disables ordered rolling restarts. Version + // tracking is done on a best-effort basis - the controller will try to + // eventually converge StatefulSet's currentRevision with updateRevision. + // Pods are recreated from the StatefulSetSpec when they are manually deleted. + // When a scale operation is performed with this strategy, new Pods will be + // created from the specification version indicated by the StatefulSet's updateRevision. OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete" ) @@ -162,6 +169,7 @@ type RollingUpdateStatefulSetStrategy struct { // for updates. During a rolling update, all pods from ordinal Replicas-1 to // Partition are updated. All pods from ordinal Partition-1 to 0 remain untouched. // This is helpful in being able to do a canary based deployment. The default value is 0. + // +optional Partition *int32 `json:"partition,omitempty" protobuf:"varint,1,opt,name=partition"` // maxUnavailable is the maximum number of pods that can be unavailable during the update. // Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). @@ -201,12 +209,14 @@ type StatefulSetPersistentVolumeClaimRetentionPolicy struct { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional WhenDeleted PersistentVolumeClaimRetentionPolicyType `json:"whenDeleted,omitempty" protobuf:"bytes,1,opt,name=whenDeleted,casttype=PersistentVolumeClaimRetentionPolicyType"` // whenScaled specifies what happens to PVCs created from StatefulSet // VolumeClaimTemplates when the StatefulSet is scaled down. The default // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional WhenScaled PersistentVolumeClaimRetentionPolicyType `json:"whenScaled,omitempty" protobuf:"bytes,2,opt,name=whenScaled,casttype=PersistentVolumeClaimRetentionPolicyType"` } @@ -236,9 +246,11 @@ type StatefulSetSpec struct { Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // selector is a label query over pods that should match the replica count. - // If empty, defaulted to labels on the pod template. + // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - // +optional + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` // template is the object that describes the pod that will be created if @@ -247,6 +259,7 @@ type StatefulSetSpec struct { // of the StatefulSet. Each pod will be named with the format // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -257,7 +270,10 @@ type StatefulSetSpec struct { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType VolumeClaimTemplates []v1.PersistentVolumeClaim `json:"volumeClaimTemplates,omitempty" protobuf:"bytes,4,rep,name=volumeClaimTemplates"` // serviceName is the name of the service that governs this StatefulSet. @@ -266,6 +282,8 @@ type StatefulSetSpec struct { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional ServiceName string `json:"serviceName" protobuf:"bytes,5,opt,name=serviceName"` // podManagementPolicy controls how pods are created during initial scale up, @@ -277,17 +295,21 @@ type StatefulSetSpec struct { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional PodManagementPolicy PodManagementPolicyType `json:"podManagementPolicy,omitempty" protobuf:"bytes,6,opt,name=podManagementPolicy,casttype=PodManagementPolicyType"` // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional UpdateStrategy StatefulSetUpdateStrategy `json:"updateStrategy,omitempty" protobuf:"bytes,7,opt,name=updateStrategy"` // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,8,opt,name=revisionHistoryLimit"` // minReadySeconds is the minimum number of seconds for which a newly created pod should be ready @@ -365,8 +387,10 @@ type StatefulSetConditionType string // StatefulSetCondition describes the state of a statefulset at a certain point. type StatefulSetCondition struct { // Type of statefulset condition. + // +optional Type StatefulSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // Last time the condition transitioned from one status to another. // +optional @@ -387,7 +411,7 @@ type StatefulSetCondition struct { // StatefulSetList is a collection of StatefulSets. type StatefulSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` Items []StatefulSet `json:"items" protobuf:"bytes,2,rep,name=items"` @@ -403,14 +427,16 @@ type StatefulSetList struct { // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type Deployment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the Deployment. - // +optional + // +required Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the Deployment. @@ -432,6 +458,7 @@ type DeploymentSpec struct { // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // The deployment strategy to use to replace existing pods with new ones. @@ -478,13 +505,15 @@ type DeploymentSpec struct { // DEPRECATED. // DeploymentRollback stores the information required to rollback a deployment. type DeploymentRollback struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Required: This must match the Name of a deployment. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // The annotations to be updated to a deployment // +optional UpdatedAnnotations map[string]string `json:"updatedAnnotations,omitempty" protobuf:"bytes,2,rep,name=updatedAnnotations"` // The config of this deployment rollback. + // +optional RollbackTo RollbackConfig `json:"rollbackTo" protobuf:"bytes,3,opt,name=rollbackTo"` } @@ -626,16 +655,22 @@ const ( // DeploymentCondition describes the state of a deployment at a certain point. type DeploymentCondition struct { // Type of deployment condition. + // +optional Type DeploymentConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DeploymentConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // The last time this condition was updated. + // +optional LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,6,opt,name=lastUpdateTime"` // Last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,7,opt,name=lastTransitionTime"` // The reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // A human readable message indicating details about the transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -647,7 +682,7 @@ type DeploymentCondition struct { // DeploymentList is a list of Deployments. type DeploymentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -675,16 +710,18 @@ type DeploymentList struct { // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevision struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // 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" protobuf:"bytes,1,opt,name=metadata"` // data is the serialized representation of the state. - Data runtime.RawExtension `json:"data,omitempty" protobuf:"bytes,2,opt,name=data"` + // +required + Data runtime.RawExtension `json:"data" protobuf:"bytes,2,opt,name=data"` // revision indicates the revision of the state represented by Data. + // +optional Revision int64 `json:"revision" protobuf:"varint,3,opt,name=revision"` } @@ -696,7 +733,7 @@ type ControllerRevision struct { // ControllerRevisionList is a resource containing a list of ControllerRevision objects. type ControllerRevisionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/apps/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/apps/v1beta1/types_swagger_doc_generated.go index a6f7a1192..e0efc96cd 100644 --- a/constraint/vendor/k8s.io/api/apps/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/apps/v1beta1/types_swagger_doc_generated.go @@ -251,7 +251,7 @@ func (StatefulSetPersistentVolumeClaimRetentionPolicy) SwaggerDoc() map[string]s var map_StatefulSetSpec = map[string]string{ "": "A StatefulSetSpec is the specification of a StatefulSet.", "replicas": "replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1.", - "selector": "selector is a label query over pods that should match the replica count. If empty, defaulted to labels on the pod template. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", + "selector": "selector is a label query over pods that should match the replica count. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", "template": "template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the StatefulSet will fulfill this Template, but have a unique identity from the rest of the StatefulSet. Each pod will be named with the format -. For example, a pod in a StatefulSet named \"web\" with index number \"3\" would be named \"web-3\".", "volumeClaimTemplates": "volumeClaimTemplates is a list of claims that pods are allowed to reference. The StatefulSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pod. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name.", "serviceName": "serviceName is the name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set. Pods get DNS/hostnames that follow the pattern: pod-specific-string.serviceName.default.svc.cluster.local where \"pod-specific-string\" is managed by the StatefulSet controller.", diff --git a/constraint/vendor/k8s.io/api/apps/v1beta2/generated.proto b/constraint/vendor/k8s.io/api/apps/v1beta2/generated.proto index d680c9663..738b1236e 100644 --- a/constraint/vendor/k8s.io/api/apps/v1beta2/generated.proto +++ b/constraint/vendor/k8s.io/api/apps/v1beta2/generated.proto @@ -48,9 +48,11 @@ message ControllerRevision { optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Data is the serialized representation of the state. + // +required optional .k8s.io.apimachinery.pkg.runtime.RawExtension data = 2; // Revision indicates the revision of the state represented by Data. + // +optional optional int64 revision = 3; } @@ -67,6 +69,7 @@ message ControllerRevisionList { // DEPRECATED - This group version of DaemonSet is deprecated by apps/v1/DaemonSet. See the release notes for // more information. // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" message DaemonSet { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -75,7 +78,7 @@ message DaemonSet { // The desired behavior of this daemon set. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional DaemonSetSpec spec = 2; // The current status of this daemon set. This data may be @@ -90,9 +93,11 @@ message DaemonSet { // DaemonSetCondition describes the state of a DaemonSet at a certain point. message DaemonSetCondition { // Type of DaemonSet condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // Last time the condition transitioned from one status to another. @@ -125,6 +130,7 @@ message DaemonSetSpec { // Must match in order to be controlled. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 1; // An object that describes the pod that will be created. @@ -133,6 +139,7 @@ message DaemonSetSpec { // selector is specified). // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 2; // An update strategy to replace existing DaemonSet pods with new pods. @@ -227,13 +234,15 @@ message DaemonSetUpdateStrategy { // DEPRECATED - This group version of Deployment is deprecated by apps/v1/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message Deployment { // Standard object metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the Deployment. - // +optional + // +required optional DeploymentSpec spec = 2; // Most recently observed status of the Deployment. @@ -244,21 +253,27 @@ message Deployment { // DeploymentCondition describes the state of a deployment at a certain point. message DeploymentCondition { // Type of deployment condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // The last time this condition was updated. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastUpdateTime = 6; // Last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 7; // The reason for the condition's last transition. + // +optional optional string reason = 4; // A human readable message indicating details about the transition. + // +optional optional string message = 5; } @@ -282,10 +297,12 @@ message DeploymentSpec { // Label selector for pods. Existing ReplicaSets whose pods are // selected by this will be the ones affected by this deployment. // It must match the pod template's labels. + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // The deployment strategy to use to replace existing pods with new ones. @@ -314,6 +331,7 @@ message DeploymentSpec { // process failed deployments and a condition with a ProgressDeadlineExceeded // reason will be surfaced in the deployment status. Note that progress will // not be estimated during the time a deployment is paused. Defaults to 600s. + // +optional optional int32 progressDeadlineSeconds = 9; } @@ -384,6 +402,8 @@ message DeploymentStrategy { // DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1/ReplicaSet. See the release notes for // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message ReplicaSet { // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -393,7 +413,7 @@ message ReplicaSet { // Spec defines the specification of the desired behavior of the ReplicaSet. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional ReplicaSetSpec spec = 2; // Status is the most recently observed status of the ReplicaSet. @@ -408,9 +428,11 @@ message ReplicaSet { // ReplicaSetCondition describes the state of a replica set at a certain point. message ReplicaSetCondition { // Type of replica set condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // The last time the condition transitioned from one status to another. @@ -457,6 +479,7 @@ message ReplicaSetSpec { // Label keys and values that must match in order to be controlled by this replica set. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // Template is the object that describes the pod that will be created if @@ -601,6 +624,7 @@ message RollingUpdateStatefulSetStrategy { message Scale { // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -616,15 +640,16 @@ message Scale { message ScaleSpec { // desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 replicas = 1; } // ScaleStatus represents the current status of a scale subresource. message ScaleStatus { // actual number of observed instances of the scaled object. + // +optional optional int32 replicas = 1; // selector is a label query over pods that should match the replicas count. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ @@ -651,12 +676,14 @@ message ScaleStatus { // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" message StatefulSet { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines the desired identities of pods in this set. - // +optional + // +required optional StatefulSetSpec spec = 2; // Status is the current status of Pods in this StatefulSet. This data @@ -668,9 +695,11 @@ message StatefulSet { // StatefulSetCondition describes the state of a statefulset at a certain point. message StatefulSetCondition { // Type of statefulset condition. + // +optional optional string type = 1; // Status of the condition, one of True, False, Unknown. + // +optional optional string status = 2; // Last time the condition transitioned from one status to another. @@ -716,6 +745,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional optional string whenDeleted = 1; // WhenScaled specifies what happens to PVCs created from StatefulSet @@ -723,6 +753,7 @@ message StatefulSetPersistentVolumeClaimRetentionPolicy { // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional optional string whenScaled = 2; } @@ -739,6 +770,9 @@ message StatefulSetSpec { // selector is a label query over pods that should match the replica count. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; // template is the object that describes the pod that will be created if @@ -748,6 +782,7 @@ message StatefulSetSpec { // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". // The only allowed template.spec.restartPolicy value is "Always". + // +required optional .k8s.io.api.core.v1.PodTemplateSpec template = 3; // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -758,7 +793,10 @@ message StatefulSetSpec { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType repeated .k8s.io.api.core.v1.PersistentVolumeClaim volumeClaimTemplates = 4; // serviceName is the name of the service that governs this StatefulSet. @@ -767,6 +805,8 @@ message StatefulSetSpec { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string serviceName = 5; // podManagementPolicy controls how pods are created during initial scale up, @@ -778,17 +818,21 @@ message StatefulSetSpec { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional optional string podManagementPolicy = 6; // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional optional StatefulSetUpdateStrategy updateStrategy = 7; // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional optional int32 revisionHistoryLimit = 8; // Minimum number of seconds for which a newly created pod should be ready diff --git a/constraint/vendor/k8s.io/api/apps/v1beta2/types.go b/constraint/vendor/k8s.io/api/apps/v1beta2/types.go index d4d4a7e0d..138039f02 100644 --- a/constraint/vendor/k8s.io/api/apps/v1beta2/types.go +++ b/constraint/vendor/k8s.io/api/apps/v1beta2/types.go @@ -35,15 +35,16 @@ const ( type ScaleSpec struct { // desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } // ScaleStatus represents the current status of a scale subresource. type ScaleStatus struct { // actual number of observed instances of the scaled object. + // +optional Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // selector is a label query over pods that should match the replicas count. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ @@ -70,9 +71,10 @@ type ScaleStatus struct { // Scale represents a scaling request for a resource. type Scale struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -103,13 +105,15 @@ type Scale struct { // // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type StatefulSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired identities of pods in this set. - // +optional + // +required Spec StatefulSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current status of Pods in this StatefulSet. This data @@ -157,11 +161,12 @@ const ( // strategy, new Pods will be created from the specification version indicated // by the StatefulSet's updateRevision. RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate" - // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version - // tracking and ordered rolling restarts are disabled. Pods are recreated - // from the StatefulSetSpec when they are manually deleted. When a scale - // operation is performed with this strategy,specification version indicated - // by the StatefulSet's currentRevision. + // OnDeleteStatefulSetStrategyType disables ordered rolling restarts. Version + // tracking is done on a best-effort basis - the controller will try to + // eventually converge StatefulSet's currentRevision with updateRevision. + // Pods are recreated from the StatefulSetSpec when they are manually deleted. + // When a scale operation is performed with this strategy, new Pods will be + // created from the specification version indicated by the StatefulSet's updateRevision. OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete" ) @@ -211,12 +216,14 @@ type StatefulSetPersistentVolumeClaimRetentionPolicy struct { // VolumeClaimTemplates when the StatefulSet is deleted. The default policy // of `Retain` causes PVCs to not be affected by StatefulSet deletion. The // `Delete` policy causes those PVCs to be deleted. + // +optional WhenDeleted PersistentVolumeClaimRetentionPolicyType `json:"whenDeleted,omitempty" protobuf:"bytes,1,opt,name=whenDeleted,casttype=PersistentVolumeClaimRetentionPolicyType"` // WhenScaled specifies what happens to PVCs created from StatefulSet // VolumeClaimTemplates when the StatefulSet is scaled down. The default // policy of `Retain` causes PVCs to not be affected by a scaledown. The // `Delete` policy causes the associated PVCs for any excess pods above // the replica count to be deleted. + // +optional WhenScaled PersistentVolumeClaimRetentionPolicyType `json:"whenScaled,omitempty" protobuf:"bytes,2,opt,name=whenScaled,casttype=PersistentVolumeClaimRetentionPolicyType"` } @@ -248,6 +255,9 @@ type StatefulSetSpec struct { // selector is a label query over pods that should match the replica count. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:immutable Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // template is the object that describes the pod that will be created if @@ -257,6 +267,7 @@ type StatefulSetSpec struct { // -. For example, a pod in a StatefulSet named // "web" with index number "3" would be named "web-3". // The only allowed template.spec.restartPolicy value is "Always". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // volumeClaimTemplates is a list of claims that pods are allowed to reference. @@ -267,7 +278,10 @@ type StatefulSetSpec struct { // any volumes in the template, with the same name. // TODO: Define the behavior if a claim already exists with the same name. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType VolumeClaimTemplates []v1.PersistentVolumeClaim `json:"volumeClaimTemplates,omitempty" protobuf:"bytes,4,rep,name=volumeClaimTemplates"` // serviceName is the name of the service that governs this StatefulSet. @@ -276,6 +290,8 @@ type StatefulSetSpec struct { // pattern: pod-specific-string.serviceName.default.svc.cluster.local // where "pod-specific-string" is managed by the StatefulSet controller. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional ServiceName string `json:"serviceName" protobuf:"bytes,5,opt,name=serviceName"` // podManagementPolicy controls how pods are created during initial scale up, @@ -287,17 +303,21 @@ type StatefulSetSpec struct { // to match the desired scale without waiting, and on scale down will delete // all pods at once. // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable + // +k8s:alpha(since: "1.37")=+k8s:optional PodManagementPolicy PodManagementPolicyType `json:"podManagementPolicy,omitempty" protobuf:"bytes,6,opt,name=podManagementPolicy,casttype=PodManagementPolicyType"` // updateStrategy indicates the StatefulSetUpdateStrategy that will be // employed to update Pods in the StatefulSet when a revision is made to // Template. + // +optional UpdateStrategy StatefulSetUpdateStrategy `json:"updateStrategy,omitempty" protobuf:"bytes,7,opt,name=updateStrategy"` // revisionHistoryLimit is the maximum number of revisions that will // be maintained in the StatefulSet's revision history. The revision history // consists of all revisions not represented by a currently applied // StatefulSetSpec version. The default value is 10. + // +optional RevisionHistoryLimit *int32 `json:"revisionHistoryLimit,omitempty" protobuf:"varint,8,opt,name=revisionHistoryLimit"` // Minimum number of seconds for which a newly created pod should be ready @@ -375,8 +395,10 @@ type StatefulSetConditionType string // StatefulSetCondition describes the state of a statefulset at a certain point. type StatefulSetCondition struct { // Type of statefulset condition. + // +optional Type StatefulSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=StatefulSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // Last time the condition transitioned from one status to another. // +optional @@ -397,7 +419,7 @@ type StatefulSetCondition struct { // StatefulSetList is a collection of StatefulSets. type StatefulSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` Items []StatefulSet `json:"items" protobuf:"bytes,2,rep,name=items"` @@ -413,14 +435,16 @@ type StatefulSetList struct { // DEPRECATED - This group version of Deployment is deprecated by apps/v1/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type Deployment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the Deployment. - // +optional + // +required Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the Deployment. @@ -438,10 +462,12 @@ type DeploymentSpec struct { // Label selector for pods. Existing ReplicaSets whose pods are // selected by this will be the ones affected by this deployment. // It must match the pod template's labels. + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // Template describes the pods that will be created. // The only allowed template.spec.restartPolicy value is "Always". + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,3,opt,name=template"` // The deployment strategy to use to replace existing pods with new ones. @@ -470,6 +496,7 @@ type DeploymentSpec struct { // process failed deployments and a condition with a ProgressDeadlineExceeded // reason will be surfaced in the deployment status. Note that progress will // not be estimated during the time a deployment is paused. Defaults to 600s. + // +optional ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty" protobuf:"varint,9,opt,name=progressDeadlineSeconds"` } @@ -604,16 +631,22 @@ const ( // DeploymentCondition describes the state of a deployment at a certain point. type DeploymentCondition struct { // Type of deployment condition. + // +optional Type DeploymentConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DeploymentConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // The last time this condition was updated. + // +optional LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,6,opt,name=lastUpdateTime"` // Last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,7,opt,name=lastTransitionTime"` // The reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // A human readable message indicating details about the transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -625,7 +658,7 @@ type DeploymentCondition struct { // DeploymentList is a list of Deployments. type DeploymentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -706,6 +739,7 @@ type DaemonSetSpec struct { // Must match in order to be controlled. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,1,opt,name=selector"` // An object that describes the pod that will be created. @@ -714,6 +748,7 @@ type DaemonSetSpec struct { // selector is specified). // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template + // +required Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,2,opt,name=template"` // An update strategy to replace existing DaemonSet pods with new pods. @@ -797,8 +832,10 @@ type DaemonSetConditionType string // DaemonSetCondition describes the state of a DaemonSet at a certain point. type DaemonSetCondition struct { // Type of DaemonSet condition. + // +optional Type DaemonSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=DaemonSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // Last time the condition transitioned from one status to another. // +optional @@ -821,8 +858,9 @@ type DaemonSetCondition struct { // DEPRECATED - This group version of DaemonSet is deprecated by apps/v1/DaemonSet. See the release notes for // more information. // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" type DaemonSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -830,7 +868,7 @@ type DaemonSet struct { // The desired behavior of this daemon set. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec DaemonSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // The current status of this daemon set. This data may be @@ -857,7 +895,7 @@ const ( // DaemonSetList is a collection of daemon sets. type DaemonSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -877,8 +915,10 @@ type DaemonSetList struct { // DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1/ReplicaSet. See the release notes for // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" type ReplicaSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -888,7 +928,7 @@ type ReplicaSet struct { // Spec defines the specification of the desired behavior of the ReplicaSet. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec ReplicaSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the most recently observed status of the ReplicaSet. @@ -908,7 +948,7 @@ type ReplicaSet struct { // ReplicaSetList is a collection of ReplicaSets. type ReplicaSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -938,6 +978,7 @@ type ReplicaSetSpec struct { // Label keys and values that must match in order to be controlled by this replica set. // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +required Selector *metav1.LabelSelector `json:"selector" protobuf:"bytes,2,opt,name=selector"` // Template is the object that describes the pod that will be created if @@ -998,8 +1039,10 @@ const ( // ReplicaSetCondition describes the state of a replica set at a certain point. type ReplicaSetCondition struct { // Type of replica set condition. + // +optional Type ReplicaSetConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=ReplicaSetConditionType"` // Status of the condition, one of True, False, Unknown. + // +optional Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=k8s.io/api/core/v1.ConditionStatus"` // The last time the condition transitioned from one status to another. // +optional @@ -1031,16 +1074,18 @@ type ReplicaSetCondition struct { // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevision struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // 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" protobuf:"bytes,1,opt,name=metadata"` // Data is the serialized representation of the state. - Data runtime.RawExtension `json:"data,omitempty" protobuf:"bytes,2,opt,name=data"` + // +required + Data runtime.RawExtension `json:"data" protobuf:"bytes,2,opt,name=data"` // Revision indicates the revision of the state represented by Data. + // +optional Revision int64 `json:"revision" protobuf:"varint,3,opt,name=revision"` } @@ -1052,7 +1097,7 @@ type ControllerRevision struct { // ControllerRevisionList is a resource containing a list of ControllerRevision objects. type ControllerRevisionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/authentication/v1/generated.pb.go b/constraint/vendor/k8s.io/api/authentication/v1/generated.pb.go index 2b872c453..8547b769f 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/authentication/v1/generated.pb.go @@ -32,6 +32,8 @@ import ( k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" ) +func (m *AttestationValue) Reset() { *m = AttestationValue{} } + func (m *BoundObjectReference) Reset() { *m = BoundObjectReference{} } func (m *ExtraValue) Reset() { *m = ExtraValue{} } @@ -54,6 +56,38 @@ func (m *TokenReviewStatus) Reset() { *m = TokenReviewStatus{} } func (m *UserInfo) Reset() { *m = UserInfo{} } +func (m AttestationValue) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m AttestationValue) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m AttestationValue) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m) > 0 { + for iNdEx := len(m) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m[iNdEx]) + copy(dAtA[i:], m[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func (m *BoundObjectReference) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -278,6 +312,35 @@ func (m *TokenRequestSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.Attestations) > 0 { + keysForAttestations := make([]string, 0, len(m.Attestations)) + for k := range m.Attestations { + keysForAttestations = append(keysForAttestations, string(k)) + } + sort.Strings(keysForAttestations) + for iNdEx := len(keysForAttestations) - 1; iNdEx >= 0; iNdEx-- { + v := m.Attestations[string(keysForAttestations[iNdEx])] + baseI := i + { + size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(keysForAttestations[iNdEx]) + copy(dAtA[i:], keysForAttestations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForAttestations[iNdEx]))) + i-- + dAtA[i] = 0xa + i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) + i-- + dAtA[i] = 0x2a + } + } if m.ExpirationSeconds != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.ExpirationSeconds)) i-- @@ -572,6 +635,21 @@ func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } +func (m AttestationValue) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m) > 0 { + for _, s := range m { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *BoundObjectReference) Size() (n int) { if m == nil { return 0 @@ -662,6 +740,15 @@ func (m *TokenRequestSpec) Size() (n int) { if m.ExpirationSeconds != nil { n += 1 + sovGenerated(uint64(*m.ExpirationSeconds)) } + if len(m.Attestations) > 0 { + for k, v := range m.Attestations { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } return n } @@ -814,10 +901,21 @@ func (this *TokenRequestSpec) String() string { if this == nil { return "nil" } + keysForAttestations := make([]string, 0, len(this.Attestations)) + for k := range this.Attestations { + keysForAttestations = append(keysForAttestations, k) + } + sort.Strings(keysForAttestations) + mapStringForAttestations := "map[string]AttestationValue{" + for _, k := range keysForAttestations { + mapStringForAttestations += fmt.Sprintf("%v: %v,", k, this.Attestations[k]) + } + mapStringForAttestations += "}" s := strings.Join([]string{`&TokenRequestSpec{`, `Audiences:` + fmt.Sprintf("%v", this.Audiences) + `,`, `BoundObjectRef:` + strings.Replace(this.BoundObjectRef.String(), "BoundObjectReference", "BoundObjectReference", 1) + `,`, `ExpirationSeconds:` + valueToStringGenerated(this.ExpirationSeconds) + `,`, + `Attestations:` + mapStringForAttestations + `,`, `}`, }, "") return s @@ -900,6 +998,88 @@ func valueToStringGenerated(v interface{}) string { pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } +func (m *AttestationValue) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AttestationValue: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AttestationValue: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + *m = append(*m, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *BoundObjectReference) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1625,6 +1805,135 @@ func (m *TokenRequestSpec) Unmarshal(dAtA []byte) error { } } m.ExpirationSeconds = &v + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Attestations", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Attestations == nil { + m.Attestations = make(map[string]AttestationValue) + } + var mapkey string + mapvalue := &AttestationValue{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &AttestationValue{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.Attestations[mapkey] = *mapvalue + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/authentication/v1/generated.proto b/constraint/vendor/k8s.io/api/authentication/v1/generated.proto index 82ff7c3c5..c7b99158a 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/authentication/v1/generated.proto @@ -28,9 +28,19 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; // Package-wide variables from generator "generated". option go_package = "k8s.io/api/authentication/v1"; +// AttestationValue masks the value so protobuf can generate +// +protobuf.nullable=true +// +protobuf.options.(gogoproto.goproto_stringer)=false +message AttestationValue { + // items, if empty, will result in an empty slice + + repeated string items = 1; +} + // BoundObjectReference is a reference to an object that a token is bound to. message BoundObjectReference { - // kind of the referent. Valid kinds are 'Pod' and 'Secret'. + // kind of the referent. Valid kinds are 'Pod', 'Secret', 'Node', + // 'ValidatingWebhookConfiguration', and 'MutatingWebhookConfiguration'. // +optional optional string kind = 1; @@ -59,10 +69,12 @@ message ExtraValue { // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" message SelfSubjectReview { // metadata is standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // status is filled in by the server with the user attributes. @@ -82,6 +94,7 @@ message TokenRequest { // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated @@ -118,6 +131,14 @@ message TokenRequestSpec { // small if you want prompt revocation. // +optional optional BoundObjectReference boundObjectRef = 3; + + // attestations is a map of well-known keys to string-slice values. + // The values for each key have a specific semantic meaning, which is + // documented on the key definition. Requesters of tokens may ask + // the Kubernetes API Server to attest to certain claims. The API Server + // may perform authorization checks depending on the key of this map. + // +optional + map attestations = 5; } // TokenRequestStatus is the result of a token request. @@ -134,10 +155,12 @@ message TokenRequestStatus { // TokenReview attempts to authenticate a token to a known user. // Note: TokenReview requests may be cached by the webhook token authenticator // plugin in the kube-apiserver. +// +k8s:supportsSubresource="/status" message TokenReview { // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated diff --git a/constraint/vendor/k8s.io/api/authentication/v1/types.go b/constraint/vendor/k8s.io/api/authentication/v1/types.go index c28bded50..1eee2b504 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1/types.go +++ b/constraint/vendor/k8s.io/api/authentication/v1/types.go @@ -39,6 +39,33 @@ const ( // It can be repeated multiplied times for multiple map keys and the same key can be repeated multiple // times to have multiple elements in the slice under a single key ImpersonateUserExtraHeaderPrefix = "Impersonate-Extra-" + + // AttestationAdmissionReviewAPIGroups is the map key for the + // admissionReviewAPIGroups claim. It represents the APIGroup that a token + // authorizes its bearer to query admission webhooks about. The value + // corresponding to this key must be a slice of length 1, and the first and + // only element of this slice must match the APIGroup of the AdmissionReview + // request being made of the webhook. The empty string is invalid as the + // first and only element of the value slice. The special value "*" means + // "all api groups", and requires matching permissions (described below). + // + // For this claim to be considered valid, the TokenRequest must meet two + // conditions. First, the BoundObjectRef must be one of + // ValidatingWebhookConfiguration or MutatingWebhookConfiguration; the + // Webhook Configuration in question must have a Rule governing a resource + // under the APIGroup named in the value to this key. Second, the requested + // audience must match one of the following patterns: + // 1. When the webhook is configured with a URL, the audience must match + // the URL field exactly. + // 2. When the webhook is configured with a service, the audience must + // match the pattern `https://$name.$namespace.svc:$port[/$path]`, where + // `/$path` is optional. + // + // The service account for which the TokenRequest is being made must have + // "attest" permissions on group "authentication.k8s.io", resource + // "admissionReviewAPIGroups", and a resource name matching exactly either + // "*", or the API group named in the value to this key. + AttestationAdmissionReviewAPIGroups = "admissionReviewAPIGroups" ) // +genclient @@ -50,11 +77,13 @@ const ( // TokenReview attempts to authenticate a token to a known user. // Note: TokenReview requests may be cached by the webhook token authenticator // plugin in the kube-apiserver. +// +k8s:supportsSubresource="/status" type TokenReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated @@ -135,15 +164,25 @@ func (t ExtraValue) String() string { return fmt.Sprintf("%v", []string(t)) } +// AttestationValue masks the value so protobuf can generate +// +protobuf.nullable=true +// +protobuf.options.(gogoproto.goproto_stringer)=false +type AttestationValue []string + +func (a AttestationValue) String() string { + return fmt.Sprintf("%v", []string(a)) +} + // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.10 // TokenRequest requests a token for a given service account. type TokenRequest struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated @@ -180,6 +219,14 @@ type TokenRequestSpec struct { // small if you want prompt revocation. // +optional BoundObjectRef *BoundObjectReference `json:"boundObjectRef" protobuf:"bytes,3,opt,name=boundObjectRef"` + + // attestations is a map of well-known keys to string-slice values. + // The values for each key have a specific semantic meaning, which is + // documented on the key definition. Requesters of tokens may ask + // the Kubernetes API Server to attest to certain claims. The API Server + // may perform authorization checks depending on the key of this map. + // +optional + Attestations map[string]AttestationValue `json:"attestations,omitempty" protobuf:"bytes,5,rep,name=attestations"` } // TokenRequestStatus is the result of a token request. @@ -194,7 +241,8 @@ type TokenRequestStatus struct { // BoundObjectReference is a reference to an object that a token is bound to. type BoundObjectReference struct { - // kind of the referent. Valid kinds are 'Pod' and 'Secret'. + // kind of the referent. Valid kinds are 'Pod', 'Secret', 'Node', + // 'ValidatingWebhookConfiguration', and 'MutatingWebhookConfiguration'. // +optional Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"` // apiVersion is API version of the referent. @@ -218,11 +266,13 @@ type BoundObjectReference struct { // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" type SelfSubjectReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // status is filled in by the server with the user attributes. // +optional diff --git a/constraint/vendor/k8s.io/api/authentication/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/authentication/v1/types_swagger_doc_generated.go index ea3acbb68..eb50e7154 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/authentication/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_BoundObjectReference = map[string]string{ "": "BoundObjectReference is a reference to an object that a token is bound to.", - "kind": "kind of the referent. Valid kinds are 'Pod' and 'Secret'.", + "kind": "kind of the referent. Valid kinds are 'Pod', 'Secret', 'Node', 'ValidatingWebhookConfiguration', and 'MutatingWebhookConfiguration'.", "apiVersion": "apiVersion is API version of the referent.", "name": "name of the referent.", "uid": "uid of the referent.", @@ -74,6 +74,7 @@ var map_TokenRequestSpec = map[string]string{ "audiences": "audiences are the intendend audiences of the token. A recipient of a token must identify themself with an identifier in the list of audiences of the token, and otherwise should reject the token. A token issued for multiple audiences may be used to authenticate against any of the audiences listed but implies a high degree of trust between the target audiences.", "expirationSeconds": "expirationSeconds is the requested duration of validity of the request. The token issuer may return a token with a different validity duration so a client needs to check the 'expiration' field in a response.", "boundObjectRef": "boundObjectRef is a reference to an object that the token will be bound to. The token will only be valid for as long as the bound object exists. NOTE: The API server's TokenReview endpoint will validate the BoundObjectRef, but other audiences may not. Keep ExpirationSeconds small if you want prompt revocation.", + "attestations": "attestations is a map of well-known keys to string-slice values. The values for each key have a specific semantic meaning, which is documented on the key definition. Requesters of tokens may ask the Kubernetes API Server to attest to certain claims. The API Server may perform authorization checks depending on the key of this map.", } func (TokenRequestSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go index 369c89b86..6bc649268 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go @@ -25,6 +25,26 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in AttestationValue) DeepCopyInto(out *AttestationValue) { + { + in := &in + *out = make(AttestationValue, len(*in)) + copy(*out, *in) + return + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AttestationValue. +func (in AttestationValue) DeepCopy() AttestationValue { + if in == nil { + return nil + } + out := new(AttestationValue) + in.DeepCopyInto(out) + return *out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BoundObjectReference) DeepCopyInto(out *BoundObjectReference) { *out = *in @@ -151,6 +171,21 @@ func (in *TokenRequestSpec) DeepCopyInto(out *TokenRequestSpec) { *out = new(BoundObjectReference) **out = **in } + if in.Attestations != nil { + in, out := &in.Attestations, &out.Attestations + *out = make(map[string]AttestationValue, len(*in)) + for key, val := range *in { + var outVal []string + if val == nil { + (*out)[key] = nil + } else { + in, out := &val, &outVal + *out = make(AttestationValue, len(*in)) + copy(*out, *in) + } + (*out)[key] = outVal + } + } return } diff --git a/constraint/vendor/k8s.io/api/authentication/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/authentication/v1alpha1/generated.proto index 2bf836d73..cd806bb8a 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/authentication/v1alpha1/generated.proto @@ -32,10 +32,12 @@ option go_package = "k8s.io/api/authentication/v1alpha1"; // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" message SelfSubjectReview { // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // status is filled in by the server with the user attributes. diff --git a/constraint/vendor/k8s.io/api/authentication/v1alpha1/types.go b/constraint/vendor/k8s.io/api/authentication/v1alpha1/types.go index 7e02470c9..5a76a91a3 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/authentication/v1alpha1/types.go @@ -30,11 +30,13 @@ import ( // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" type SelfSubjectReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // status is filled in by the server with the user attributes. // +optional diff --git a/constraint/vendor/k8s.io/api/authentication/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/authentication/v1beta1/generated.proto index 999c65156..e5992bcaa 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/authentication/v1beta1/generated.proto @@ -41,10 +41,12 @@ message ExtraValue { // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" message SelfSubjectReview { // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // status is filled in by the server with the user attributes. @@ -62,10 +64,12 @@ message SelfSubjectReviewStatus { // TokenReview attempts to authenticate a token to a known user. // Note: TokenReview requests may be cached by the webhook token authenticator // plugin in the kube-apiserver. +// +k8s:supportsSubresource="/status" message TokenReview { // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated diff --git a/constraint/vendor/k8s.io/api/authentication/v1beta1/types.go b/constraint/vendor/k8s.io/api/authentication/v1beta1/types.go index 33dacdb72..8873d5d2a 100644 --- a/constraint/vendor/k8s.io/api/authentication/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/authentication/v1beta1/types.go @@ -34,11 +34,13 @@ import ( // TokenReview attempts to authenticate a token to a known user. // Note: TokenReview requests may be cached by the webhook token authenticator // plugin in the kube-apiserver. +// +k8s:supportsSubresource="/status" type TokenReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated @@ -128,11 +130,13 @@ func (t ExtraValue) String() string { // SelfSubjectReview contains the user information that the kube-apiserver has about the user making this request. // When using impersonation, users will receive the user info of the user being impersonated. If impersonation or // request header authentication is used, any extra keys will have their case ignored and returned as lowercase. +// +k8s:supportsSubresource="/status" type SelfSubjectReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // status is filled in by the server with the user attributes. // +optional diff --git a/constraint/vendor/k8s.io/api/authorization/v1/generated.proto b/constraint/vendor/k8s.io/api/authorization/v1/generated.proto index c47449f91..40753aa43 100644 --- a/constraint/vendor/k8s.io/api/authorization/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/authorization/v1/generated.proto @@ -94,10 +94,12 @@ message LabelSelectorAttributes { // LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. // Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions // checking. +// +k8s:supportsSubresource="/status" message LocalSubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. spec.namespace must be equal to the namespace @@ -203,10 +205,12 @@ message ResourceRule { // SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a // spec.namespace means "in all namespaces". Self is a special case, because users should always be able // to check whether they can perform an action +// +k8s:supportsSubresource="/status" message SelfSubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. user and groups must be empty @@ -222,10 +226,14 @@ message SelfSubjectAccessReview { message SelfSubjectAccessReviewSpec { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional ResourceAttributes resourceAttributes = 1; // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional NonResourceAttributes nonResourceAttributes = 2; } @@ -235,10 +243,12 @@ message SelfSubjectAccessReviewSpec { // or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to // drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. // SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. +// +k8s:supportsSubresource="/status" message SelfSubjectRulesReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. @@ -256,10 +266,12 @@ message SelfSubjectRulesReviewSpec { } // SubjectAccessReview checks whether or not a user or group can perform an action. +// +k8s:supportsSubresource="/status" message SubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated @@ -275,10 +287,14 @@ message SubjectAccessReview { message SubjectAccessReviewSpec { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional ResourceAttributes resourceAttributes = 1; // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional NonResourceAttributes nonResourceAttributes = 2; // user is the user you're testing for. diff --git a/constraint/vendor/k8s.io/api/authorization/v1/types.go b/constraint/vendor/k8s.io/api/authorization/v1/types.go index dcc9b0f85..eb9f808cf 100644 --- a/constraint/vendor/k8s.io/api/authorization/v1/types.go +++ b/constraint/vendor/k8s.io/api/authorization/v1/types.go @@ -29,11 +29,13 @@ import ( // +k8s:prerelease-lifecycle-gen:introduced=1.6 // SubjectAccessReview checks whether or not a user or group can perform an action. +// +k8s:supportsSubresource="/status" type SubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated @@ -53,11 +55,13 @@ type SubjectAccessReview struct { // SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a // spec.namespace means "in all namespaces". Self is a special case, because users should always be able // to check whether they can perform an action +// +k8s:supportsSubresource="/status" type SelfSubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. user and groups must be empty @@ -76,11 +80,13 @@ type SelfSubjectAccessReview struct { // LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. // Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions // checking. +// +k8s:supportsSubresource="/status" type LocalSubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. spec.namespace must be equal to the namespace @@ -195,9 +201,13 @@ type NonResourceAttributes struct { type SubjectAccessReviewSpec struct { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember ResourceAttributes *ResourceAttributes `json:"resourceAttributes,omitempty" protobuf:"bytes,1,opt,name=resourceAttributes"` // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember NonResourceAttributes *NonResourceAttributes `json:"nonResourceAttributes,omitempty" protobuf:"bytes,2,opt,name=nonResourceAttributes"` // user is the user you're testing for. @@ -231,9 +241,13 @@ func (t ExtraValue) String() string { type SelfSubjectAccessReviewSpec struct { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember ResourceAttributes *ResourceAttributes `json:"resourceAttributes,omitempty" protobuf:"bytes,1,opt,name=resourceAttributes"` // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember NonResourceAttributes *NonResourceAttributes `json:"nonResourceAttributes,omitempty" protobuf:"bytes,2,opt,name=nonResourceAttributes"` } @@ -269,11 +283,13 @@ type SubjectAccessReviewStatus struct { // or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to // drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. // SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. +// +k8s:supportsSubresource="/status" type SelfSubjectRulesReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. diff --git a/constraint/vendor/k8s.io/api/authorization/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/authorization/v1beta1/generated.proto index 8095ab4db..37618f077 100644 --- a/constraint/vendor/k8s.io/api/authorization/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/authorization/v1beta1/generated.proto @@ -41,10 +41,12 @@ message ExtraValue { // LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. // Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions // checking. +// +k8s:supportsSubresource="/status" message LocalSubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. spec.namespace must be equal to the namespace @@ -150,10 +152,12 @@ message ResourceRule { // SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a // spec.namespace means "in all namespaces". Self is a special case, because users should always be able // to check whether they can perform an action +// +k8s:supportsSubresource="/status" message SelfSubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. user and groups must be empty @@ -169,10 +173,14 @@ message SelfSubjectAccessReview { message SelfSubjectAccessReviewSpec { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional ResourceAttributes resourceAttributes = 1; // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional NonResourceAttributes nonResourceAttributes = 2; } @@ -182,10 +190,12 @@ message SelfSubjectAccessReviewSpec { // or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to // drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. // SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. +// +k8s:supportsSubresource="/status" message SelfSubjectRulesReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated. @@ -203,10 +213,12 @@ message SelfSubjectRulesReviewSpec { } // SubjectAccessReview checks whether or not a user or group can perform an action. +// +k8s:supportsSubresource="/status" message SubjectAccessReview { // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec holds information about the request being evaluated @@ -222,10 +234,14 @@ message SubjectAccessReview { message SubjectAccessReviewSpec { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional ResourceAttributes resourceAttributes = 1; // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember optional NonResourceAttributes nonResourceAttributes = 2; // user is the user you're testing for. diff --git a/constraint/vendor/k8s.io/api/authorization/v1beta1/types.go b/constraint/vendor/k8s.io/api/authorization/v1beta1/types.go index 204559fd2..7dc8409af 100644 --- a/constraint/vendor/k8s.io/api/authorization/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/authorization/v1beta1/types.go @@ -32,11 +32,13 @@ import ( // +k8s:prerelease-lifecycle-gen:replacement=authorization.k8s.io,v1,SubjectAccessReview // SubjectAccessReview checks whether or not a user or group can perform an action. +// +k8s:supportsSubresource="/status" type SubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated @@ -58,11 +60,13 @@ type SubjectAccessReview struct { // SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a // spec.namespace means "in all namespaces". Self is a special case, because users should always be able // to check whether they can perform an action +// +k8s:supportsSubresource="/status" type SelfSubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. user and groups must be empty @@ -83,11 +87,13 @@ type SelfSubjectAccessReview struct { // LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. // Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions // checking. +// +k8s:supportsSubresource="/status" type LocalSubjectAccessReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. spec.namespace must be equal to the namespace @@ -148,9 +154,13 @@ type NonResourceAttributes struct { type SubjectAccessReviewSpec struct { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember ResourceAttributes *ResourceAttributes `json:"resourceAttributes,omitempty" protobuf:"bytes,1,opt,name=resourceAttributes"` // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember NonResourceAttributes *NonResourceAttributes `json:"nonResourceAttributes,omitempty" protobuf:"bytes,2,opt,name=nonResourceAttributes"` // user is the user you're testing for. @@ -184,9 +194,13 @@ func (t ExtraValue) String() string { type SelfSubjectAccessReviewSpec struct { // resourceAttributes describes information for a resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember ResourceAttributes *ResourceAttributes `json:"resourceAttributes,omitempty" protobuf:"bytes,1,opt,name=resourceAttributes"` // nonResourceAttributes describes information for a non-resource access request // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:unionMember NonResourceAttributes *NonResourceAttributes `json:"nonResourceAttributes,omitempty" protobuf:"bytes,2,opt,name=nonResourceAttributes"` } @@ -224,11 +238,13 @@ type SubjectAccessReviewStatus struct { // or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to // drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. // SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. +// +k8s:supportsSubresource="/status" type SelfSubjectRulesReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec holds information about the request being evaluated. diff --git a/constraint/vendor/k8s.io/api/autoscaling/v1/generated.pb.go b/constraint/vendor/k8s.io/api/autoscaling/v1/generated.pb.go index 6028054ae..681c0c44c 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v1/generated.pb.go @@ -410,6 +410,11 @@ func (m *HorizontalPodAutoscalerCondition) MarshalToSizedBuffer(dAtA []byte) (in _ = i var l int _ = l + if m.ObservedGeneration != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.ObservedGeneration)) + i-- + dAtA[i] = 0x30 + } i -= len(m.Message) copy(dAtA[i:], m.Message) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) @@ -1344,6 +1349,9 @@ func (m *HorizontalPodAutoscalerCondition) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) l = len(m.Message) n += 1 + l + sovGenerated(uint64(l)) + if m.ObservedGeneration != nil { + n += 1 + sovGenerated(uint64(*m.ObservedGeneration)) + } return n } @@ -1708,6 +1716,7 @@ func (this *HorizontalPodAutoscalerCondition) String() string { `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, `}`, }, "") return s @@ -3101,6 +3110,26 @@ func (m *HorizontalPodAutoscalerCondition) Unmarshal(dAtA []byte) error { } m.Message = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ObservedGeneration = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/autoscaling/v1/generated.proto b/constraint/vendor/k8s.io/api/autoscaling/v1/generated.proto index 6ef1facb6..a20b92a79 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/autoscaling/v1/generated.proto @@ -88,9 +88,11 @@ message ContainerResourceMetricStatus { // +structType=atomic message CrossVersionObjectReference { // kind is the kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since: "1.37")=+k8s:required optional string kind = 1; // name is the name of the referent; More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + // +k8s:alpha(since: "1.37")=+k8s:required optional string name = 2; // apiVersion is the API version of the referent @@ -142,8 +144,9 @@ message ExternalMetricStatus { } // configuration of a horizontal pod autoscaler. +// +k8s:supportsSubresource="/status" message HorizontalPodAutoscaler { - // Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -178,6 +181,12 @@ message HorizontalPodAutoscalerCondition { // the transition // +optional optional string message = 5; + + // 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. + // +optional + optional int64 observedGeneration = 6; } // list of horizontal pod autoscaler objects. @@ -192,7 +201,7 @@ message HorizontalPodAutoscalerList { // specification of a horizontal pod autoscaler. message HorizontalPodAutoscalerSpec { - // reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption + // scaleTargetRef is the reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption // and will set the desired number of pods by using its Scale subresource. optional CrossVersionObjectReference scaleTargetRef = 1; @@ -202,15 +211,15 @@ message HorizontalPodAutoscalerSpec { // metric is configured. Scaling is active as long as at least one metric value is // available. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 - // +k8s:alpha(since: "1.36")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 optional int32 minReplicas = 2; // maxReplicas is the upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:minimum=1 optional int32 maxReplicas = 3; // targetCPUUtilizationPercentage is the target average CPU utilization (represented as a percentage of requested CPU) over all the pods; @@ -461,8 +470,9 @@ message ResourceMetricStatus { // Scale represents a scaling request for a resource. message Scale { - // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -478,9 +488,9 @@ message Scale { message ScaleSpec { // replicas is the desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 replicas = 1; } diff --git a/constraint/vendor/k8s.io/api/autoscaling/v1/types.go b/constraint/vendor/k8s.io/api/autoscaling/v1/types.go index 97222afc0..5554e6271 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v1/types.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v1/types.go @@ -26,9 +26,11 @@ import ( // +structType=atomic type CrossVersionObjectReference struct { // kind is the kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since: "1.37")=+k8s:required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` // name is the name of the referent; More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + // +k8s:alpha(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // apiVersion is the API version of the referent @@ -38,7 +40,7 @@ type CrossVersionObjectReference struct { // specification of a horizontal pod autoscaler. type HorizontalPodAutoscalerSpec struct { - // reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption + // scaleTargetRef is the reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption // and will set the desired number of pods by using its Scale subresource. ScaleTargetRef CrossVersionObjectReference `json:"scaleTargetRef" protobuf:"bytes,1,opt,name=scaleTargetRef"` // minReplicas is the lower limit for the number of replicas to which the autoscaler @@ -47,15 +49,15 @@ type HorizontalPodAutoscalerSpec struct { // metric is configured. Scaling is active as long as at least one metric value is // available. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 - // +k8s:alpha(since: "1.36")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 MinReplicas *int32 `json:"minReplicas,omitempty" protobuf:"varint,2,opt,name=minReplicas"` // maxReplicas is the upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:minimum=1 MaxReplicas int32 `json:"maxReplicas" protobuf:"varint,3,opt,name=maxReplicas"` // targetCPUUtilizationPercentage is the target average CPU utilization (represented as a percentage of requested CPU) over all the pods; @@ -92,9 +94,10 @@ type HorizontalPodAutoscalerStatus struct { // +k8s:prerelease-lifecycle-gen:introduced=1.2 // configuration of a horizontal pod autoscaler. +// +k8s:supportsSubresource="/status" type HorizontalPodAutoscaler struct { - metav1.TypeMeta `json:",inline"` - // Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -112,7 +115,7 @@ type HorizontalPodAutoscaler struct { // list of horizontal pod autoscaler objects. type HorizontalPodAutoscalerList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -127,9 +130,10 @@ type HorizontalPodAutoscalerList struct { // Scale represents a scaling request for a resource. type Scale struct { - metav1.TypeMeta `json:",inline"` - // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. @@ -145,9 +149,9 @@ type Scale struct { type ScaleSpec struct { // replicas is the desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } @@ -440,6 +444,12 @@ type HorizontalPodAutoscalerCondition struct { // the transition // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` + + // 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. + // +optional + ObservedGeneration *int64 `json:"observedGeneration,omitempty" protobuf:"varint,6,opt,name=observedGeneration"` } // ObjectMetricStatus indicates the current value of a metric describing a diff --git a/constraint/vendor/k8s.io/api/autoscaling/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/autoscaling/v1/types_swagger_doc_generated.go index ba43d06c1..4132f42d6 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v1/types_swagger_doc_generated.go @@ -88,7 +88,7 @@ func (ExternalMetricStatus) SwaggerDoc() map[string]string { var map_HorizontalPodAutoscaler = map[string]string{ "": "configuration of a horizontal pod autoscaler.", - "metadata": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec defines the behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.", "status": "status is the current information about the autoscaler.", } @@ -104,6 +104,7 @@ var map_HorizontalPodAutoscalerCondition = map[string]string{ "lastTransitionTime": "lastTransitionTime is the last time the condition transitioned from one status to another", "reason": "reason is the reason for the condition's last transition.", "message": "message is a human-readable explanation containing details about the transition", + "observedGeneration": "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.", } func (HorizontalPodAutoscalerCondition) SwaggerDoc() map[string]string { @@ -122,7 +123,7 @@ func (HorizontalPodAutoscalerList) SwaggerDoc() map[string]string { var map_HorizontalPodAutoscalerSpec = map[string]string{ "": "specification of a horizontal pod autoscaler.", - "scaleTargetRef": "reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption and will set the desired number of pods by using its Scale subresource.", + "scaleTargetRef": "scaleTargetRef is the reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption and will set the desired number of pods by using its Scale subresource.", "minReplicas": "minReplicas is the lower limit for the number of replicas to which the autoscaler can scale down. It defaults to 1 pod. minReplicas is allowed to be 0 if the alpha feature gate HPAScaleToZero is enabled and at least one Object or External metric is configured. Scaling is active as long as at least one metric value is available.", "maxReplicas": "maxReplicas is the upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas.", "targetCPUUtilizationPercentage": "targetCPUUtilizationPercentage is the target average CPU utilization (represented as a percentage of requested CPU) over all the pods; if not specified the default autoscaling policy will be used.", @@ -245,7 +246,7 @@ func (ResourceMetricStatus) SwaggerDoc() map[string]string { var map_Scale = map[string]string{ "": "Scale represents a scaling request for a resource.", - "metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.", + "metadata": "metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.", "spec": "spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.", "status": "status is the current status of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Read-only.", } diff --git a/constraint/vendor/k8s.io/api/autoscaling/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/autoscaling/v1/zz_generated.deepcopy.go index 603e6aa8c..e0ad1668c 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v1/zz_generated.deepcopy.go @@ -180,6 +180,11 @@ func (in *HorizontalPodAutoscaler) DeepCopyObject() runtime.Object { func (in *HorizontalPodAutoscalerCondition) DeepCopyInto(out *HorizontalPodAutoscalerCondition) { *out = *in in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } return } diff --git a/constraint/vendor/k8s.io/api/autoscaling/v2/generated.pb.go b/constraint/vendor/k8s.io/api/autoscaling/v2/generated.pb.go index 7505c7592..0f663d46e 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v2/generated.pb.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v2/generated.pb.go @@ -506,6 +506,11 @@ func (m *HorizontalPodAutoscalerCondition) MarshalToSizedBuffer(dAtA []byte) (in _ = i var l int _ = l + if m.ObservedGeneration != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.ObservedGeneration)) + i-- + dAtA[i] = 0x30 + } i -= len(m.Message) copy(dAtA[i:], m.Message) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) @@ -1489,6 +1494,9 @@ func (m *HorizontalPodAutoscalerCondition) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) l = len(m.Message) n += 1 + l + sovGenerated(uint64(l)) + if m.ObservedGeneration != nil { + n += 1 + sovGenerated(uint64(*m.ObservedGeneration)) + } return n } @@ -1892,6 +1900,7 @@ func (this *HorizontalPodAutoscalerCondition) String() string { `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, `}`, }, "") return s @@ -3524,6 +3533,26 @@ func (m *HorizontalPodAutoscalerCondition) Unmarshal(dAtA []byte) error { } m.Message = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ObservedGeneration = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/autoscaling/v2/generated.proto b/constraint/vendor/k8s.io/api/autoscaling/v2/generated.proto index f56b8c749..d9a31f941 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v2/generated.proto +++ b/constraint/vendor/k8s.io/api/autoscaling/v2/generated.proto @@ -67,9 +67,11 @@ message ContainerResourceMetricStatus { // CrossVersionObjectReference contains enough information to let you identify the referred resource. message CrossVersionObjectReference { // kind is the kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since: "1.37")=+k8s:required optional string kind = 1; // name is the name of the referent; More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + // +k8s:alpha(since: "1.37")=+k8s:required optional string name = 2; // apiVersion is the API version of the referent @@ -122,8 +124,7 @@ message HPAScalingPolicy { // window is chosen. // // The tolerance is applied to the metric values and prevents scaling too -// eagerly for small metric variations. (Note that setting a tolerance requires -// the beta HPAConfigurableTolerance feature gate to be enabled.) +// eagerly for small metric variations. message HPAScalingRules { // stabilizationWindowSeconds is the number of seconds for which past recommendations should be // considered while scaling up or scaling down. @@ -156,9 +157,6 @@ message HPAScalingRules { // and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be // triggered when the actual consumption falls below 95Mi or exceeds 101Mi. // - // This is an beta field and requires the HPAConfigurableTolerance feature - // gate to be enabled. - // // +featureGate=HPAConfigurableTolerance // +optional optional .k8s.io.apimachinery.pkg.api.resource.Quantity tolerance = 4; @@ -167,6 +165,7 @@ message HPAScalingRules { // HorizontalPodAutoscaler is the configuration for a horizontal pod // autoscaler, which automatically manages the replica count of any resource // implementing the scale subresource based on the metrics specified. +// +k8s:supportsSubresource="/status" message HorizontalPodAutoscaler { // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -224,6 +223,12 @@ message HorizontalPodAutoscalerCondition { // the transition // +optional optional string message = 5; + + // 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. + // +optional + optional int64 observedGeneration = 6; } // HorizontalPodAutoscalerList is a list of horizontal pod autoscaler objects. @@ -248,16 +253,16 @@ message HorizontalPodAutoscalerSpec { // metric is configured. Scaling is active as long as at least one metric value is // available. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 - // +k8s:alpha(since: "1.36")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 optional int32 minReplicas = 2; // maxReplicas is the upper limit for the number of replicas to which the autoscaler can scale up. // It cannot be less that minReplicas. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:minimum=1 optional int32 maxReplicas = 3; // metrics contains the specifications for which to use to calculate the @@ -270,6 +275,7 @@ message HorizontalPodAutoscalerSpec { // If not set, the default metric will be set to 80% average CPU utilization. // +listType=atomic // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional repeated MetricSpec metrics = 4; // behavior configures the scaling behavior of the target @@ -302,6 +308,7 @@ message HorizontalPodAutoscalerStatus { // currentMetrics is the last read state of the metrics used by this autoscaler. // +listType=atomic // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional repeated MetricStatus currentMetrics = 5; // conditions is the set of conditions required for this autoscaler to scale its target, @@ -336,6 +343,8 @@ message MetricSpec { // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:opaqueType optional ObjectMetricSource object = 2; // pods refers to a metric describing each pod in the current scale target @@ -378,6 +387,8 @@ message MetricStatus { // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:opaqueType optional ObjectMetricStatus object = 2; // pods refers to a metric describing each pod in the current scale target @@ -394,7 +405,7 @@ message MetricStatus { // +optional optional ResourceMetricStatus resource = 4; - // container resource refers to a resource metric (such as those specified in + // containerResource refers to a resource metric (such as those specified in // requests and limits) known to Kubernetes describing a single container in each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available @@ -444,7 +455,7 @@ message MetricValueStatus { // +optional optional .k8s.io.apimachinery.pkg.api.resource.Quantity averageValue = 2; - // currentAverageUtilization is the current value of the average of the + // averageUtilization is the current value of the average of the // resource metric across all relevant pods, represented as a percentage of // the requested value of the resource for the pods. // +optional @@ -473,7 +484,7 @@ message ObjectMetricStatus { // current contains the current value for the given metric optional MetricValueStatus current = 2; - // DescribedObject specifies the descriptions of a object,such as kind,name apiVersion + // describedObject specifies the descriptions of a object,such as kind,name apiVersion optional CrossVersionObjectReference describedObject = 3; } diff --git a/constraint/vendor/k8s.io/api/autoscaling/v2/types.go b/constraint/vendor/k8s.io/api/autoscaling/v2/types.go index ad10169a0..49c9e751c 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v2/types.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v2/types.go @@ -31,8 +31,9 @@ import ( // HorizontalPodAutoscaler is the configuration for a horizontal pod // autoscaler, which automatically manages the replica count of any resource // implementing the scale subresource based on the metrics specified. +// +k8s:supportsSubresource="/status" type HorizontalPodAutoscaler struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -59,16 +60,16 @@ type HorizontalPodAutoscalerSpec struct { // metric is configured. Scaling is active as long as at least one metric value is // available. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 - // +k8s:alpha(since: "1.36")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifEnabled(HPAScaleToZero)=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:ifDisabled(HPAScaleToZero)=+k8s:minimum=1 MinReplicas *int32 `json:"minReplicas,omitempty" protobuf:"varint,2,opt,name=minReplicas"` // maxReplicas is the upper limit for the number of replicas to which the autoscaler can scale up. // It cannot be less that minReplicas. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:minimum=1 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:minimum=1 MaxReplicas int32 `json:"maxReplicas" protobuf:"varint,3,opt,name=maxReplicas"` // metrics contains the specifications for which to use to calculate the @@ -81,6 +82,7 @@ type HorizontalPodAutoscalerSpec struct { // If not set, the default metric will be set to 80% average CPU utilization. // +listType=atomic // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional Metrics []MetricSpec `json:"metrics,omitempty" protobuf:"bytes,4,rep,name=metrics"` // behavior configures the scaling behavior of the target @@ -93,9 +95,11 @@ type HorizontalPodAutoscalerSpec struct { // CrossVersionObjectReference contains enough information to let you identify the referred resource. type CrossVersionObjectReference struct { // kind is the kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since: "1.37")=+k8s:required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` // name is the name of the referent; More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + // +k8s:alpha(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // apiVersion is the API version of the referent @@ -113,6 +117,8 @@ type MetricSpec struct { // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:opaqueType Object *ObjectMetricSource `json:"object,omitempty" protobuf:"bytes,2,opt,name=object"` // pods refers to a metric describing each pod in the current scale target @@ -187,8 +193,7 @@ const ( // window is chosen. // // The tolerance is applied to the metric values and prevents scaling too -// eagerly for small metric variations. (Note that setting a tolerance requires -// the beta HPAConfigurableTolerance feature gate to be enabled.) +// eagerly for small metric variations. type HPAScalingRules struct { // stabilizationWindowSeconds is the number of seconds for which past recommendations should be // considered while scaling up or scaling down. @@ -221,9 +226,6 @@ type HPAScalingRules struct { // and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be // triggered when the actual consumption falls below 95Mi or exceeds 101Mi. // - // This is an beta field and requires the HPAConfigurableTolerance feature - // gate to be enabled. - // // +featureGate=HPAConfigurableTolerance // +optional Tolerance *resource.Quantity `json:"tolerance,omitempty" protobuf:"bytes,4,opt,name=tolerance"` @@ -424,6 +426,7 @@ type HorizontalPodAutoscalerStatus struct { // currentMetrics is the last read state of the metrics used by this autoscaler. // +listType=atomic // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional CurrentMetrics []MetricStatus `json:"currentMetrics" protobuf:"bytes,5,rep,name=currentMetrics"` // conditions is the set of conditions required for this autoscaler to scale its target, @@ -476,6 +479,12 @@ type HorizontalPodAutoscalerCondition struct { // the transition // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` + + // 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. + // +optional + ObservedGeneration *int64 `json:"observedGeneration,omitempty" protobuf:"varint,6,opt,name=observedGeneration"` } // MetricStatus describes the last-read state of a single metric. @@ -487,6 +496,8 @@ type MetricStatus struct { // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:opaqueType Object *ObjectMetricStatus `json:"object,omitempty" protobuf:"bytes,2,opt,name=object"` // pods refers to a metric describing each pod in the current scale target @@ -503,7 +514,7 @@ type MetricStatus struct { // +optional Resource *ResourceMetricStatus `json:"resource,omitempty" protobuf:"bytes,4,opt,name=resource"` - // container resource refers to a resource metric (such as those specified in + // containerResource refers to a resource metric (such as those specified in // requests and limits) known to Kubernetes describing a single container in each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available @@ -529,7 +540,7 @@ type ObjectMetricStatus struct { // current contains the current value for the given metric Current MetricValueStatus `json:"current" protobuf:"bytes,2,name=current"` - // DescribedObject specifies the descriptions of a object,such as kind,name apiVersion + // describedObject specifies the descriptions of a object,such as kind,name apiVersion DescribedObject CrossVersionObjectReference `json:"describedObject" protobuf:"bytes,3,name=describedObject"` } @@ -593,7 +604,7 @@ type MetricValueStatus struct { // +optional AverageValue *resource.Quantity `json:"averageValue,omitempty" protobuf:"bytes,2,opt,name=averageValue"` - // currentAverageUtilization is the current value of the average of the + // averageUtilization is the current value of the average of the // resource metric across all relevant pods, represented as a percentage of // the requested value of the resource for the pods. // +optional @@ -605,7 +616,7 @@ type MetricValueStatus struct { // HorizontalPodAutoscalerList is a list of horizontal pod autoscaler objects. type HorizontalPodAutoscalerList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata is the standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/autoscaling/v2/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/autoscaling/v2/types_swagger_doc_generated.go index af3f3022d..de5a6b389 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v2/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v2/types_swagger_doc_generated.go @@ -92,11 +92,11 @@ func (HPAScalingPolicy) SwaggerDoc() map[string]string { } var map_HPAScalingRules = map[string]string{ - "": "HPAScalingRules configures the scaling behavior for one direction via scaling Policy Rules and a configurable metric tolerance.\n\nScaling Policy Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen.\n\nThe tolerance is applied to the metric values and prevents scaling too eagerly for small metric variations. (Note that setting a tolerance requires the beta HPAConfigurableTolerance feature gate to be enabled.)", + "": "HPAScalingRules configures the scaling behavior for one direction via scaling Policy Rules and a configurable metric tolerance.\n\nScaling Policy Rules are applied after calculating DesiredReplicas from metrics for the HPA. They can limit the scaling velocity by specifying scaling policies. They can prevent flapping by specifying the stabilization window, so that the number of replicas is not set instantly, instead, the safest value from the stabilization window is chosen.\n\nThe tolerance is applied to the metric values and prevents scaling too eagerly for small metric variations.", "stabilizationWindowSeconds": "stabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long).", "selectPolicy": "selectPolicy is used to specify which policy should be used. If not set, the default value Max is used.", "policies": "policies is a list of potential scaling polices which can be used during scaling. If not set, use the default values: - For scale up: allow doubling the number of pods, or an absolute change of 4 pods in a 15s window. - For scale down: allow all pods to be removed in a 15s window.", - "tolerance": "tolerance is the tolerance on the ratio between the current and desired metric value under which no updates are made to the desired number of replicas (e.g. 0.01 for 1%). Must be greater than or equal to zero. If not set, the default cluster-wide tolerance is applied (by default 10%).\n\nFor example, if autoscaling is configured with a memory consumption target of 100Mi, and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be triggered when the actual consumption falls below 95Mi or exceeds 101Mi.\n\nThis is an beta field and requires the HPAConfigurableTolerance feature gate to be enabled.", + "tolerance": "tolerance is the tolerance on the ratio between the current and desired metric value under which no updates are made to the desired number of replicas (e.g. 0.01 for 1%). Must be greater than or equal to zero. If not set, the default cluster-wide tolerance is applied (by default 10%).\n\nFor example, if autoscaling is configured with a memory consumption target of 100Mi, and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be triggered when the actual consumption falls below 95Mi or exceeds 101Mi.", } func (HPAScalingRules) SwaggerDoc() map[string]string { @@ -131,6 +131,7 @@ var map_HorizontalPodAutoscalerCondition = map[string]string{ "lastTransitionTime": "lastTransitionTime is the last time the condition transitioned from one status to another", "reason": "reason is the reason for the condition's last transition.", "message": "message is a human-readable explanation containing details about the transition", + "observedGeneration": "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.", } func (HorizontalPodAutoscalerCondition) SwaggerDoc() map[string]string { @@ -204,7 +205,7 @@ var map_MetricStatus = map[string]string{ "object": "object refers to a metric describing a single kubernetes object (for example, hits-per-second on an Ingress object).", "pods": "pods refers to a metric describing each pod in the current scale target (for example, transactions-processed-per-second). The values will be averaged together before being compared to the target value.", "resource": "resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source.", - "containerResource": "container resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing a single container in each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source.", + "containerResource": "containerResource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing a single container in each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source.", "external": "external refers to a global metric that is not associated with any Kubernetes object. It allows autoscaling based on information coming from components running outside of cluster (for example length of queue in cloud messaging service, or QPS from loadbalancer running outside of cluster).", } @@ -228,7 +229,7 @@ var map_MetricValueStatus = map[string]string{ "": "MetricValueStatus holds the current value for a metric", "value": "value is the current value of the metric (as a quantity).", "averageValue": "averageValue is the current value of the average of the metric across all relevant pods (as a quantity)", - "averageUtilization": "currentAverageUtilization is the current value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods.", + "averageUtilization": "averageUtilization is the current value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods.", } func (MetricValueStatus) SwaggerDoc() map[string]string { @@ -250,7 +251,7 @@ var map_ObjectMetricStatus = map[string]string{ "": "ObjectMetricStatus indicates the current value of a metric describing a kubernetes object (for example, hits-per-second on an Ingress object).", "metric": "metric identifies the target metric by name and selector", "current": "current contains the current value for the given metric", - "describedObject": "DescribedObject specifies the descriptions of a object,such as kind,name apiVersion", + "describedObject": "describedObject specifies the descriptions of a object,such as kind,name apiVersion", } func (ObjectMetricStatus) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/autoscaling/v2/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/autoscaling/v2/zz_generated.deepcopy.go index 5fbcf9f80..ace4fa2fd 100644 --- a/constraint/vendor/k8s.io/api/autoscaling/v2/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/autoscaling/v2/zz_generated.deepcopy.go @@ -222,6 +222,11 @@ func (in *HorizontalPodAutoscalerBehavior) DeepCopy() *HorizontalPodAutoscalerBe func (in *HorizontalPodAutoscalerCondition) DeepCopyInto(out *HorizontalPodAutoscalerCondition) { *out = *in in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } return } diff --git a/constraint/vendor/k8s.io/api/batch/v1/generated.pb.go b/constraint/vendor/k8s.io/api/batch/v1/generated.pb.go index 099350e73..7c086a41c 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/batch/v1/generated.pb.go @@ -26,6 +26,7 @@ import ( k8s_io_api_core_v1 "k8s.io/api/core/v1" v11 "k8s.io/api/core/v1" + v1alpha3 "k8s.io/api/scheduling/v1alpha3" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" math_bits "math/bits" @@ -49,6 +50,8 @@ func (m *JobCondition) Reset() { *m = JobCondition{} } func (m *JobList) Reset() { *m = JobList{} } +func (m *JobSchedulingConfiguration) Reset() { *m = JobSchedulingConfiguration{} } + func (m *JobSpec) Reset() { *m = JobSpec{} } func (m *JobStatus) Reset() { *m = JobStatus{} } @@ -472,6 +475,79 @@ func (m *JobList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *JobSchedulingConfiguration) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *JobSchedulingConfiguration) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *JobSchedulingConfiguration) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ResourceClaims) > 0 { + for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.SchedulingPolicy != nil { + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + func (m *JobSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -492,6 +568,20 @@ func (m *JobSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Scheduling != nil { + { + size, err := m.Scheduling.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x8a + } if m.SuccessPolicy != nil { { size, err := m.SuccessPolicy.MarshalToSizedBuffer(dAtA[:i]) @@ -1195,6 +1285,33 @@ func (m *JobList) Size() (n int) { return n } +func (m *JobSchedulingConfiguration) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SchedulingPolicy != nil { + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.ResourceClaims) > 0 { + for _, e := range m.ResourceClaims { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *JobSpec) Size() (n int) { if m == nil { return 0 @@ -1254,6 +1371,10 @@ func (m *JobSpec) Size() (n int) { l = m.SuccessPolicy.Size() n += 2 + l + sovGenerated(uint64(l)) } + if m.Scheduling != nil { + l = m.Scheduling.Size() + n += 2 + l + sovGenerated(uint64(l)) + } return n } @@ -1544,6 +1665,24 @@ func (this *JobList) String() string { }, "") return s } +func (this *JobSchedulingConfiguration) String() string { + if this == nil { + return "nil" + } + repeatedStringForResourceClaims := "[]WorkloadPodGroupResourceClaim{" + for _, f := range this.ResourceClaims { + repeatedStringForResourceClaims += fmt.Sprintf("%v", f) + "," + } + repeatedStringForResourceClaims += "}" + s := strings.Join([]string{`&JobSchedulingConfiguration{`, + `SchedulingPolicy:` + strings.Replace(fmt.Sprintf("%v", this.SchedulingPolicy), "WorkloadPodGroupSchedulingPolicy", "v1alpha3.WorkloadPodGroupSchedulingPolicy", 1) + `,`, + `SchedulingConstraints:` + strings.Replace(fmt.Sprintf("%v", this.SchedulingConstraints), "WorkloadPodGroupSchedulingConstraints", "v1alpha3.WorkloadPodGroupSchedulingConstraints", 1) + `,`, + `DisruptionMode:` + strings.Replace(fmt.Sprintf("%v", this.DisruptionMode), "WorkloadPodGroupDisruptionMode", "v1alpha3.WorkloadPodGroupDisruptionMode", 1) + `,`, + `ResourceClaims:` + repeatedStringForResourceClaims + `,`, + `}`, + }, "") + return s +} func (this *JobSpec) String() string { if this == nil { return "nil" @@ -1565,6 +1704,7 @@ func (this *JobSpec) String() string { `PodReplacementPolicy:` + valueToStringGenerated(this.PodReplacementPolicy) + `,`, `ManagedBy:` + valueToStringGenerated(this.ManagedBy) + `,`, `SuccessPolicy:` + strings.Replace(this.SuccessPolicy.String(), "SuccessPolicy", "SuccessPolicy", 1) + `,`, + `Scheduling:` + strings.Replace(this.Scheduling.String(), "JobSchedulingConfiguration", "JobSchedulingConfiguration", 1) + `,`, `}`, }, "") return s @@ -2898,6 +3038,198 @@ func (m *JobList) Unmarshal(dAtA []byte) error { } return nil } +func (m *JobSchedulingConfiguration) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: JobSchedulingConfiguration: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: JobSchedulingConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingPolicy == nil { + m.SchedulingPolicy = &v1alpha3.WorkloadPodGroupSchedulingPolicy{} + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &v1alpha3.WorkloadPodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &v1alpha3.WorkloadPodGroupDisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaims = append(m.ResourceClaims, v1alpha3.WorkloadPodGroupResourceClaim{}) + if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *JobSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3349,6 +3681,42 @@ func (m *JobSpec) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 17: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Scheduling", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Scheduling == nil { + m.Scheduling = &JobSchedulingConfiguration{} + } + if err := m.Scheduling.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/batch/v1/generated.proto b/constraint/vendor/k8s.io/api/batch/v1/generated.proto index 5c3501285..da24d6d93 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/batch/v1/generated.proto @@ -22,6 +22,7 @@ syntax = "proto2"; package k8s.io.api.batch.v1; import "k8s.io/api/core/v1/generated.proto"; +import "k8s.io/api/scheduling/v1alpha3/generated.proto"; import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; @@ -30,6 +31,7 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; option go_package = "k8s.io/api/batch/v1"; // CronJob represents the configuration of a single cron job. +// +k8s:supportsSubresource="/status" message CronJob { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -62,7 +64,7 @@ message CronJobList { message CronJobSpec { // The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string schedule = 1; // The time zone name for the given schedule, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. @@ -127,6 +129,7 @@ message CronJobStatus { } // Job represents the configuration of a single job. +// +k8s:supportsSubresource="/status" message Job { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -180,6 +183,62 @@ message JobList { repeated Job items = 2; } +// JobSchedulingConfiguration composes the reusable workload-aware +// scheduling building blocks. +message JobSchedulingConfiguration { + // SchedulingPolicy defines the scheduling policy for this Job. + // Exactly one of Basic or Gang must be set. + // This field is immutable after creation: the policy may not be added or + // removed. The policy variant (basic/gang) is frozen by hand-written + // validation; only schedulingPolicy.gang.minCount may be changed. + // + // +optional + // +k8s:optional + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional .k8s.io.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingPolicy schedulingPolicy = 1; + + // SchedulingConstraints defines scheduling constraints (e.g. topology) + // for the Job's pods. + // This field is immutable after creation. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional .k8s.io.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingConstraints schedulingConstraints = 2; + + // DisruptionMode defines the mode in which the Job's pods can be disrupted. + // One of Single, All. + // This field is immutable after creation: it may not be added or removed, + // and the selected mode may not be changed. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional .k8s.io.api.scheduling.v1alpha3.WorkloadPodGroupDisruptionMode disruptionMode = 3; + + // ResourceClaims defines which ResourceClaims may be shared among Pods in + // the Job. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // At most 4 claims may be set, matching the limit on the resulting PodGroup. + // This list is immutable after creation: entries may neither be added, + // removed, nor modified. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + repeated .k8s.io.api.scheduling.v1alpha3.WorkloadPodGroupResourceClaim resourceClaims = 4; +} + // JobSpec describes how the job execution will look like. message JobSpec { // Specifies the maximum desired number of pods the job should @@ -251,6 +310,8 @@ message JobSpec { // It can be null or up to completions. It is required and must be // less than or equal to 10^4 when is completions greater than 10^5. // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("backoffLimitPerIndex") optional int32 maxFailedIndexes = 13; // A label query over pods that should match the pod count. @@ -346,6 +407,23 @@ message JobSpec { // This field is immutable. // +optional optional string managedBy = 15; + + // scheduling defines the Workload-aware Scheduling configuration for this Job. + // When set, it specifies the scheduling policy (basic or gang), topology + // constraints, disruption mode, and shared resource claims. + // When omitted, the Job defaults to the basic scheduling policy, which behaves + // as standard pod-by-pod scheduling. + // This field is alpha-level and requires the WorkloadWithJob feature gate. + // This field is immutable, including whether it is set at all, only + // policy.gang.minCount may be changed after creation. + // + // +featureGate=WorkloadWithJob + // +optional + // +k8s:ifDisabled(WorkloadWithJob)=+k8s:forbidden + // +k8s:optional + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional JobSchedulingConfiguration scheduling = 17; } // JobStatus represents the current state of a Job. @@ -408,9 +486,6 @@ message JobStatus { // The number of pods which are terminating (in phase Pending or Running // and have a deletionTimestamp). - // - // This field is beta-level. The job controller populates the field when - // the feature gate JobPodReplacementPolicy is enabled (enabled by default). // +optional optional int32 terminating = 11; @@ -465,6 +540,7 @@ message JobTemplateSpec { // Standard object's metadata of the jobs created from this template. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the job. diff --git a/constraint/vendor/k8s.io/api/batch/v1/types.go b/constraint/vendor/k8s.io/api/batch/v1/types.go index d4894e2ef..8e35cb228 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/types.go +++ b/constraint/vendor/k8s.io/api/batch/v1/types.go @@ -18,6 +18,7 @@ package v1 import ( corev1 "k8s.io/api/core/v1" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" ) @@ -66,8 +67,9 @@ const ( // +k8s:prerelease-lifecycle-gen:introduced=1.2 // Job represents the configuration of a single job. +// +k8s:supportsSubresource="/status" type Job struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -89,7 +91,7 @@ type Job struct { // JobList is a collection of jobs. type JobList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -371,6 +373,8 @@ type JobSpec struct { // It can be null or up to completions. It is required and must be // less than or equal to 10^4 when is completions greater than 10^5. // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("backoffLimitPerIndex") MaxFailedIndexes *int32 `json:"maxFailedIndexes,omitempty" protobuf:"varint,13,opt,name=maxFailedIndexes"` // TODO enabled it when https://github.com/kubernetes/kubernetes/issues/28486 has been fixed @@ -471,6 +475,79 @@ type JobSpec struct { // This field is immutable. // +optional ManagedBy *string `json:"managedBy,omitempty" protobuf:"bytes,15,opt,name=managedBy"` + + // scheduling defines the Workload-aware Scheduling configuration for this Job. + // When set, it specifies the scheduling policy (basic or gang), topology + // constraints, disruption mode, and shared resource claims. + // When omitted, the Job defaults to the basic scheduling policy, which behaves + // as standard pod-by-pod scheduling. + // This field is alpha-level and requires the WorkloadWithJob feature gate. + // This field is immutable, including whether it is set at all, only + // policy.gang.minCount may be changed after creation. + // + // +featureGate=WorkloadWithJob + // +optional + // +k8s:ifDisabled(WorkloadWithJob)=+k8s:forbidden + // +k8s:optional + // +k8s:update=NoSet + // +k8s:update=NoUnset + Scheduling *JobSchedulingConfiguration `json:"scheduling,omitempty" protobuf:"bytes,17,opt,name=scheduling"` +} + +// JobSchedulingConfiguration composes the reusable workload-aware +// scheduling building blocks. +type JobSchedulingConfiguration struct { + // SchedulingPolicy defines the scheduling policy for this Job. + // Exactly one of Basic or Gang must be set. + // This field is immutable after creation: the policy may not be added or + // removed. The policy variant (basic/gang) is frozen by hand-written + // validation; only schedulingPolicy.gang.minCount may be changed. + // + // +optional + // +k8s:optional + // +k8s:update=NoSet + // +k8s:update=NoUnset + SchedulingPolicy *schedulingv1alpha3.WorkloadPodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,1,opt,name=schedulingPolicy"` + + // SchedulingConstraints defines scheduling constraints (e.g. topology) + // for the Job's pods. + // This field is immutable after creation. + // + // +optional + // +k8s:optional + // +k8s:immutable + SchedulingConstraints *schedulingv1alpha3.WorkloadPodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,2,opt,name=schedulingConstraints"` + + // DisruptionMode defines the mode in which the Job's pods can be disrupted. + // One of Single, All. + // This field is immutable after creation: it may not be added or removed, + // and the selected mode may not be changed. + // + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *schedulingv1alpha3.WorkloadPodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,3,opt,name=disruptionMode"` + + // ResourceClaims defines which ResourceClaims may be shared among Pods in + // the Job. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // At most 4 claims may be set, matching the limit on the resulting PodGroup. + // This list is immutable after creation: entries may neither be added, + // removed, nor modified. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + ResourceClaims []schedulingv1alpha3.WorkloadPodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,4,rep,name=resourceClaims"` } // JobStatus represents the current state of a Job. @@ -533,9 +610,6 @@ type JobStatus struct { // The number of pods which are terminating (in phase Pending or Running // and have a deletionTimestamp). - // - // This field is beta-level. The job controller populates the field when - // the feature gate JobPodReplacementPolicy is enabled (enabled by default). // +optional Terminating *int32 `json:"terminating,omitempty" protobuf:"varint,11,opt,name=terminating"` @@ -626,10 +700,8 @@ const ( // JobReasponDeadlineExceeded means job duration is past ActiveDeadline JobReasonDeadlineExceeded string = "DeadlineExceeded" // JobReasonMaxFailedIndexesExceeded indicates that an indexed of a job failed - // This const is used in beta-level feature: https://kep.k8s.io/3850. JobReasonMaxFailedIndexesExceeded string = "MaxFailedIndexesExceeded" // JobReasonFailedIndexes means Job has failed indexes. - // This const is used in beta-level feature: https://kep.k8s.io/3850. JobReasonFailedIndexes string = "FailedIndexes" // JobReasonSuccessPolicy reason indicates a SuccessCriteriaMet condition is added due to // a Job met successPolicy. @@ -664,6 +736,7 @@ type JobTemplateSpec struct { // Standard object's metadata of the jobs created from this template. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the job. @@ -677,8 +750,9 @@ type JobTemplateSpec struct { // +k8s:prerelease-lifecycle-gen:introduced=1.21 // CronJob represents the configuration of a single cron job. +// +k8s:supportsSubresource="/status" type CronJob struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -700,7 +774,7 @@ type CronJob struct { // CronJobList is a collection of cron jobs. type CronJobList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -716,7 +790,7 @@ type CronJobSpec struct { // The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Schedule string `json:"schedule" protobuf:"bytes,1,opt,name=schedule"` // The time zone name for the given schedule, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. diff --git a/constraint/vendor/k8s.io/api/batch/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/batch/v1/types_swagger_doc_generated.go index 267df4292..ddf64555a 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/batch/v1/types_swagger_doc_generated.go @@ -110,6 +110,18 @@ func (JobList) SwaggerDoc() map[string]string { return map_JobList } +var map_JobSchedulingConfiguration = map[string]string{ + "": "JobSchedulingConfiguration composes the reusable workload-aware scheduling building blocks.", + "schedulingPolicy": "SchedulingPolicy defines the scheduling policy for this Job. Exactly one of Basic or Gang must be set. This field is immutable after creation: the policy may not be added or removed. The policy variant (basic/gang) is frozen by hand-written validation; only schedulingPolicy.gang.minCount may be changed.", + "schedulingConstraints": "SchedulingConstraints defines scheduling constraints (e.g. topology) for the Job's pods. This field is immutable after creation.", + "disruptionMode": "DisruptionMode defines the mode in which the Job's pods can be disrupted. One of Single, All. This field is immutable after creation: it may not be added or removed, and the selected mode may not be changed.", + "resourceClaims": "ResourceClaims defines which ResourceClaims may be shared among Pods in the Job. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate. At most 4 claims may be set, matching the limit on the resulting PodGroup. This list is immutable after creation: entries may neither be added, removed, nor modified.", +} + +func (JobSchedulingConfiguration) SwaggerDoc() map[string]string { + return map_JobSchedulingConfiguration +} + var map_JobSpec = map[string]string{ "": "JobSpec describes how the job execution will look like.", "parallelism": "Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/", @@ -128,6 +140,7 @@ var map_JobSpec = map[string]string{ "suspend": "suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false.", "podReplacementPolicy": "podReplacementPolicy specifies when to create replacement Pods. Possible values are: - TerminatingOrFailed means that we recreate pods\n when they are terminating (has a metadata.deletionTimestamp) or failed.\n- Failed means to wait until a previously created Pod is fully terminated (has phase\n Failed or Succeeded) before creating a replacement Pod.\n\nWhen using podFailurePolicy, Failed is the the only allowed value. TerminatingOrFailed and Failed are allowed values when podFailurePolicy is not in use.", "managedBy": "ManagedBy field indicates the controller that manages a Job. The k8s Job controller reconciles jobs which don't have this field at all or the field value is the reserved string `kubernetes.io/job-controller`, but skips reconciling Jobs with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 63 characters. This field is immutable.", + "scheduling": "scheduling defines the Workload-aware Scheduling configuration for this Job. When set, it specifies the scheduling policy (basic or gang), topology constraints, disruption mode, and shared resource claims. When omitted, the Job defaults to the basic scheduling policy, which behaves as standard pod-by-pod scheduling. This field is alpha-level and requires the WorkloadWithJob feature gate. This field is immutable, including whether it is set at all, only policy.gang.minCount may be changed after creation.", } func (JobSpec) SwaggerDoc() map[string]string { @@ -142,7 +155,7 @@ var map_JobStatus = map[string]string{ "active": "The number of pending and running pods which are not terminating (without a deletionTimestamp). The value is zero for finished jobs.", "succeeded": "The number of pods which reached phase Succeeded. The value increases monotonically for a given spec. However, it may decrease in reaction to scale down of elastic indexed jobs.", "failed": "The number of pods which reached phase Failed. The value increases monotonically.", - "terminating": "The number of pods which are terminating (in phase Pending or Running and have a deletionTimestamp).\n\nThis field is beta-level. The job controller populates the field when the feature gate JobPodReplacementPolicy is enabled (enabled by default).", + "terminating": "The number of pods which are terminating (in phase Pending or Running and have a deletionTimestamp).", "completedIndexes": "completedIndexes holds the completed indexes when .spec.completionMode = \"Indexed\" in a text format. The indexes are represented as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the completed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\".", "failedIndexes": "FailedIndexes holds the failed indexes when spec.backoffLimitPerIndex is set. The indexes are represented in the text format analogous as for the `completedIndexes` field, ie. they are kept as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the failed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\". The set of failed indexes cannot overlap with the set of completed indexes.", "uncountedTerminatedPods": "uncountedTerminatedPods holds the UIDs of Pods that have terminated but the job controller hasn't yet accounted for in the status counters.\n\nThe job controller creates pods with a finalizer. When a pod terminates (succeeded or failed), the controller does three steps to account for it in the job status:\n\n1. Add the pod UID to the arrays in this field. 2. Remove the pod finalizer. 3. Remove the pod UID from the arrays while increasing the corresponding\n counter.\n\nOld jobs might not be tracked using this field, in which case the field remains null. The structure is empty for finished jobs.", diff --git a/constraint/vendor/k8s.io/api/batch/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/batch/v1/zz_generated.deepcopy.go index 88c58b3d1..50d47596f 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/batch/v1/zz_generated.deepcopy.go @@ -23,6 +23,7 @@ package v1 import ( corev1 "k8s.io/api/core/v1" + v1alpha3 "k8s.io/api/scheduling/v1alpha3" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" types "k8s.io/apimachinery/pkg/types" @@ -239,6 +240,44 @@ func (in *JobList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *JobSchedulingConfiguration) DeepCopyInto(out *JobSchedulingConfiguration) { + *out = *in + if in.SchedulingPolicy != nil { + in, out := &in.SchedulingPolicy, &out.SchedulingPolicy + *out = new(v1alpha3.WorkloadPodGroupSchedulingPolicy) + (*in).DeepCopyInto(*out) + } + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(v1alpha3.WorkloadPodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(v1alpha3.WorkloadPodGroupDisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.ResourceClaims != nil { + in, out := &in.ResourceClaims, &out.ResourceClaims + *out = make([]v1alpha3.WorkloadPodGroupResourceClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JobSchedulingConfiguration. +func (in *JobSchedulingConfiguration) DeepCopy() *JobSchedulingConfiguration { + if in == nil { + return nil + } + out := new(JobSchedulingConfiguration) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *JobSpec) DeepCopyInto(out *JobSpec) { *out = *in @@ -318,6 +357,11 @@ func (in *JobSpec) DeepCopyInto(out *JobSpec) { *out = new(string) **out = **in } + if in.Scheduling != nil { + in, out := &in.Scheduling, &out.Scheduling + *out = new(JobSchedulingConfiguration) + (*in).DeepCopyInto(*out) + } return } diff --git a/constraint/vendor/k8s.io/api/batch/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/batch/v1/zz_generated.model_name.go index c5b86f29c..d7305143a 100644 --- a/constraint/vendor/k8s.io/api/batch/v1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/batch/v1/zz_generated.model_name.go @@ -56,6 +56,11 @@ func (in JobList) OpenAPIModelName() string { return "io.k8s.api.batch.v1.JobList" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in JobSchedulingConfiguration) OpenAPIModelName() string { + return "io.k8s.api.batch.v1.JobSchedulingConfiguration" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in JobSpec) OpenAPIModelName() string { return "io.k8s.api.batch.v1.JobSpec" diff --git a/constraint/vendor/k8s.io/api/batch/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/batch/v1beta1/generated.proto index 47000470c..411d681d0 100644 --- a/constraint/vendor/k8s.io/api/batch/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/batch/v1beta1/generated.proto @@ -31,6 +31,7 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; option go_package = "k8s.io/api/batch/v1beta1"; // CronJob represents the configuration of a single cron job. +// +k8s:supportsSubresource="/status" message CronJob { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -63,7 +64,7 @@ message CronJobList { message CronJobSpec { // The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string schedule = 1; // The time zone name for the given schedule, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. @@ -134,6 +135,7 @@ message JobTemplateSpec { // Standard object's metadata of the jobs created from this template. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the job. diff --git a/constraint/vendor/k8s.io/api/batch/v1beta1/types.go b/constraint/vendor/k8s.io/api/batch/v1beta1/types.go index 9e1a1b470..dea910b82 100644 --- a/constraint/vendor/k8s.io/api/batch/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/batch/v1beta1/types.go @@ -27,6 +27,7 @@ type JobTemplateSpec struct { // Standard object's metadata of the jobs created from this template. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the job. @@ -43,8 +44,9 @@ type JobTemplateSpec struct { // +k8s:prerelease-lifecycle-gen:replacement=batch,v1,CronJob // CronJob represents the configuration of a single cron job. +// +k8s:supportsSubresource="/status" type CronJob struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -69,7 +71,7 @@ type CronJob struct { // CronJobList is a collection of cron jobs. type CronJobList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -85,7 +87,7 @@ type CronJobSpec struct { // The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Schedule string `json:"schedule" protobuf:"bytes,1,opt,name=schedule"` // The time zone name for the given schedule, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. diff --git a/constraint/vendor/k8s.io/api/certificates/v1/generated.pb.go b/constraint/vendor/k8s.io/api/certificates/v1/generated.pb.go index e47a42e62..5b103ff8d 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/generated.pb.go @@ -26,10 +26,13 @@ import ( "sort" k8s_io_api_core_v1 "k8s.io/api/core/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" math_bits "math/bits" reflect "reflect" strings "strings" + + k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" ) func (m *CertificateSigningRequest) Reset() { *m = CertificateSigningRequest{} } @@ -42,8 +45,22 @@ func (m *CertificateSigningRequestSpec) Reset() { *m = CertificateSigningRequest func (m *CertificateSigningRequestStatus) Reset() { *m = CertificateSigningRequestStatus{} } +func (m *ClusterTrustBundle) Reset() { *m = ClusterTrustBundle{} } + +func (m *ClusterTrustBundleList) Reset() { *m = ClusterTrustBundleList{} } + +func (m *ClusterTrustBundleSpec) Reset() { *m = ClusterTrustBundleSpec{} } + func (m *ExtraValue) Reset() { *m = ExtraValue{} } +func (m *PodCertificateRequest) Reset() { *m = PodCertificateRequest{} } + +func (m *PodCertificateRequestList) Reset() { *m = PodCertificateRequestList{} } + +func (m *PodCertificateRequestSpec) Reset() { *m = PodCertificateRequestSpec{} } + +func (m *PodCertificateRequestStatus) Reset() { *m = PodCertificateRequestStatus{} } + func (m *CertificateSigningRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -348,7 +365,7 @@ func (m *CertificateSigningRequestStatus) MarshalToSizedBuffer(dAtA []byte) (int return len(dAtA) - i, nil } -func (m ExtraValue) Marshal() (dAtA []byte, err error) { +func (m *ClusterTrustBundle) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -358,270 +375,2058 @@ func (m ExtraValue) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m ExtraValue) MarshalTo(dAtA []byte) (int, error) { +func (m *ClusterTrustBundle) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m ExtraValue) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ClusterTrustBundle) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m) > 0 { - for iNdEx := len(m) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m[iNdEx]) - copy(dAtA[i:], m[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m[iNdEx]))) - i-- - dAtA[i] = 0xa + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0xa return len(dAtA) - i, nil } -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ +func (m *ClusterTrustBundleList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *CertificateSigningRequest) Size() (n int) { - if m == nil { - return 0 - } + +func (m *ClusterTrustBundleList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ClusterTrustBundleList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.ObjectMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Spec.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Status.Size() - n += 1 + l + sovGenerated(uint64(l)) - return n + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *CertificateSigningRequestCondition) Size() (n int) { - if m == nil { - return 0 +func (m *ClusterTrustBundleSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *ClusterTrustBundleSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ClusterTrustBundleSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.Type) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Reason) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Message) - n += 1 + l + sovGenerated(uint64(l)) - l = m.LastUpdateTime.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.LastTransitionTime.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Status) - n += 1 + l + sovGenerated(uint64(l)) - return n + i -= len(m.TrustBundle) + copy(dAtA[i:], m.TrustBundle) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TrustBundle))) + i-- + dAtA[i] = 0x12 + i -= len(m.SignerName) + copy(dAtA[i:], m.SignerName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SignerName))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *CertificateSigningRequestList) Size() (n int) { - if m == nil { - return 0 +func (m ExtraValue) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m ExtraValue) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m ExtraValue) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.ListMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Items) > 0 { - for _, e := range m.Items { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + if len(m) > 0 { + for iNdEx := len(m) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m[iNdEx]) + copy(dAtA[i:], m[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m[iNdEx]))) + i-- + dAtA[i] = 0xa } } - return n + return len(dAtA) - i, nil } -func (m *CertificateSigningRequestSpec) Size() (n int) { - if m == nil { - return 0 +func (m *PodCertificateRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *PodCertificateRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodCertificateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if m.Request != nil { - l = len(m.Request) - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.Username) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.UID) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Groups) > 0 { - for _, s := range m.Groups { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - if len(m.Usages) > 0 { - for _, s := range m.Usages { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - if len(m.Extra) > 0 { - for k, v := range m.Extra { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - l = len(m.SignerName) - n += 1 + l + sovGenerated(uint64(l)) - if m.ExpirationSeconds != nil { - n += 1 + sovGenerated(uint64(*m.ExpirationSeconds)) - } - return n + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *CertificateSigningRequestStatus) Size() (n int) { - if m == nil { - return 0 +func (m *PodCertificateRequestList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *PodCertificateRequestList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodCertificateRequestList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if len(m.Conditions) > 0 { - for _, e := range m.Conditions { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 } } - if m.Certificate != nil { - l = len(m.Certificate) - n += 1 + l + sovGenerated(uint64(l)) + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - return n + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m ExtraValue) Size() (n int) { - if m == nil { - return 0 +func (m *PodCertificateRequestSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *PodCertificateRequestSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodCertificateRequestSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if len(m) > 0 { - for _, s := range m { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) + if m.StubPKCS10Request != nil { + i -= len(m.StubPKCS10Request) + copy(dAtA[i:], m.StubPKCS10Request) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.StubPKCS10Request))) + i-- + dAtA[i] = 0x62 + } + if len(m.UnverifiedUserAnnotations) > 0 { + keysForUnverifiedUserAnnotations := make([]string, 0, len(m.UnverifiedUserAnnotations)) + for k := range m.UnverifiedUserAnnotations { + keysForUnverifiedUserAnnotations = append(keysForUnverifiedUserAnnotations, string(k)) + } + sort.Strings(keysForUnverifiedUserAnnotations) + for iNdEx := len(keysForUnverifiedUserAnnotations) - 1; iNdEx >= 0; iNdEx-- { + v := m.UnverifiedUserAnnotations[string(keysForUnverifiedUserAnnotations[iNdEx])] + baseI := i + i -= len(v) + copy(dAtA[i:], v) + i = encodeVarintGenerated(dAtA, i, uint64(len(v))) + i-- + dAtA[i] = 0x12 + i -= len(keysForUnverifiedUserAnnotations[iNdEx]) + copy(dAtA[i:], keysForUnverifiedUserAnnotations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForUnverifiedUserAnnotations[iNdEx]))) + i-- + dAtA[i] = 0xa + i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) + i-- + dAtA[i] = 0x5a } } - return n + if m.MaxExpirationSeconds != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.MaxExpirationSeconds)) + i-- + dAtA[i] = 0x40 + } + i -= len(m.NodeUID) + copy(dAtA[i:], m.NodeUID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.NodeUID))) + i-- + dAtA[i] = 0x3a + i -= len(m.NodeName) + copy(dAtA[i:], m.NodeName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.NodeName))) + i-- + dAtA[i] = 0x32 + i -= len(m.ServiceAccountUID) + copy(dAtA[i:], m.ServiceAccountUID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.ServiceAccountUID))) + i-- + dAtA[i] = 0x2a + i -= len(m.ServiceAccountName) + copy(dAtA[i:], m.ServiceAccountName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.ServiceAccountName))) + i-- + dAtA[i] = 0x22 + i -= len(m.PodUID) + copy(dAtA[i:], m.PodUID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PodUID))) + i-- + dAtA[i] = 0x1a + i -= len(m.PodName) + copy(dAtA[i:], m.PodName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PodName))) + i-- + dAtA[i] = 0x12 + i -= len(m.SignerName) + copy(dAtA[i:], m.SignerName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SignerName))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func sovGenerated(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenerated(x uint64) (n int) { - return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *CertificateSigningRequest) String() string { - if this == nil { - return "nil" +func (m *PodCertificateRequestStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - s := strings.Join([]string{`&CertificateSigningRequest{`, - `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CertificateSigningRequestSpec", "CertificateSigningRequestSpec", 1), `&`, ``, 1) + `,`, - `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CertificateSigningRequestStatus", "CertificateSigningRequestStatus", 1), `&`, ``, 1) + `,`, - `}`, - }, "") - return s + return dAtA[:n], nil } -func (this *CertificateSigningRequestCondition) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CertificateSigningRequestCondition{`, - `Type:` + fmt.Sprintf("%v", this.Type) + `,`, - `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, - `Message:` + fmt.Sprintf("%v", this.Message) + `,`, - `LastUpdateTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastUpdateTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, - `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, - `Status:` + fmt.Sprintf("%v", this.Status) + `,`, - `}`, - }, "") - return s + +func (m *PodCertificateRequestStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (this *CertificateSigningRequestList) String() string { - if this == nil { - return "nil" + +func (m *PodCertificateRequestStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.NotAfter != nil { + { + size, err := m.NotAfter.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 } - repeatedStringForItems := "[]CertificateSigningRequest{" - for _, f := range this.Items { - repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "CertificateSigningRequest", "CertificateSigningRequest", 1), `&`, ``, 1) + "," + if m.BeginRefreshAt != nil { + { + size, err := m.BeginRefreshAt.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a } - repeatedStringForItems += "}" - s := strings.Join([]string{`&CertificateSigningRequestList{`, - `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, - `Items:` + repeatedStringForItems + `,`, - `}`, - }, "") - return s -} -func (this *CertificateSigningRequestSpec) String() string { - if this == nil { - return "nil" + if m.NotBefore != nil { + { + size, err := m.NotBefore.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 } - keysForExtra := make([]string, 0, len(this.Extra)) - for k := range this.Extra { - keysForExtra = append(keysForExtra, k) + i -= len(m.CertificateChain) + copy(dAtA[i:], m.CertificateChain) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.CertificateChain))) + i-- + dAtA[i] = 0x12 + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } } - sort.Strings(keysForExtra) - mapStringForExtra := "map[string]ExtraValue{" - for _, k := range keysForExtra { - mapStringForExtra += fmt.Sprintf("%v: %v,", k, this.Extra[k]) + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ } - mapStringForExtra += "}" - s := strings.Join([]string{`&CertificateSigningRequestSpec{`, - `Request:` + valueToStringGenerated(this.Request) + `,`, - `Username:` + fmt.Sprintf("%v", this.Username) + `,`, - `UID:` + fmt.Sprintf("%v", this.UID) + `,`, - `Groups:` + fmt.Sprintf("%v", this.Groups) + `,`, - `Usages:` + fmt.Sprintf("%v", this.Usages) + `,`, - `Extra:` + mapStringForExtra + `,`, - `SignerName:` + fmt.Sprintf("%v", this.SignerName) + `,`, - `ExpirationSeconds:` + valueToStringGenerated(this.ExpirationSeconds) + `,`, - `}`, - }, "") - return s + dAtA[offset] = uint8(v) + return base } -func (this *CertificateSigningRequestStatus) String() string { - if this == nil { - return "nil" +func (m *CertificateSigningRequest) Size() (n int) { + if m == nil { + return 0 } - repeatedStringForConditions := "[]CertificateSigningRequestCondition{" - for _, f := range this.Conditions { - repeatedStringForConditions += strings.Replace(strings.Replace(f.String(), "CertificateSigningRequestCondition", "CertificateSigningRequestCondition", 1), `&`, ``, 1) + "," + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *CertificateSigningRequestCondition) Size() (n int) { + if m == nil { + return 0 } - repeatedStringForConditions += "}" - s := strings.Join([]string{`&CertificateSigningRequestStatus{`, - `Conditions:` + repeatedStringForConditions + `,`, - `Certificate:` + valueToStringGenerated(this.Certificate) + `,`, - `}`, - }, "") - return s + var l int + _ = l + l = len(m.Type) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + l = m.LastUpdateTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.LastTransitionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Status) + n += 1 + l + sovGenerated(uint64(l)) + return n } -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" + +func (m *CertificateSigningRequestList) Size() (n int) { + if m == nil { + return 0 } - pv := reflect.Indirect(rv).Interface() + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CertificateSigningRequestSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Request != nil { + l = len(m.Request) + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.Username) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.UID) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Groups) > 0 { + for _, s := range m.Groups { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.Usages) > 0 { + for _, s := range m.Usages { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.Extra) > 0 { + for k, v := range m.Extra { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + l = len(m.SignerName) + n += 1 + l + sovGenerated(uint64(l)) + if m.ExpirationSeconds != nil { + n += 1 + sovGenerated(uint64(*m.ExpirationSeconds)) + } + return n +} + +func (m *CertificateSigningRequestStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.Certificate != nil { + l = len(m.Certificate) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *ClusterTrustBundle) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *ClusterTrustBundleList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *ClusterTrustBundleSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SignerName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.TrustBundle) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m ExtraValue) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m) > 0 { + for _, s := range m { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodCertificateRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *PodCertificateRequestList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodCertificateRequestSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SignerName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.PodName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.PodUID) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.ServiceAccountName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.ServiceAccountUID) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.NodeName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.NodeUID) + n += 1 + l + sovGenerated(uint64(l)) + if m.MaxExpirationSeconds != nil { + n += 1 + sovGenerated(uint64(*m.MaxExpirationSeconds)) + } + if len(m.UnverifiedUserAnnotations) > 0 { + for k, v := range m.UnverifiedUserAnnotations { + _ = k + _ = v + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + if m.StubPKCS10Request != nil { + l = len(m.StubPKCS10Request) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodCertificateRequestStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = len(m.CertificateChain) + n += 1 + l + sovGenerated(uint64(l)) + if m.NotBefore != nil { + l = m.NotBefore.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.BeginRefreshAt != nil { + l = m.BeginRefreshAt.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.NotAfter != nil { + l = m.NotAfter.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func sovGenerated(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *CertificateSigningRequest) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequest{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CertificateSigningRequestSpec", "CertificateSigningRequestSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CertificateSigningRequestStatus", "CertificateSigningRequestStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequestCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `LastUpdateTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastUpdateTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]CertificateSigningRequest{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "CertificateSigningRequest", "CertificateSigningRequest", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&CertificateSigningRequestList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestSpec) String() string { + if this == nil { + return "nil" + } + keysForExtra := make([]string, 0, len(this.Extra)) + for k := range this.Extra { + keysForExtra = append(keysForExtra, k) + } + sort.Strings(keysForExtra) + mapStringForExtra := "map[string]ExtraValue{" + for _, k := range keysForExtra { + mapStringForExtra += fmt.Sprintf("%v: %v,", k, this.Extra[k]) + } + mapStringForExtra += "}" + s := strings.Join([]string{`&CertificateSigningRequestSpec{`, + `Request:` + valueToStringGenerated(this.Request) + `,`, + `Username:` + fmt.Sprintf("%v", this.Username) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `Groups:` + fmt.Sprintf("%v", this.Groups) + `,`, + `Usages:` + fmt.Sprintf("%v", this.Usages) + `,`, + `Extra:` + mapStringForExtra + `,`, + `SignerName:` + fmt.Sprintf("%v", this.SignerName) + `,`, + `ExpirationSeconds:` + valueToStringGenerated(this.ExpirationSeconds) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]CertificateSigningRequestCondition{" + for _, f := range this.Conditions { + repeatedStringForConditions += strings.Replace(strings.Replace(f.String(), "CertificateSigningRequestCondition", "CertificateSigningRequestCondition", 1), `&`, ``, 1) + "," + } + repeatedStringForConditions += "}" + s := strings.Join([]string{`&CertificateSigningRequestStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `Certificate:` + valueToStringGenerated(this.Certificate) + `,`, + `}`, + }, "") + return s +} +func (this *ClusterTrustBundle) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterTrustBundle{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ClusterTrustBundleSpec", "ClusterTrustBundleSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ClusterTrustBundleList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]ClusterTrustBundle{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "ClusterTrustBundle", "ClusterTrustBundle", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&ClusterTrustBundleList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *ClusterTrustBundleSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterTrustBundleSpec{`, + `SignerName:` + fmt.Sprintf("%v", this.SignerName) + `,`, + `TrustBundle:` + fmt.Sprintf("%v", this.TrustBundle) + `,`, + `}`, + }, "") + return s +} +func (this *PodCertificateRequest) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodCertificateRequest{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodCertificateRequestSpec", "PodCertificateRequestSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodCertificateRequestStatus", "PodCertificateRequestStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodCertificateRequestList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]PodCertificateRequest{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PodCertificateRequest", "PodCertificateRequest", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&PodCertificateRequestList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *PodCertificateRequestSpec) String() string { + if this == nil { + return "nil" + } + keysForUnverifiedUserAnnotations := make([]string, 0, len(this.UnverifiedUserAnnotations)) + for k := range this.UnverifiedUserAnnotations { + keysForUnverifiedUserAnnotations = append(keysForUnverifiedUserAnnotations, k) + } + sort.Strings(keysForUnverifiedUserAnnotations) + mapStringForUnverifiedUserAnnotations := "map[string]string{" + for _, k := range keysForUnverifiedUserAnnotations { + mapStringForUnverifiedUserAnnotations += fmt.Sprintf("%v: %v,", k, this.UnverifiedUserAnnotations[k]) + } + mapStringForUnverifiedUserAnnotations += "}" + s := strings.Join([]string{`&PodCertificateRequestSpec{`, + `SignerName:` + fmt.Sprintf("%v", this.SignerName) + `,`, + `PodName:` + fmt.Sprintf("%v", this.PodName) + `,`, + `PodUID:` + fmt.Sprintf("%v", this.PodUID) + `,`, + `ServiceAccountName:` + fmt.Sprintf("%v", this.ServiceAccountName) + `,`, + `ServiceAccountUID:` + fmt.Sprintf("%v", this.ServiceAccountUID) + `,`, + `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, + `NodeUID:` + fmt.Sprintf("%v", this.NodeUID) + `,`, + `MaxExpirationSeconds:` + valueToStringGenerated(this.MaxExpirationSeconds) + `,`, + `UnverifiedUserAnnotations:` + mapStringForUnverifiedUserAnnotations + `,`, + `StubPKCS10Request:` + valueToStringGenerated(this.StubPKCS10Request) + `,`, + `}`, + }, "") + return s +} +func (this *PodCertificateRequestStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + s := strings.Join([]string{`&PodCertificateRequestStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `CertificateChain:` + fmt.Sprintf("%v", this.CertificateChain) + `,`, + `NotBefore:` + strings.Replace(fmt.Sprintf("%v", this.NotBefore), "Time", "v1.Time", 1) + `,`, + `BeginRefreshAt:` + strings.Replace(fmt.Sprintf("%v", this.BeginRefreshAt), "Time", "v1.Time", 1) + `,`, + `NotAfter:` + strings.Replace(fmt.Sprintf("%v", this.NotAfter), "Time", "v1.Time", 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } -func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { +func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestCondition: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestCondition: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Type = RequestConditionType(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Reason = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastUpdateTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastUpdateTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Status = k8s_io_api_core_v1.ConditionStatus(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, CertificateSigningRequest{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Request = append(m.Request[:0], dAtA[iNdEx:postIndex]...) + if m.Request == nil { + m.Request = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Username = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.UID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Groups", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Groups = append(m.Groups, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Usages", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Usages = append(m.Usages, KeyUsage(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Extra", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Extra == nil { + m.Extra = make(map[string]ExtraValue) + } + var mapkey string + mapvalue := &ExtraValue{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &ExtraValue{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.Extra[mapkey] = *mapvalue + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignerName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignerName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ExpirationSeconds", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ExpirationSeconds = &v + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, CertificateSigningRequestCondition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Certificate = append(m.Certificate[:0], dAtA[iNdEx:postIndex]...) + if m.Certificate == nil { + m.Certificate = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ClusterTrustBundle) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ClusterTrustBundle: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ClusterTrustBundle: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ClusterTrustBundleList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -644,15 +2449,15 @@ func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CertificateSigningRequest: wiretype end group for non-group") + return fmt.Errorf("proto: ClusterTrustBundleList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CertificateSigningRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ClusterTrustBundleList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -679,46 +2484,13 @@ func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -745,7 +2517,8 @@ func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Items = append(m.Items, ClusterTrustBundle{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -770,7 +2543,7 @@ func (m *CertificateSigningRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { +func (m *ClusterTrustBundleSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -793,15 +2566,15 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CertificateSigningRequestCondition: wiretype end group for non-group") + return fmt.Errorf("proto: ClusterTrustBundleSpec: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CertificateSigningRequestCondition: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ClusterTrustBundleSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SignerName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -829,11 +2602,11 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Type = RequestConditionType(dAtA[iNdEx:postIndex]) + m.SignerName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TrustBundle", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -861,11 +2634,61 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Reason = string(dAtA[iNdEx:postIndex]) + m.TrustBundle = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ExtraValue) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ExtraValue: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ExtraValue: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -893,11 +2716,61 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Message = string(dAtA[iNdEx:postIndex]) + *m = append(*m, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 4: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodCertificateRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodCertificateRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodCertificateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastUpdateTime", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -924,13 +2797,13 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.LastUpdateTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 5: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -957,15 +2830,15 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 6: + case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -975,23 +2848,24 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Status = k8s_io_api_core_v1.ConditionStatus(dAtA[iNdEx:postIndex]) + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -1014,7 +2888,7 @@ func (m *CertificateSigningRequestCondition) Unmarshal(dAtA []byte) error { } return nil } -func (m *CertificateSigningRequestList) Unmarshal(dAtA []byte) error { +func (m *PodCertificateRequestList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1037,10 +2911,10 @@ func (m *CertificateSigningRequestList) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CertificateSigningRequestList: wiretype end group for non-group") + return fmt.Errorf("proto: PodCertificateRequestList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CertificateSigningRequestList: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PodCertificateRequestList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1105,7 +2979,7 @@ func (m *CertificateSigningRequestList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, CertificateSigningRequest{}) + m.Items = append(m.Items, PodCertificateRequest{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } @@ -1131,7 +3005,7 @@ func (m *CertificateSigningRequestList) Unmarshal(dAtA []byte) error { } return nil } -func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { +func (m *PodCertificateRequestSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1141,30 +3015,94 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if shift >= 64 { return ErrIntOverflowGenerated } - if iNdEx >= l { - return io.ErrUnexpectedEOF + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodCertificateRequestSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodCertificateRequestSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignerName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignerName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + if postIndex > l { + return io.ErrUnexpectedEOF } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CertificateSigningRequestSpec: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CertificateSigningRequestSpec: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + m.PodName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PodUID", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -1174,29 +3112,27 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Request = append(m.Request[:0], dAtA[iNdEx:postIndex]...) - if m.Request == nil { - m.Request = []byte{} - } + m.PodUID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ServiceAccountName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1224,11 +3160,11 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Username = string(dAtA[iNdEx:postIndex]) + m.ServiceAccountName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ServiceAccountUID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1256,11 +3192,11 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.UID = string(dAtA[iNdEx:postIndex]) + m.ServiceAccountUID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Groups", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1288,11 +3224,11 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Groups = append(m.Groups, string(dAtA[iNdEx:postIndex])) + m.NodeName = k8s_io_apimachinery_pkg_types.NodeName(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: + case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Usages", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeUID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1320,11 +3256,31 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Usages = append(m.Usages, KeyUsage(dAtA[iNdEx:postIndex])) + m.NodeUID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 6: + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxExpirationSeconds", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.MaxExpirationSeconds = &v + case 11: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Extra", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UnverifiedUserAnnotations", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -1351,11 +3307,11 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Extra == nil { - m.Extra = make(map[string]ExtraValue) + if m.UnverifiedUserAnnotations == nil { + m.UnverifiedUserAnnotations = make(map[string]string) } var mapkey string - mapvalue := &ExtraValue{} + var mapvalue string for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 @@ -1404,7 +3360,7 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { - var mapmsglen int + var stringLenmapvalue uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -1414,26 +3370,24 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - mapmsglen |= int(b&0x7F) << shift + stringLenmapvalue |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if mapmsglen < 0 { + intStringLenmapvalue := int(stringLenmapvalue) + if intStringLenmapvalue < 0 { return ErrInvalidLengthGenerated } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { + postStringIndexmapvalue := iNdEx + intStringLenmapvalue + if postStringIndexmapvalue < 0 { return ErrInvalidLengthGenerated } - if postmsgIndex > l { + if postStringIndexmapvalue > l { return io.ErrUnexpectedEOF } - mapvalue = &ExtraValue{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex + mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue]) + iNdEx = postStringIndexmapvalue } else { iNdEx = entryPreIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -1449,13 +3403,13 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { iNdEx += skippy } } - m.Extra[mapkey] = *mapvalue + m.UnverifiedUserAnnotations[mapkey] = mapvalue iNdEx = postIndex - case 7: + case 12: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SignerName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StubPKCS10Request", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -1465,44 +3419,26 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.SignerName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpirationSeconds", wireType) - } - var v int32 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int32(b&0x7F) << shift - if b < 0x80 { - break - } + m.StubPKCS10Request = append(m.StubPKCS10Request[:0], dAtA[iNdEx:postIndex]...) + if m.StubPKCS10Request == nil { + m.StubPKCS10Request = []byte{} } - m.ExpirationSeconds = &v + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -1524,7 +3460,7 @@ func (m *CertificateSigningRequestSpec) Unmarshal(dAtA []byte) error { } return nil } -func (m *CertificateSigningRequestStatus) Unmarshal(dAtA []byte) error { +func (m *PodCertificateRequestStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1547,10 +3483,10 @@ func (m *CertificateSigningRequestStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CertificateSigningRequestStatus: wiretype end group for non-group") + return fmt.Errorf("proto: PodCertificateRequestStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CertificateSigningRequestStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PodCertificateRequestStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1582,16 +3518,16 @@ func (m *CertificateSigningRequestStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Conditions = append(m.Conditions, CertificateSigningRequestCondition{}) + m.Conditions = append(m.Conditions, v1.Condition{}) if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CertificateChain", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -1601,81 +3537,101 @@ func (m *CertificateSigningRequestStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Certificate = append(m.Certificate[:0], dAtA[iNdEx:postIndex]...) - if m.Certificate == nil { - m.Certificate = []byte{} - } + m.CertificateChain = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NotBefore", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { return ErrInvalidLengthGenerated } - if (iNdEx + skippy) > l { + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ExtraValue) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated + if m.NotBefore == nil { + m.NotBefore = &v1.Time{} } - if iNdEx >= l { + if err := m.NotBefore.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BeginRefreshAt", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + if m.BeginRefreshAt == nil { + m.BeginRefreshAt = &v1.Time{} } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ExtraValue: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ExtraValue: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + if err := m.BeginRefreshAt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NotAfter", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -1685,23 +3641,27 @@ func (m *ExtraValue) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - *m = append(*m, string(dAtA[iNdEx:postIndex])) + if m.NotAfter == nil { + m.NotAfter = &v1.Time{} + } + if err := m.NotAfter.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex diff --git a/constraint/vendor/k8s.io/api/certificates/v1/generated.proto b/constraint/vendor/k8s.io/api/certificates/v1/generated.proto index a334db4e1..8c97f1239 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/certificates/v1/generated.proto @@ -204,12 +204,12 @@ message CertificateSigningRequestStatus { // +listType=map // +listMapKey=type // +optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=type - // +k8s:alpha(since: "1.36")=+k8s:customUnique - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=type + // +k8s:beta(since: "1.37")=+k8s:customUnique + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember repeated CertificateSigningRequestCondition conditions = 1; // certificate is populated with an issued certificate by the signer after an Approved condition is present. @@ -243,6 +243,81 @@ message CertificateSigningRequestStatus { optional bytes certificate = 2; } +// ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors +// (root certificates). +// +// ClusterTrustBundle objects are considered to be readable by any authenticated +// user in the cluster, because they can be mounted by pods using the +// `clusterTrustBundle` projection. All service accounts have read access to +// ClusterTrustBundles by default. Users who only have namespace-level access +// to a cluster can read ClusterTrustBundles by impersonating a serviceaccount +// that they have access to. +// +// It can be optionally associated with a particular signer, in which case it +// contains one valid set of trust anchors for that signer. Signers may have +// multiple associated ClusterTrustBundles; each is an independent set of trust +// anchors for that signer. Admission control is used to enforce that only users +// with permissions on the signer can create or modify the corresponding bundle. +message ClusterTrustBundle { + // metadata contains the object metadata. + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec contains the signer (if any) and trust anchors. + optional ClusterTrustBundleSpec spec = 2; +} + +// ClusterTrustBundleList is a collection of ClusterTrustBundle objects +message ClusterTrustBundleList { + // metadata contains the list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // items is a collection of ClusterTrustBundle objects + repeated ClusterTrustBundle items = 2; +} + +// ClusterTrustBundleSpec contains the signer and trust anchors. +message ClusterTrustBundleSpec { + // signerName indicates the associated signer, if any. + // + // In order to create or update a ClusterTrustBundle that sets signerName, + // you must have the following cluster-scoped permission: + // group=certificates.k8s.io resource=signers resourceName= + // verb=attest. + // + // If signerName is not empty, then the ClusterTrustBundle object must be + // named with the signer name as a prefix (translating slashes to colons). + // For example, for the signer name `example.com/foo`, valid + // ClusterTrustBundle object names include `example.com:foo:abc` and + // `example.com:foo:v1`. + // + // If signerName is empty, then the ClusterTrustBundle object's name must + // not have such a prefix. + // + // List/watch requests for ClusterTrustBundles can filter on this field + // using a `spec.signerName=NAME` field selector. + // + // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable + optional string signerName = 1; + + // trustBundle contains the individual X.509 trust anchors for this + // bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates. + // + // The data must consist only of PEM certificate blocks that parse as valid + // X.509 certificates. Each certificate must include a basic constraints + // extension with the CA bit set. The API server will reject objects that + // contain duplicate certificates, or that use PEM block headers. + // + // Users of ClusterTrustBundles, including Kubelet, are free to reorder and + // deduplicate certificate blocks in this file according to their own logic, + // as well as to drop PEM block headers and inter-block data. + optional string trustBundle = 2; +} + // ExtraValue masks the value so protobuf can generate // +protobuf.nullable=true // +protobuf.options.(gogoproto.goproto_stringer)=false @@ -252,3 +327,209 @@ message ExtraValue { repeated string items = 1; } +// PodCertificateRequest encodes a pod requesting a certificate from a given +// signer. +// +// Kubelets use this API to implement podCertificate projected volumes +// +k8s:supportsSubresource="/status" +message PodCertificateRequest { + // metadata contains the object metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec contains the details about the certificate being requested. + // +required + optional PodCertificateRequestSpec spec = 2; + + // status contains the issued certificate, and a standard set of conditions. + // +optional + optional PodCertificateRequestStatus status = 3; +} + +// PodCertificateRequestList is a collection of PodCertificateRequest objects +message PodCertificateRequestList { + // metadata contains the list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // items is a collection of PodCertificateRequest objects + repeated PodCertificateRequest items = 2; +} + +// PodCertificateRequestSpec describes the certificate request. All fields are +// immutable after creation. +message PodCertificateRequestSpec { + // signerName indicates the requested signer. + // + // All signer names beginning with `kubernetes.io` are reserved for use by + // the Kubernetes project. There is currently one well-known signer + // documented by the Kubernetes project, + // `kubernetes.io/kube-apiserver-client-pod`, which will issue client + // certificates understood by kube-apiserver. It is currently + // unimplemented. + // + // +required + optional string signerName = 1; + + // podName is the name of the pod into which the certificate will be mounted. + // + // +required + optional string podName = 2; + + // podUID is the UID of the pod into which the certificate will be mounted. + // + // +required + optional string podUID = 3; + + // serviceAccountName is the name of the service account the pod is running as. + // + // +required + optional string serviceAccountName = 4; + + // serviceAccountUID is the UID of the service account the pod is running as. + // + // +required + optional string serviceAccountUID = 5; + + // nodeName is the name of the node the pod is assigned to. + // + // +required + optional string nodeName = 6; + + // nodeUID is the UID of the node the pod is assigned to. + // + // +required + optional string nodeUID = 7; + + // maxExpirationSeconds is the maximum lifetime permitted for the + // certificate. + // + // If omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver + // will reject values shorter than 3600 (1 hour). The maximum allowable + // value is 7862400 (91 days). + // + // The signer implementation is then free to issue a certificate with any + // lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 + // seconds (1 hour). This constraint is enforced by kube-apiserver. + // `kubernetes.io` signers will never issue certificates with a lifetime + // longer than 24 hours. + // + // +optional + // +default=86400 + optional int32 maxExpirationSeconds = 8; + + // A PKCS#10 certificate signing request (DER-serialized) generated by + // Kubelet using the subject private key. + // + // Most signer implementations will ignore the contents of the CSR except to + // extract the subject public key. The API server automatically verifies the + // CSR signature during admission, so the signer does not need to repeat the + // verification. CSRs generated by kubelet are completely empty. + // + // The subject public key must be one of RSA3072, RSA4096, ECDSAP256, + // ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in + // the future. + // + // Signer implementations do not need to support all key types supported by + // kube-apiserver and kubelet. If a signer does not support the key type + // used for a given PodCertificateRequest, it must deny the request by + // setting a status.conditions entry with a type of "Denied" and a reason of + // "UnsupportedKeyType". It may also suggest a key type that it does support + // in the message field. + // + // +required + optional bytes stubPKCS10Request = 12; + + // unverifiedUserAnnotations allow pod authors to pass additional information to + // the signer implementation. Kubernetes does not restrict or validate this + // metadata in any way. + // + // Entries are subject to the same validation as object metadata annotations, + // with the addition that all keys must be domain-prefixed. No restrictions + // are placed on values, except an overall size limitation on the entire field. + // + // Signers should document the keys and values they support. Signers should + // deny requests that contain keys they do not recognize. + // + // +optional + map unverifiedUserAnnotations = 11; +} + +// PodCertificateRequestStatus describes the status of the request, and holds +// the certificate data if the request is issued. +message PodCertificateRequestStatus { + // conditions applied to the request. + // + // The types "Issued", "Denied", and "Failed" have special handling. At + // most one of these conditions may be present, and they must have status + // "True". + // + // If the request is denied with `Reason=UnsupportedKeyType`, the signer may + // suggest a key type that will work in the message field. + // + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // certificateChain is populated with an issued certificate by the signer. + // This field is set via the /status subresource. Once populated, this field + // is immutable. + // + // If the certificate signing request is denied, a condition of type + // "Denied" is added and this field remains empty. If the signer cannot + // issue the certificate, a condition of type "Failed" is added and this + // field remains empty. + // + // Validation requirements: + // 1. certificateChain must consist of one or more PEM-formatted certificates. + // 2. Each entry must be a valid PEM-wrapped, DER-encoded ASN.1 Certificate as + // described in section 4 of RFC5280. + // + // If more than one block is present, and the definition of the requested + // spec.signerName does not indicate otherwise, the first block is the + // issued certificate, and subsequent blocks should be treated as + // intermediate certificates and presented in TLS handshakes. When + // projecting the chain into a pod volume, kubelet will drop any data + // in-between the PEM blocks, as well as any PEM block headers. + // + // +optional + optional string certificateChain = 2; + + // notBefore is the time at which the certificate becomes valid. The value + // must be the same as the notBefore value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time notBefore = 4; + + // beginRefreshAt is the time at which the kubelet should begin trying to + // refresh the certificate. This field is set via the /status subresource, + // and must be set at the same time as certificateChain. Once populated, + // this field is immutable. + // + // This field is only a hint. Kubelet may start refreshing before or after + // this time if necessary. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time beginRefreshAt = 5; + + // notAfter is the time at which the certificate expires. The value must be + // the same as the notAfter value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time notAfter = 6; +} + diff --git a/constraint/vendor/k8s.io/api/certificates/v1/register.go b/constraint/vendor/k8s.io/api/certificates/v1/register.go index 2dac94ada..474b8b032 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/register.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/register.go @@ -53,6 +53,10 @@ func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &CertificateSigningRequest{}, &CertificateSigningRequestList{}, + &ClusterTrustBundle{}, + &ClusterTrustBundleList{}, + &PodCertificateRequest{}, + &PodCertificateRequestList{}, ) // Add the watch version that applies diff --git a/constraint/vendor/k8s.io/api/certificates/v1/types.go b/constraint/vendor/k8s.io/api/certificates/v1/types.go index 9a86af13a..b90179ea4 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/types.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/types.go @@ -21,6 +21,7 @@ import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" ) // +genclient @@ -42,7 +43,7 @@ import ( // +k8s:supportsSubresource="/status" // +k8s:supportsSubresource="/approval" type CertificateSigningRequest struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -179,12 +180,12 @@ type CertificateSigningRequestStatus struct { // +listType=map // +listMapKey=type // +optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=type - // +k8s:alpha(since: "1.36")=+k8s:customUnique - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=type + // +k8s:beta(since: "1.37")=+k8s:customUnique + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember Conditions []CertificateSigningRequestCondition `json:"conditions,omitempty" protobuf:"bytes,1,rep,name=conditions"` // certificate is populated with an issued certificate by the signer after an Approved condition is present. @@ -273,7 +274,7 @@ type CertificateSigningRequestCondition struct { // CertificateSigningRequestList is a collection of CertificateSigningRequest objects type CertificateSigningRequestList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -316,3 +317,326 @@ const ( UsageMicrosoftSGC KeyUsage = "microsoft sgc" UsageNetscapeSGC KeyUsage = "netscape sgc" ) + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors +// (root certificates). +// +// ClusterTrustBundle objects are considered to be readable by any authenticated +// user in the cluster, because they can be mounted by pods using the +// `clusterTrustBundle` projection. All service accounts have read access to +// ClusterTrustBundles by default. Users who only have namespace-level access +// to a cluster can read ClusterTrustBundles by impersonating a serviceaccount +// that they have access to. +// +// It can be optionally associated with a particular signer, in which case it +// contains one valid set of trust anchors for that signer. Signers may have +// multiple associated ClusterTrustBundles; each is an independent set of trust +// anchors for that signer. Admission control is used to enforce that only users +// with permissions on the signer can create or modify the corresponding bundle. +type ClusterTrustBundle struct { + metav1.TypeMeta `json:""` + + // metadata contains the object metadata. + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec contains the signer (if any) and trust anchors. + Spec ClusterTrustBundleSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` +} + +// ClusterTrustBundleSpec contains the signer and trust anchors. +type ClusterTrustBundleSpec struct { + // signerName indicates the associated signer, if any. + // + // In order to create or update a ClusterTrustBundle that sets signerName, + // you must have the following cluster-scoped permission: + // group=certificates.k8s.io resource=signers resourceName= + // verb=attest. + // + // If signerName is not empty, then the ClusterTrustBundle object must be + // named with the signer name as a prefix (translating slashes to colons). + // For example, for the signer name `example.com/foo`, valid + // ClusterTrustBundle object names include `example.com:foo:abc` and + // `example.com:foo:v1`. + // + // If signerName is empty, then the ClusterTrustBundle object's name must + // not have such a prefix. + // + // List/watch requests for ClusterTrustBundles can filter on this field + // using a `spec.signerName=NAME` field selector. + // + // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable + SignerName string `json:"signerName,omitempty" protobuf:"bytes,1,opt,name=signerName"` + + // trustBundle contains the individual X.509 trust anchors for this + // bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates. + // + // The data must consist only of PEM certificate blocks that parse as valid + // X.509 certificates. Each certificate must include a basic constraints + // extension with the CA bit set. The API server will reject objects that + // contain duplicate certificates, or that use PEM block headers. + // + // Users of ClusterTrustBundles, including Kubelet, are free to reorder and + // deduplicate certificate blocks in this file according to their own logic, + // as well as to drop PEM block headers and inter-block data. + TrustBundle string `json:"trustBundle" protobuf:"bytes,2,opt,name=trustBundle"` +} + +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterTrustBundleList is a collection of ClusterTrustBundle objects +type ClusterTrustBundleList struct { + metav1.TypeMeta `json:""` + + // metadata contains the list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // items is a collection of ClusterTrustBundle objects + Items []ClusterTrustBundle `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// +genclient +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodCertificateRequest encodes a pod requesting a certificate from a given +// signer. +// +// Kubelets use this API to implement podCertificate projected volumes +// +k8s:supportsSubresource="/status" +type PodCertificateRequest struct { + metav1.TypeMeta `json:""` + + // metadata contains the object metadata. + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec contains the details about the certificate being requested. + // +required + Spec PodCertificateRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status contains the issued certificate, and a standard set of conditions. + // +optional + Status PodCertificateRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// PodCertificateRequestSpec describes the certificate request. All fields are +// immutable after creation. +type PodCertificateRequestSpec struct { + // signerName indicates the requested signer. + // + // All signer names beginning with `kubernetes.io` are reserved for use by + // the Kubernetes project. There is currently one well-known signer + // documented by the Kubernetes project, + // `kubernetes.io/kube-apiserver-client-pod`, which will issue client + // certificates understood by kube-apiserver. It is currently + // unimplemented. + // + // +required + SignerName string `json:"signerName" protobuf:"bytes,1,opt,name=signerName"` + + // podName is the name of the pod into which the certificate will be mounted. + // + // +required + PodName string `json:"podName" protobuf:"bytes,2,opt,name=podName"` + // podUID is the UID of the pod into which the certificate will be mounted. + // + // +required + PodUID types.UID `json:"podUID" protobuf:"bytes,3,opt,name=podUID"` + + // serviceAccountName is the name of the service account the pod is running as. + // + // +required + ServiceAccountName string `json:"serviceAccountName" protobuf:"bytes,4,opt,name=serviceAccountName"` + // serviceAccountUID is the UID of the service account the pod is running as. + // + // +required + ServiceAccountUID types.UID `json:"serviceAccountUID" protobuf:"bytes,5,opt,name=serviceAccountUID"` + + // nodeName is the name of the node the pod is assigned to. + // + // +required + NodeName types.NodeName `json:"nodeName" protobuf:"bytes,6,opt,name=nodeName"` + // nodeUID is the UID of the node the pod is assigned to. + // + // +required + NodeUID types.UID `json:"nodeUID" protobuf:"bytes,7,opt,name=nodeUID"` + + // maxExpirationSeconds is the maximum lifetime permitted for the + // certificate. + // + // If omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver + // will reject values shorter than 3600 (1 hour). The maximum allowable + // value is 7862400 (91 days). + // + // The signer implementation is then free to issue a certificate with any + // lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 + // seconds (1 hour). This constraint is enforced by kube-apiserver. + // `kubernetes.io` signers will never issue certificates with a lifetime + // longer than 24 hours. + // + // +optional + // +default=86400 + MaxExpirationSeconds *int32 `json:"maxExpirationSeconds,omitempty" protobuf:"varint,8,opt,name=maxExpirationSeconds"` + + // A PKCS#10 certificate signing request (DER-serialized) generated by + // Kubelet using the subject private key. + // + // Most signer implementations will ignore the contents of the CSR except to + // extract the subject public key. The API server automatically verifies the + // CSR signature during admission, so the signer does not need to repeat the + // verification. CSRs generated by kubelet are completely empty. + // + // The subject public key must be one of RSA3072, RSA4096, ECDSAP256, + // ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in + // the future. + // + // Signer implementations do not need to support all key types supported by + // kube-apiserver and kubelet. If a signer does not support the key type + // used for a given PodCertificateRequest, it must deny the request by + // setting a status.conditions entry with a type of "Denied" and a reason of + // "UnsupportedKeyType". It may also suggest a key type that it does support + // in the message field. + // + // +required + StubPKCS10Request []byte `json:"stubPKCS10Request" protobuf:"bytes,12,opt,name=stubPKCS10Request"` + + // unverifiedUserAnnotations allow pod authors to pass additional information to + // the signer implementation. Kubernetes does not restrict or validate this + // metadata in any way. + // + // Entries are subject to the same validation as object metadata annotations, + // with the addition that all keys must be domain-prefixed. No restrictions + // are placed on values, except an overall size limitation on the entire field. + // + // Signers should document the keys and values they support. Signers should + // deny requests that contain keys they do not recognize. + // + // +optional + UnverifiedUserAnnotations map[string]string `json:"unverifiedUserAnnotations,omitempty" protobuf:"bytes,11,opt,name=unverifiedUserAnnotations"` +} + +// PodCertificateRequestStatus describes the status of the request, and holds +// the certificate data if the request is issued. +type PodCertificateRequestStatus struct { + // conditions applied to the request. + // + // The types "Issued", "Denied", and "Failed" have special handling. At + // most one of these conditions may be present, and they must have status + // "True". + // + // If the request is denied with `Reason=UnsupportedKeyType`, the signer may + // suggest a key type that will work in the message field. + // + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + + // certificateChain is populated with an issued certificate by the signer. + // This field is set via the /status subresource. Once populated, this field + // is immutable. + // + // If the certificate signing request is denied, a condition of type + // "Denied" is added and this field remains empty. If the signer cannot + // issue the certificate, a condition of type "Failed" is added and this + // field remains empty. + // + // Validation requirements: + // 1. certificateChain must consist of one or more PEM-formatted certificates. + // 2. Each entry must be a valid PEM-wrapped, DER-encoded ASN.1 Certificate as + // described in section 4 of RFC5280. + // + // If more than one block is present, and the definition of the requested + // spec.signerName does not indicate otherwise, the first block is the + // issued certificate, and subsequent blocks should be treated as + // intermediate certificates and presented in TLS handshakes. When + // projecting the chain into a pod volume, kubelet will drop any data + // in-between the PEM blocks, as well as any PEM block headers. + // + // +optional + CertificateChain string `json:"certificateChain,omitempty" protobuf:"bytes,2,opt,name=certificateChain"` + + // notBefore is the time at which the certificate becomes valid. The value + // must be the same as the notBefore value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + // + // +optional + NotBefore *metav1.Time `json:"notBefore,omitempty" protobuf:"bytes,4,opt,name=notBefore"` + + // beginRefreshAt is the time at which the kubelet should begin trying to + // refresh the certificate. This field is set via the /status subresource, + // and must be set at the same time as certificateChain. Once populated, + // this field is immutable. + // + // This field is only a hint. Kubelet may start refreshing before or after + // this time if necessary. + // + // +optional + BeginRefreshAt *metav1.Time `json:"beginRefreshAt,omitempty" protobuf:"bytes,5,opt,name=beginRefreshAt"` + + // notAfter is the time at which the certificate expires. The value must be + // the same as the notAfter value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + // + // +optional + NotAfter *metav1.Time `json:"notAfter,omitempty" protobuf:"bytes,6,opt,name=notAfter"` +} + +// Well-known condition types for PodCertificateRequests +const ( + // Denied indicates the request was denied by the signer. + PodCertificateRequestConditionTypeDenied string = "Denied" + // Failed indicates the signer failed to issue the certificate. + PodCertificateRequestConditionTypeFailed string = "Failed" + // Issued indicates the certificate has been issued. + PodCertificateRequestConditionTypeIssued string = "Issued" +) + +// Well-known condition reasons for PodCertificateRequests +const ( + // UnsupportedKeyType should be set on "Denied" conditions when the signer + // doesn't support the key type of publicKey. + PodCertificateRequestConditionUnsupportedKeyType string = "UnsupportedKeyType" + + // InvalidUnverifiedUserAnnotations should be set on "Denied" conditions when the signer + // does not recognize one of the keys passed in userConfig, or if the signer + // otherwise considers the userConfig of the request to be invalid. + PodCertificateRequestConditionInvalidUserConfig string = "InvalidUnverifiedUserAnnotations" +) + +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodCertificateRequestList is a collection of PodCertificateRequest objects +type PodCertificateRequestList struct { + metav1.TypeMeta `json:""` + + // metadata contains the list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // items is a collection of PodCertificateRequest objects + Items []PodCertificateRequest `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/constraint/vendor/k8s.io/api/certificates/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/certificates/v1/types_swagger_doc_generated.go index 4bdf39ebb..503de052a 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/types_swagger_doc_generated.go @@ -86,4 +86,86 @@ func (CertificateSigningRequestStatus) SwaggerDoc() map[string]string { return map_CertificateSigningRequestStatus } +var map_ClusterTrustBundle = map[string]string{ + "": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular signer, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", + "metadata": "metadata contains the object metadata.", + "spec": "spec contains the signer (if any) and trust anchors.", +} + +func (ClusterTrustBundle) SwaggerDoc() map[string]string { + return map_ClusterTrustBundle +} + +var map_ClusterTrustBundleList = map[string]string{ + "": "ClusterTrustBundleList is a collection of ClusterTrustBundle objects", + "metadata": "metadata contains the list metadata.", + "items": "items is a collection of ClusterTrustBundle objects", +} + +func (ClusterTrustBundleList) SwaggerDoc() map[string]string { + return map_ClusterTrustBundleList +} + +var map_ClusterTrustBundleSpec = map[string]string{ + "": "ClusterTrustBundleSpec contains the signer and trust anchors.", + "signerName": "signerName indicates the associated signer, if any.\n\nIn order to create or update a ClusterTrustBundle that sets signerName, you must have the following cluster-scoped permission: group=certificates.k8s.io resource=signers resourceName= verb=attest.\n\nIf signerName is not empty, then the ClusterTrustBundle object must be named with the signer name as a prefix (translating slashes to colons). For example, for the signer name `example.com/foo`, valid ClusterTrustBundle object names include `example.com:foo:abc` and `example.com:foo:v1`.\n\nIf signerName is empty, then the ClusterTrustBundle object's name must not have such a prefix.\n\nList/watch requests for ClusterTrustBundles can filter on this field using a `spec.signerName=NAME` field selector.", + "trustBundle": "trustBundle contains the individual X.509 trust anchors for this bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates.\n\nThe data must consist only of PEM certificate blocks that parse as valid X.509 certificates. Each certificate must include a basic constraints extension with the CA bit set. The API server will reject objects that contain duplicate certificates, or that use PEM block headers.\n\nUsers of ClusterTrustBundles, including Kubelet, are free to reorder and deduplicate certificate blocks in this file according to their own logic, as well as to drop PEM block headers and inter-block data.", +} + +func (ClusterTrustBundleSpec) SwaggerDoc() map[string]string { + return map_ClusterTrustBundleSpec +} + +var map_PodCertificateRequest = map[string]string{ + "": "PodCertificateRequest encodes a pod requesting a certificate from a given signer.\n\nKubelets use this API to implement podCertificate projected volumes", + "metadata": "metadata contains the object metadata.", + "spec": "spec contains the details about the certificate being requested.", + "status": "status contains the issued certificate, and a standard set of conditions.", +} + +func (PodCertificateRequest) SwaggerDoc() map[string]string { + return map_PodCertificateRequest +} + +var map_PodCertificateRequestList = map[string]string{ + "": "PodCertificateRequestList is a collection of PodCertificateRequest objects", + "metadata": "metadata contains the list metadata.", + "items": "items is a collection of PodCertificateRequest objects", +} + +func (PodCertificateRequestList) SwaggerDoc() map[string]string { + return map_PodCertificateRequestList +} + +var map_PodCertificateRequestSpec = map[string]string{ + "": "PodCertificateRequestSpec describes the certificate request. All fields are immutable after creation.", + "signerName": "signerName indicates the requested signer.\n\nAll signer names beginning with `kubernetes.io` are reserved for use by the Kubernetes project. There is currently one well-known signer documented by the Kubernetes project, `kubernetes.io/kube-apiserver-client-pod`, which will issue client certificates understood by kube-apiserver. It is currently unimplemented.", + "podName": "podName is the name of the pod into which the certificate will be mounted.", + "podUID": "podUID is the UID of the pod into which the certificate will be mounted.", + "serviceAccountName": "serviceAccountName is the name of the service account the pod is running as.", + "serviceAccountUID": "serviceAccountUID is the UID of the service account the pod is running as.", + "nodeName": "nodeName is the name of the node the pod is assigned to.", + "nodeUID": "nodeUID is the UID of the node the pod is assigned to.", + "maxExpirationSeconds": "maxExpirationSeconds is the maximum lifetime permitted for the certificate.\n\nIf omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver will reject values shorter than 3600 (1 hour). The maximum allowable value is 7862400 (91 days).\n\nThe signer implementation is then free to issue a certificate with any lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 seconds (1 hour). This constraint is enforced by kube-apiserver. `kubernetes.io` signers will never issue certificates with a lifetime longer than 24 hours.", + "stubPKCS10Request": "A PKCS#10 certificate signing request (DER-serialized) generated by Kubelet using the subject private key.\n\nMost signer implementations will ignore the contents of the CSR except to extract the subject public key. The API server automatically verifies the CSR signature during admission, so the signer does not need to repeat the verification. CSRs generated by kubelet are completely empty.\n\nThe subject public key must be one of RSA3072, RSA4096, ECDSAP256, ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in the future.\n\nSigner implementations do not need to support all key types supported by kube-apiserver and kubelet. If a signer does not support the key type used for a given PodCertificateRequest, it must deny the request by setting a status.conditions entry with a type of \"Denied\" and a reason of \"UnsupportedKeyType\". It may also suggest a key type that it does support in the message field.", + "unverifiedUserAnnotations": "unverifiedUserAnnotations allow pod authors to pass additional information to the signer implementation. Kubernetes does not restrict or validate this metadata in any way.\n\nEntries are subject to the same validation as object metadata annotations, with the addition that all keys must be domain-prefixed. No restrictions are placed on values, except an overall size limitation on the entire field.\n\nSigners should document the keys and values they support. Signers should deny requests that contain keys they do not recognize.", +} + +func (PodCertificateRequestSpec) SwaggerDoc() map[string]string { + return map_PodCertificateRequestSpec +} + +var map_PodCertificateRequestStatus = map[string]string{ + "": "PodCertificateRequestStatus describes the status of the request, and holds the certificate data if the request is issued.", + "conditions": "conditions applied to the request.\n\nThe types \"Issued\", \"Denied\", and \"Failed\" have special handling. At most one of these conditions may be present, and they must have status \"True\".\n\nIf the request is denied with `Reason=UnsupportedKeyType`, the signer may suggest a key type that will work in the message field.", + "certificateChain": "certificateChain is populated with an issued certificate by the signer. This field is set via the /status subresource. Once populated, this field is immutable.\n\nIf the certificate signing request is denied, a condition of type \"Denied\" is added and this field remains empty. If the signer cannot issue the certificate, a condition of type \"Failed\" is added and this field remains empty.\n\nValidation requirements:\n 1. certificateChain must consist of one or more PEM-formatted certificates.\n 2. Each entry must be a valid PEM-wrapped, DER-encoded ASN.1 Certificate as\n described in section 4 of RFC5280.\n\nIf more than one block is present, and the definition of the requested spec.signerName does not indicate otherwise, the first block is the issued certificate, and subsequent blocks should be treated as intermediate certificates and presented in TLS handshakes. When projecting the chain into a pod volume, kubelet will drop any data in-between the PEM blocks, as well as any PEM block headers.", + "notBefore": "notBefore is the time at which the certificate becomes valid. The value must be the same as the notBefore value in the leaf certificate in certificateChain. This field is set via the /status subresource. Once populated, it is immutable. The signer must set this field at the same time it sets certificateChain.", + "beginRefreshAt": "beginRefreshAt is the time at which the kubelet should begin trying to refresh the certificate. This field is set via the /status subresource, and must be set at the same time as certificateChain. Once populated, this field is immutable.\n\nThis field is only a hint. Kubelet may start refreshing before or after this time if necessary.", + "notAfter": "notAfter is the time at which the certificate expires. The value must be the same as the notAfter value in the leaf certificate in certificateChain. This field is set via the /status subresource. Once populated, it is immutable. The signer must set this field at the same time it sets certificateChain.", +} + +func (PodCertificateRequestStatus) SwaggerDoc() map[string]string { + return map_PodCertificateRequestStatus +} + // AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.deepcopy.go index aefa60411..b25937758 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.deepcopy.go @@ -22,6 +22,7 @@ limitations under the License. package v1 import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -183,6 +184,82 @@ func (in *CertificateSigningRequestStatus) DeepCopy() *CertificateSigningRequest return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterTrustBundle) DeepCopyInto(out *ClusterTrustBundle) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTrustBundle. +func (in *ClusterTrustBundle) DeepCopy() *ClusterTrustBundle { + if in == nil { + return nil + } + out := new(ClusterTrustBundle) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterTrustBundle) 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 *ClusterTrustBundleList) DeepCopyInto(out *ClusterTrustBundleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterTrustBundle, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTrustBundleList. +func (in *ClusterTrustBundleList) DeepCopy() *ClusterTrustBundleList { + if in == nil { + return nil + } + out := new(ClusterTrustBundleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterTrustBundleList) 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 *ClusterTrustBundleSpec) DeepCopyInto(out *ClusterTrustBundleSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTrustBundleSpec. +func (in *ClusterTrustBundleSpec) DeepCopy() *ClusterTrustBundleSpec { + if in == nil { + return nil + } + out := new(ClusterTrustBundleSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in ExtraValue) DeepCopyInto(out *ExtraValue) { { @@ -202,3 +279,132 @@ func (in ExtraValue) DeepCopy() ExtraValue { in.DeepCopyInto(out) return *out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodCertificateRequest) DeepCopyInto(out *PodCertificateRequest) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodCertificateRequest. +func (in *PodCertificateRequest) DeepCopy() *PodCertificateRequest { + if in == nil { + return nil + } + out := new(PodCertificateRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodCertificateRequest) 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 *PodCertificateRequestList) DeepCopyInto(out *PodCertificateRequestList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodCertificateRequest, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodCertificateRequestList. +func (in *PodCertificateRequestList) DeepCopy() *PodCertificateRequestList { + if in == nil { + return nil + } + out := new(PodCertificateRequestList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodCertificateRequestList) 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 *PodCertificateRequestSpec) DeepCopyInto(out *PodCertificateRequestSpec) { + *out = *in + if in.MaxExpirationSeconds != nil { + in, out := &in.MaxExpirationSeconds, &out.MaxExpirationSeconds + *out = new(int32) + **out = **in + } + if in.StubPKCS10Request != nil { + in, out := &in.StubPKCS10Request, &out.StubPKCS10Request + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.UnverifiedUserAnnotations != nil { + in, out := &in.UnverifiedUserAnnotations, &out.UnverifiedUserAnnotations + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodCertificateRequestSpec. +func (in *PodCertificateRequestSpec) DeepCopy() *PodCertificateRequestSpec { + if in == nil { + return nil + } + out := new(PodCertificateRequestSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodCertificateRequestStatus) DeepCopyInto(out *PodCertificateRequestStatus) { + *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.NotBefore != nil { + in, out := &in.NotBefore, &out.NotBefore + *out = (*in).DeepCopy() + } + if in.BeginRefreshAt != nil { + in, out := &in.BeginRefreshAt, &out.BeginRefreshAt + *out = (*in).DeepCopy() + } + if in.NotAfter != nil { + in, out := &in.NotAfter, &out.NotAfter + *out = (*in).DeepCopy() + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodCertificateRequestStatus. +func (in *PodCertificateRequestStatus) DeepCopy() *PodCertificateRequestStatus { + if in == nil { + return nil + } + out := new(PodCertificateRequestStatus) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.model_name.go index 9c7ad07a2..73457044c 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.model_name.go @@ -45,3 +45,38 @@ func (in CertificateSigningRequestSpec) OpenAPIModelName() string { func (in CertificateSigningRequestStatus) OpenAPIModelName() string { return "io.k8s.api.certificates.v1.CertificateSigningRequestStatus" } + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ClusterTrustBundle) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.ClusterTrustBundle" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ClusterTrustBundleList) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.ClusterTrustBundleList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ClusterTrustBundleSpec) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.ClusterTrustBundleSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodCertificateRequest) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.PodCertificateRequest" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodCertificateRequestList) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.PodCertificateRequestList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodCertificateRequestSpec) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.PodCertificateRequestSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodCertificateRequestStatus) OpenAPIModelName() string { + return "io.k8s.api.certificates.v1.PodCertificateRequestStatus" +} diff --git a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.prerelease-lifecycle.go index 3a2b27403..522a9bee5 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/certificates/v1/zz_generated.prerelease-lifecycle.go @@ -32,3 +32,27 @@ func (in *CertificateSigningRequest) APILifecycleIntroduced() (major, minor int) func (in *CertificateSigningRequestList) APILifecycleIntroduced() (major, minor int) { return 1, 19 } + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *ClusterTrustBundle) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *ClusterTrustBundleList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *PodCertificateRequest) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *PodCertificateRequestList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} diff --git a/constraint/vendor/k8s.io/api/certificates/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/certificates/v1alpha1/generated.proto index 7155f778c..914d8e269 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/certificates/v1alpha1/generated.proto @@ -38,7 +38,7 @@ option go_package = "k8s.io/api/certificates/v1alpha1"; // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users @@ -85,6 +85,8 @@ message ClusterTrustBundleSpec { // using a `spec.signerName=NAME` field selector. // // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable optional string signerName = 1; // trustBundle contains the individual X.509 trust anchors for this diff --git a/constraint/vendor/k8s.io/api/certificates/v1alpha1/types.go b/constraint/vendor/k8s.io/api/certificates/v1alpha1/types.go index beef02599..bdac6657c 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/certificates/v1alpha1/types.go @@ -36,13 +36,13 @@ import ( // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users // with permissions on the signer can create or modify the corresponding bundle. type ClusterTrustBundle struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the object metadata. // +optional @@ -74,6 +74,8 @@ type ClusterTrustBundleSpec struct { // using a `spec.signerName=NAME` field selector. // // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable SignerName string `json:"signerName,omitempty" protobuf:"bytes,1,opt,name=signerName"` // trustBundle contains the individual X.509 trust anchors for this @@ -96,7 +98,7 @@ type ClusterTrustBundleSpec struct { // ClusterTrustBundleList is a collection of ClusterTrustBundle objects type ClusterTrustBundleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the list metadata. // diff --git a/constraint/vendor/k8s.io/api/certificates/v1alpha1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/certificates/v1alpha1/types_swagger_doc_generated.go index bff649e3c..862897e97 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1alpha1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/certificates/v1alpha1/types_swagger_doc_generated.go @@ -28,7 +28,7 @@ package v1alpha1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_ClusterTrustBundle = map[string]string{ - "": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular assigner, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", + "": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular signer, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", "metadata": "metadata contains the object metadata.", "spec": "spec contains the signer (if any) and trust anchors.", } diff --git a/constraint/vendor/k8s.io/api/certificates/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/certificates/v1beta1/generated.proto index cc46dee16..25561abbc 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/certificates/v1beta1/generated.proto @@ -183,12 +183,12 @@ message CertificateSigningRequestStatus { // +listType=map // +listMapKey=type // +optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=type - // +k8s:alpha(since: "1.36")=+k8s:customUnique - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=type + // +k8s:beta(since: "1.37")=+k8s:customUnique + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember repeated CertificateSigningRequestCondition conditions = 1; // If request was approved, the controller will place the issued certificate here. @@ -206,7 +206,7 @@ message CertificateSigningRequestStatus { // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users @@ -253,6 +253,8 @@ message ClusterTrustBundleSpec { // using a `spec.signerName=NAME` field selector. // // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable optional string signerName = 1; // trustBundle contains the individual X.509 trust anchors for this @@ -282,6 +284,7 @@ message ExtraValue { // signer. // // Kubelets use this API to implement podCertificate projected volumes +// +k8s:supportsSubresource="/status" message PodCertificateRequest { // metadata contains the object metadata. // @@ -467,6 +470,9 @@ message PodCertificateRequestStatus { // +listType=map // +listMapKey=type // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; // certificateChain is populated with an issued certificate by the signer. diff --git a/constraint/vendor/k8s.io/api/certificates/v1beta1/types.go b/constraint/vendor/k8s.io/api/certificates/v1beta1/types.go index e8ffa41e6..eaa77c194 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/certificates/v1beta1/types.go @@ -35,7 +35,7 @@ import ( // +k8s:supportsSubresource="/status" // +k8s:supportsSubresource="/approval" type CertificateSigningRequest struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -177,12 +177,12 @@ type CertificateSigningRequestStatus struct { // +listType=map // +listMapKey=type // +optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=type - // +k8s:alpha(since: "1.36")=+k8s:customUnique - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember - // +k8s:alpha(since: "1.36")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=type + // +k8s:beta(since: "1.37")=+k8s:customUnique + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:item(type: "Approved")=+k8s:zeroOrOneOfMember + // +k8s:beta(since: "1.37")=+k8s:item(type: "Denied")=+k8s:zeroOrOneOfMember Conditions []CertificateSigningRequestCondition `json:"conditions,omitempty" protobuf:"bytes,1,rep,name=conditions"` // If request was approved, the controller will place the issued certificate here. @@ -230,7 +230,7 @@ type CertificateSigningRequestCondition struct { // +k8s:prerelease-lifecycle-gen:replacement=certificates.k8s.io,v1,CertificateSigningRequestList type CertificateSigningRequestList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -274,6 +274,7 @@ const ( // +genclient:nonNamespaced // +k8s:prerelease-lifecycle-gen:introduced=1.33 // +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=certificates.k8s.io,v1,ClusterTrustBundle // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors @@ -286,13 +287,13 @@ const ( // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users // with permissions on the signer can create or modify the corresponding bundle. type ClusterTrustBundle struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the object metadata. // +optional @@ -324,6 +325,8 @@ type ClusterTrustBundleSpec struct { // using a `spec.signerName=NAME` field selector. // // +optional + // +k8s:alpha(since:"1.37")=+k8s:optional + // +k8s:alpha(since:"1.37")=+k8s:immutable SignerName string `json:"signerName,omitempty" protobuf:"bytes,1,opt,name=signerName"` // trustBundle contains the individual X.509 trust anchors for this @@ -342,11 +345,12 @@ type ClusterTrustBundleSpec struct { // +k8s:prerelease-lifecycle-gen:introduced=1.33 // +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=certificates.k8s.io,v1,ClusterTrustBundleList // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterTrustBundleList is a collection of ClusterTrustBundle objects type ClusterTrustBundleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the list metadata. // @@ -359,14 +363,17 @@ type ClusterTrustBundleList struct { // +genclient // +k8s:prerelease-lifecycle-gen:introduced=1.35 +// +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=certificates.k8s.io,v1,PodCertificateRequest // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // PodCertificateRequest encodes a pod requesting a certificate from a given // signer. // // Kubelets use this API to implement podCertificate projected volumes +// +k8s:supportsSubresource="/status" type PodCertificateRequest struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the object metadata. // @@ -538,6 +545,9 @@ type PodCertificateRequestStatus struct { // +listType=map // +listMapKey=type // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // certificateChain is populated with an issued certificate by the signer. @@ -618,10 +628,12 @@ const ( // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.35 +// +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=certificates.k8s.io,v1,PodCertificateRequestList // PodCertificateRequestList is a collection of PodCertificateRequest objects type PodCertificateRequestList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // metadata contains the list metadata. // diff --git a/constraint/vendor/k8s.io/api/certificates/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/certificates/v1beta1/types_swagger_doc_generated.go index cad8768a5..c5352a7ac 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/certificates/v1beta1/types_swagger_doc_generated.go @@ -76,7 +76,7 @@ func (CertificateSigningRequestStatus) SwaggerDoc() map[string]string { } var map_ClusterTrustBundle = map[string]string{ - "": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular assigner, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", + "": "ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors (root certificates).\n\nClusterTrustBundle objects are considered to be readable by any authenticated user in the cluster, because they can be mounted by pods using the `clusterTrustBundle` projection. All service accounts have read access to ClusterTrustBundles by default. Users who only have namespace-level access to a cluster can read ClusterTrustBundles by impersonating a serviceaccount that they have access to.\n\nIt can be optionally associated with a particular signer, in which case it contains one valid set of trust anchors for that signer. Signers may have multiple associated ClusterTrustBundles; each is an independent set of trust anchors for that signer. Admission control is used to enforce that only users with permissions on the signer can create or modify the corresponding bundle.", "metadata": "metadata contains the object metadata.", "spec": "spec contains the signer (if any) and trust anchors.", } diff --git a/constraint/vendor/k8s.io/api/certificates/v1beta1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/certificates/v1beta1/zz_generated.prerelease-lifecycle.go index d541ffb00..3b6f17e3e 100644 --- a/constraint/vendor/k8s.io/api/certificates/v1beta1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/certificates/v1beta1/zz_generated.prerelease-lifecycle.go @@ -85,6 +85,12 @@ func (in *ClusterTrustBundle) APILifecycleDeprecated() (major, minor int) { return 1, 37 } +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *ClusterTrustBundle) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "certificates.k8s.io", Version: "v1", Kind: "ClusterTrustBundle"} +} + // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *ClusterTrustBundle) APILifecycleRemoved() (major, minor int) { @@ -103,6 +109,12 @@ func (in *ClusterTrustBundleList) APILifecycleDeprecated() (major, minor int) { return 1, 37 } +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *ClusterTrustBundleList) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "certificates.k8s.io", Version: "v1", Kind: "ClusterTrustBundleList"} +} + // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *ClusterTrustBundleList) APILifecycleRemoved() (major, minor int) { @@ -118,13 +130,19 @@ func (in *PodCertificateRequest) APILifecycleIntroduced() (major, minor int) { // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *PodCertificateRequest) APILifecycleDeprecated() (major, minor int) { - return 1, 38 + return 1, 37 +} + +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *PodCertificateRequest) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "certificates.k8s.io", Version: "v1", Kind: "PodCertificateRequest"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *PodCertificateRequest) APILifecycleRemoved() (major, minor int) { - return 1, 41 + return 1, 40 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. @@ -136,11 +154,17 @@ func (in *PodCertificateRequestList) APILifecycleIntroduced() (major, minor int) // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *PodCertificateRequestList) APILifecycleDeprecated() (major, minor int) { - return 1, 38 + return 1, 37 +} + +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *PodCertificateRequestList) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "certificates.k8s.io", Version: "v1", Kind: "PodCertificateRequestList"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *PodCertificateRequestList) APILifecycleRemoved() (major, minor int) { - return 1, 41 + return 1, 40 } diff --git a/constraint/vendor/k8s.io/api/coordination/v1/generated.proto b/constraint/vendor/k8s.io/api/coordination/v1/generated.proto index 4d4f7e08f..75f1c9acf 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/coordination/v1/generated.proto @@ -30,6 +30,7 @@ option go_package = "k8s.io/api/coordination/v1"; // Lease defines a lease concept. message Lease { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -79,14 +80,14 @@ message LeaseSpec { // +optional optional int32 leaseTransitions = 5; - // Strategy indicates the strategy for picking the leader for coordinated leader election. + // strategy indicates the strategy for picking the leader for coordinated leader election. // If the field is not specified, there is no active coordination for this lease. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. // +featureGate=CoordinatedLeaderElection // +optional optional string strategy = 6; - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. // This field can only be set if Strategy is also set. // +featureGate=CoordinatedLeaderElection diff --git a/constraint/vendor/k8s.io/api/coordination/v1/types.go b/constraint/vendor/k8s.io/api/coordination/v1/types.go index 5307cea88..297ec32cb 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1/types.go +++ b/constraint/vendor/k8s.io/api/coordination/v1/types.go @@ -38,7 +38,8 @@ const ( // Lease defines a lease concept. type Lease struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -72,13 +73,13 @@ type LeaseSpec struct { // holders. // +optional LeaseTransitions *int32 `json:"leaseTransitions,omitempty" protobuf:"varint,5,opt,name=leaseTransitions"` - // Strategy indicates the strategy for picking the leader for coordinated leader election. + // strategy indicates the strategy for picking the leader for coordinated leader election. // If the field is not specified, there is no active coordination for this lease. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. // +featureGate=CoordinatedLeaderElection // +optional Strategy *CoordinatedLeaseStrategy `json:"strategy,omitempty" protobuf:"bytes,6,opt,name=strategy"` - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. // This field can only be set if Strategy is also set. // +featureGate=CoordinatedLeaderElection @@ -91,7 +92,7 @@ type LeaseSpec struct { // LeaseList is a list of Lease objects. type LeaseList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/coordination/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/coordination/v1/types_swagger_doc_generated.go index 6c1a7ea8b..c8bdb1e42 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/coordination/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Lease = map[string]string{ "": "Lease defines a lease concept.", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -54,8 +54,8 @@ var map_LeaseSpec = map[string]string{ "acquireTime": "acquireTime is a time when the current lease was acquired.", "renewTime": "renewTime is a time when the current holder of a lease has last updated the lease.", "leaseTransitions": "leaseTransitions is the number of transitions of a lease between holders.", - "strategy": "Strategy indicates the strategy for picking the leader for coordinated leader election. If the field is not specified, there is no active coordination for this lease. (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled.", - "preferredHolder": "PreferredHolder signals to a lease holder that the lease has a more optimal holder and should be given up. This field can only be set if Strategy is also set.", + "strategy": "strategy indicates the strategy for picking the leader for coordinated leader election. If the field is not specified, there is no active coordination for this lease. (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled.", + "preferredHolder": "preferredHolder signals to a lease holder that the lease has a more optimal holder and should be given up. This field can only be set if Strategy is also set.", } func (LeaseSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/coordination/v1alpha2/generated.proto b/constraint/vendor/k8s.io/api/coordination/v1alpha2/generated.proto index 379fcf0d5..7e1c0e0ef 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1alpha2/generated.proto +++ b/constraint/vendor/k8s.io/api/coordination/v1alpha2/generated.proto @@ -32,6 +32,7 @@ option go_package = "k8s.io/api/coordination/v1alpha2"; // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. message LeaseCandidate { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -55,19 +56,19 @@ message LeaseCandidateList { // LeaseCandidateSpec is a specification of a Lease. message LeaseCandidateSpec { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // This field is immutable. // +required optional string leaseName = 1; - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime pingTime = 2; - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -77,18 +78,18 @@ message LeaseCandidateSpec { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime renewTime = 3; - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. // +required optional string binaryVersion = 4; - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" // +optional optional string emulationVersion = 5; - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. diff --git a/constraint/vendor/k8s.io/api/coordination/v1alpha2/types.go b/constraint/vendor/k8s.io/api/coordination/v1alpha2/types.go index f8a6d33af..ff32ee16f 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1alpha2/types.go +++ b/constraint/vendor/k8s.io/api/coordination/v1alpha2/types.go @@ -28,7 +28,8 @@ import ( // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. type LeaseCandidate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -41,17 +42,17 @@ type LeaseCandidate struct { // LeaseCandidateSpec is a specification of a Lease. type LeaseCandidateSpec struct { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // This field is immutable. // +required LeaseName string `json:"leaseName" protobuf:"bytes,1,name=leaseName"` - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. // +optional PingTime *metav1.MicroTime `json:"pingTime,omitempty" protobuf:"bytes,2,opt,name=pingTime"` - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -60,16 +61,16 @@ type LeaseCandidateSpec struct { // garbage collection for still active LeaseCandidates. // +optional RenewTime *metav1.MicroTime `json:"renewTime,omitempty" protobuf:"bytes,3,opt,name=renewTime"` - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. // +required BinaryVersion string `json:"binaryVersion" protobuf:"bytes,4,name=binaryVersion"` - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" // +optional EmulationVersion string `json:"emulationVersion,omitempty" protobuf:"bytes,5,opt,name=emulationVersion"` - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. @@ -82,7 +83,7 @@ type LeaseCandidateSpec struct { // LeaseCandidateList is a list of Lease objects. type LeaseCandidateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/coordination/v1alpha2/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/coordination/v1alpha2/types_swagger_doc_generated.go index f7e29849e..2ab18a6f6 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1alpha2/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/coordination/v1alpha2/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1alpha2 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_LeaseCandidate = map[string]string{ "": "LeaseCandidate defines a candidate for a Lease object. Candidates are created such that coordinated leader election will pick the best leader from the list of candidates.", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -49,12 +49,12 @@ func (LeaseCandidateList) SwaggerDoc() map[string]string { var map_LeaseCandidateSpec = map[string]string{ "": "LeaseCandidateSpec is a specification of a Lease.", - "leaseName": "LeaseName is the name of the lease for which this candidate is contending. This field is immutable.", - "pingTime": "PingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", - "renewTime": "RenewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", - "binaryVersion": "BinaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", - "emulationVersion": "EmulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", - "strategy": "Strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", + "leaseName": "leaseName is the name of the lease for which this candidate is contending. This field is immutable.", + "pingTime": "pingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", + "renewTime": "renewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", + "binaryVersion": "binaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", + "emulationVersion": "emulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", + "strategy": "strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", } func (LeaseCandidateSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/coordination/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/coordination/v1beta1/generated.proto index 74df40c64..510b230f7 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/coordination/v1beta1/generated.proto @@ -31,6 +31,7 @@ option go_package = "k8s.io/api/coordination/v1beta1"; // Lease defines a lease concept. message Lease { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -44,6 +45,7 @@ message Lease { // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. message LeaseCandidate { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -67,21 +69,21 @@ message LeaseCandidateList { // LeaseCandidateSpec is a specification of a Lease. message LeaseCandidateSpec { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // The limits on this field are the same as on Lease.name. Multiple lease candidates // may reference the same Lease.name. // This field is immutable. // +required optional string leaseName = 1; - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime pingTime = 2; - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -91,18 +93,18 @@ message LeaseCandidateSpec { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.MicroTime renewTime = 3; - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. // +required optional string binaryVersion = 4; - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" // +optional optional string emulationVersion = 5; - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. @@ -149,13 +151,13 @@ message LeaseSpec { // +optional optional int32 leaseTransitions = 5; - // Strategy indicates the strategy for picking the leader for coordinated leader election + // strategy indicates the strategy for picking the leader for coordinated leader election. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. // +featureGate=CoordinatedLeaderElection // +optional optional string strategy = 6; - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. // +featureGate=CoordinatedLeaderElection // +optional diff --git a/constraint/vendor/k8s.io/api/coordination/v1beta1/types.go b/constraint/vendor/k8s.io/api/coordination/v1beta1/types.go index ba6d6aa09..3141d7062 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/coordination/v1beta1/types.go @@ -29,7 +29,8 @@ import ( // Lease defines a lease concept. type Lease struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -63,12 +64,12 @@ type LeaseSpec struct { // holders. // +optional LeaseTransitions *int32 `json:"leaseTransitions,omitempty" protobuf:"varint,5,opt,name=leaseTransitions"` - // Strategy indicates the strategy for picking the leader for coordinated leader election + // strategy indicates the strategy for picking the leader for coordinated leader election. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. // +featureGate=CoordinatedLeaderElection // +optional Strategy *v1.CoordinatedLeaseStrategy `json:"strategy,omitempty" protobuf:"bytes,6,opt,name=strategy"` - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. // +featureGate=CoordinatedLeaderElection // +optional @@ -82,7 +83,7 @@ type LeaseSpec struct { // LeaseList is a list of Lease objects. type LeaseList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -99,7 +100,8 @@ type LeaseList struct { // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. type LeaseCandidate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -112,19 +114,19 @@ type LeaseCandidate struct { // LeaseCandidateSpec is a specification of a Lease. type LeaseCandidateSpec struct { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // The limits on this field are the same as on Lease.name. Multiple lease candidates // may reference the same Lease.name. // This field is immutable. // +required LeaseName string `json:"leaseName" protobuf:"bytes,1,name=leaseName"` - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. // +optional PingTime *metav1.MicroTime `json:"pingTime,omitempty" protobuf:"bytes,2,opt,name=pingTime"` - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -133,16 +135,16 @@ type LeaseCandidateSpec struct { // garbage collection for still active LeaseCandidates. // +optional RenewTime *metav1.MicroTime `json:"renewTime,omitempty" protobuf:"bytes,3,opt,name=renewTime"` - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. // +required BinaryVersion string `json:"binaryVersion" protobuf:"bytes,4,name=binaryVersion"` - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" // +optional EmulationVersion string `json:"emulationVersion,omitempty" protobuf:"bytes,5,opt,name=emulationVersion"` - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. @@ -155,7 +157,7 @@ type LeaseCandidateSpec struct { // LeaseCandidateList is a list of Lease objects. type LeaseCandidateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/coordination/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/coordination/v1beta1/types_swagger_doc_generated.go index 35812b77f..c4297c569 100644 --- a/constraint/vendor/k8s.io/api/coordination/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/coordination/v1beta1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1beta1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Lease = map[string]string{ "": "Lease defines a lease concept.", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -39,7 +39,7 @@ func (Lease) SwaggerDoc() map[string]string { var map_LeaseCandidate = map[string]string{ "": "LeaseCandidate defines a candidate for a Lease object. Candidates are created such that coordinated leader election will pick the best leader from the list of candidates.", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec contains the specification of the Lease. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -59,12 +59,12 @@ func (LeaseCandidateList) SwaggerDoc() map[string]string { var map_LeaseCandidateSpec = map[string]string{ "": "LeaseCandidateSpec is a specification of a Lease.", - "leaseName": "LeaseName is the name of the lease for which this candidate is contending. The limits on this field are the same as on Lease.name. Multiple lease candidates may reference the same Lease.name. This field is immutable.", - "pingTime": "PingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", - "renewTime": "RenewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", - "binaryVersion": "BinaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", - "emulationVersion": "EmulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", - "strategy": "Strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", + "leaseName": "leaseName is the name of the lease for which this candidate is contending. The limits on this field are the same as on Lease.name. Multiple lease candidates may reference the same Lease.name. This field is immutable.", + "pingTime": "pingTime is the last time that the server has requested the LeaseCandidate to renew. It is only done during leader election to check if any LeaseCandidates have become ineligible. When PingTime is updated, the LeaseCandidate will respond by updating RenewTime.", + "renewTime": "renewTime is the time that the LeaseCandidate was last updated. Any time a Lease needs to do leader election, the PingTime field is updated to signal to the LeaseCandidate that they should update the RenewTime. Old LeaseCandidate objects are also garbage collected if it has been hours since the last renew. The PingTime field is updated regularly to prevent garbage collection for still active LeaseCandidates.", + "binaryVersion": "binaryVersion is the binary version. It must be in a semver format without leading `v`. This field is required.", + "emulationVersion": "emulationVersion is the emulation version. It must be in a semver format without leading `v`. EmulationVersion must be less than or equal to BinaryVersion. This field is required when strategy is \"OldestEmulationVersion\"", + "strategy": "strategy is the strategy that coordinated leader election will use for picking the leader. If multiple candidates for the same Lease return different strategies, the strategy provided by the candidate with the latest BinaryVersion will be used. If there is still conflict, this is a user error and coordinated leader election will not operate the Lease until resolved.", } func (LeaseCandidateSpec) SwaggerDoc() map[string]string { @@ -88,8 +88,8 @@ var map_LeaseSpec = map[string]string{ "acquireTime": "acquireTime is a time when the current lease was acquired.", "renewTime": "renewTime is a time when the current holder of a lease has last updated the lease.", "leaseTransitions": "leaseTransitions is the number of transitions of a lease between holders.", - "strategy": "Strategy indicates the strategy for picking the leader for coordinated leader election (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled.", - "preferredHolder": "PreferredHolder signals to a lease holder that the lease has a more optimal holder and should be given up.", + "strategy": "strategy indicates the strategy for picking the leader for coordinated leader election. (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled.", + "preferredHolder": "preferredHolder signals to a lease holder that the lease has a more optimal holder and should be given up.", } func (LeaseSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/core/v1/generated.pb.go b/constraint/vendor/k8s.io/api/core/v1/generated.pb.go index 0fcbd5edf..41bf20df2 100644 --- a/constraint/vendor/k8s.io/api/core/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/core/v1/generated.pb.go @@ -158,6 +158,8 @@ func (m *EventSeries) Reset() { *m = EventSeries{} } func (m *EventSource) Reset() { *m = EventSource{} } +func (m *EvictionResponder) Reset() { *m = EvictionResponder{} } + func (m *ExecAction) Reset() { *m = ExecAction{} } func (m *FCVolumeSource) Reset() { *m = FCVolumeSource{} } @@ -244,6 +246,10 @@ func (m *NodeAddress) Reset() { *m = NodeAddress{} } func (m *NodeAffinity) Reset() { *m = NodeAffinity{} } +func (m *NodeAllocatableMappedResources) Reset() { *m = NodeAllocatableMappedResources{} } + +func (m *NodeAllocatableOverheadResources) Reset() { *m = NodeAllocatableOverheadResources{} } + func (m *NodeAllocatableResourceClaimStatus) Reset() { *m = NodeAllocatableResourceClaimStatus{} } func (m *NodeCondition) Reset() { *m = NodeCondition{} } @@ -258,6 +264,8 @@ func (m *NodeFeatures) Reset() { *m = NodeFeatures{} } func (m *NodeList) Reset() { *m = NodeList{} } +func (m *NodePodPreemptionPolicy) Reset() { *m = NodePodPreemptionPolicy{} } + func (m *NodeProxyOptions) Reset() { *m = NodeProxyOptions{} } func (m *NodeRuntimeHandler) Reset() { *m = NodeRuntimeHandler{} } @@ -360,14 +368,14 @@ func (m *PodSpec) Reset() { *m = PodSpec{} } func (m *PodStatus) Reset() { *m = PodStatus{} } -func (m *PodStatusResult) Reset() { *m = PodStatusResult{} } - func (m *PodTemplate) Reset() { *m = PodTemplate{} } func (m *PodTemplateList) Reset() { *m = PodTemplateList{} } func (m *PodTemplateSpec) Reset() { *m = PodTemplateSpec{} } +func (m *PodVolumeHealth) Reset() { *m = PodVolumeHealth{} } + func (m *PortStatus) Reset() { *m = PortStatus{} } func (m *PortworxVolumeSource) Reset() { *m = PortworxVolumeSource{} } @@ -498,6 +506,10 @@ func (m *Volume) Reset() { *m = Volume{} } func (m *VolumeDevice) Reset() { *m = VolumeDevice{} } +func (m *VolumeHealthCondition) Reset() { *m = VolumeHealthCondition{} } + +func (m *VolumeHealthStatus) Reset() { *m = VolumeHealthStatus{} } + func (m *VolumeMount) Reset() { *m = VolumeMount{} } func (m *VolumeMountStatus) Reset() { *m = VolumeMountStatus{} } @@ -1462,6 +1474,11 @@ func (m *ClusterTrustBundleProjection) MarshalToSizedBuffer(dAtA []byte) (int, e _ = i var l int _ = l + if m.User != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.User)) + i-- + dAtA[i] = 0x30 + } if m.Optional != nil { i-- if *m.Optional { @@ -1999,6 +2016,11 @@ func (m *ConfigMapVolumeSource) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.DefaultUser != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultUser)) + i-- + dAtA[i] = 0x28 + } if m.Optional != nil { i-- if *m.Optional { @@ -3035,6 +3057,11 @@ func (m *DownwardAPIVolumeFile) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.User != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.User)) + i-- + dAtA[i] = 0x28 + } if m.Mode != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.Mode)) i-- @@ -3092,6 +3119,11 @@ func (m *DownwardAPIVolumeSource) MarshalToSizedBuffer(dAtA []byte) (int, error) _ = i var l int _ = l + if m.DefaultUser != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultUser)) + i-- + dAtA[i] = 0x18 + } if m.DefaultMode != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultMode)) i-- @@ -3134,6 +3166,11 @@ func (m *EmptyDirVolumeSource) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Mode != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Mode)) + i-- + dAtA[i] = 0x18 + } if m.SizeLimit != nil { { size, err := m.SizeLimit.MarshalToSizedBuffer(dAtA[:i]) @@ -4207,6 +4244,39 @@ func (m *EventSource) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *EvictionResponder) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *EvictionResponder) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EvictionResponder) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x10 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *ExecAction) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -4597,6 +4667,13 @@ func (m *GRPCAction) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Mode != nil { + i -= len(*m.Mode) + copy(dAtA[i:], *m.Mode) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Mode))) + i-- + dAtA[i] = 0x1a + } if m.Service != nil { i -= len(*m.Service) copy(dAtA[i:], *m.Service) @@ -4757,6 +4834,13 @@ func (m *HTTPGetAction) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.Protocol != nil { + i -= len(*m.Protocol) + copy(dAtA[i:], *m.Protocol) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Protocol))) + i-- + dAtA[i] = 0x32 + } if len(m.HTTPHeaders) > 0 { for iNdEx := len(m.HTTPHeaders) - 1; iNdEx >= 0; iNdEx-- { { @@ -5209,6 +5293,11 @@ func (m *KeyToPath) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.User != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.User)) + i-- + dAtA[i] = 0x20 + } if m.Mode != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.Mode)) i-- @@ -6325,6 +6414,98 @@ func (m *NodeAffinity) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *NodeAllocatableMappedResources) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableMappedResources) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableMappedResources) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Quantity != nil { + { + size, err := m.Quantity.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *NodeAllocatableOverheadResources) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableOverheadResources) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableOverheadResources) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PerContainer != nil { + { + size, err := m.PerContainer.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.PerPod != nil { + { + size, err := m.PerPod.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *NodeAllocatableResourceClaimStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -6345,17 +6526,10 @@ func (m *NodeAllocatableResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) ( _ = i var l int _ = l - if len(m.Resources) > 0 { - keysForResources := make([]string, 0, len(m.Resources)) - for k := range m.Resources { - keysForResources = append(keysForResources, string(k)) - } - sort.Strings(keysForResources) - for iNdEx := len(keysForResources) - 1; iNdEx >= 0; iNdEx-- { - v := m.Resources[ResourceName(keysForResources[iNdEx])] - baseI := i + if len(m.Overhead) > 0 { + for iNdEx := len(m.Overhead) - 1; iNdEx >= 0; iNdEx-- { { - size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Overhead[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -6363,15 +6537,21 @@ func (m *NodeAllocatableResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) ( i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x12 - i -= len(keysForResources[iNdEx]) - copy(dAtA[i:], keysForResources[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForResources[iNdEx]))) - i-- - dAtA[i] = 0xa - i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) + dAtA[i] = 0x2a + } + } + if len(m.Mapping) > 0 { + for iNdEx := len(m.Mapping) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Mapping[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } i-- - dAtA[i] = 0x1a + dAtA[i] = 0x22 } } if len(m.Containers) > 0 { @@ -6666,6 +6846,38 @@ func (m *NodeList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *NodePodPreemptionPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodePodPreemptionPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodePodPreemptionPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DisableResizePreemption) > 0 { + for iNdEx := len(m.DisableResizePreemption) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.DisableResizePreemption[iNdEx]) + copy(dAtA[i:], m.DisableResizePreemption[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.DisableResizePreemption[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func (m *NodeProxyOptions) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -6927,6 +7139,18 @@ func (m *NodeSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.PodPreemptionPolicy != nil { + { + size, err := m.PodPreemptionPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } if len(m.PodCIDRs) > 0 { for iNdEx := len(m.PodCIDRs) - 1; iNdEx >= 0; iNdEx-- { i -= len(m.PodCIDRs[iNdEx]) @@ -7254,6 +7478,16 @@ func (m *NodeSystemInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.RunningInUserNamespace != nil { + i-- + if *m.RunningInUserNamespace { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x60 + } if m.Swap != nil { { size, err := m.Swap.MarshalToSizedBuffer(dAtA[:i]) @@ -7750,6 +7984,18 @@ func (m *PersistentVolumeClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, er _ = i var l int _ = l + if m.HealthStatus != nil { + { + size, err := m.HealthStatus.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + } if m.ModifyVolumeStatus != nil { { size, err := m.ModifyVolumeStatus.MarshalToSizedBuffer(dAtA[:i]) @@ -8834,6 +9080,11 @@ func (m *PodCertificateProjection) MarshalToSizedBuffer(dAtA []byte) (int, error _ = i var l int _ = l + if m.User != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.User)) + i-- + dAtA[i] = 0x40 + } if len(m.UserAnnotations) > 0 { keysForUserAnnotations := make([]string, 0, len(m.UserAnnotations)) for k := range m.UserAnnotations { @@ -9769,6 +10020,22 @@ func (m *PodSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.EvictionResponders) > 0 { + for iNdEx := len(m.EvictionResponders) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.EvictionResponders[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2 + i-- + dAtA[i] = 0xe2 + } + } if m.SchedulingGroup != nil { { size, err := m.SchedulingGroup.MarshalToSizedBuffer(dAtA[:i]) @@ -10280,6 +10547,22 @@ func (m *PodStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.VolumeHealth) > 0 { + for iNdEx := len(m.VolumeHealth) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.VolumeHealth[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xb2 + } + } if len(m.NodeAllocatableResourceClaimStatuses) > 0 { for iNdEx := len(m.NodeAllocatableResourceClaimStatuses) - 1; iNdEx >= 0; iNdEx-- { { @@ -10515,49 +10798,6 @@ func (m *PodStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *PodStatusResult) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PodStatusResult) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PodStatusResult) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - func (m *PodTemplate) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -10691,6 +10931,58 @@ func (m *PodTemplateSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *PodVolumeHealth) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodVolumeHealth) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodVolumeHealth) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if len(m.HealthConditions) > 0 { + for iNdEx := len(m.HealthConditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.HealthConditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *PortStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -11033,6 +11325,11 @@ func (m *ProjectedVolumeSource) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.DefaultUser != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultUser)) + i-- + dAtA[i] = 0x18 + } if m.DefaultMode != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultMode)) i-- @@ -12764,6 +13061,11 @@ func (m *SecretVolumeSource) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.DefaultUser != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.DefaultUser)) + i-- + dAtA[i] = 0x28 + } if m.Optional != nil { i-- if *m.Optional { @@ -13165,6 +13467,11 @@ func (m *ServiceAccountTokenProjection) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if m.User != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.User)) + i-- + dAtA[i] = 0x20 + } i -= len(m.Path) copy(dAtA[i:], m.Path) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Path))) @@ -14217,6 +14524,91 @@ func (m *VolumeDevice) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *VolumeHealthCondition) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VolumeHealthCondition) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VolumeHealthCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Message) + copy(dAtA[i:], m.Message) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) + i-- + dAtA[i] = 0x1a + i -= len(m.Reason) + copy(dAtA[i:], m.Reason) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason))) + i-- + dAtA[i] = 0x12 + i -= len(m.Status) + copy(dAtA[i:], m.Status) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *VolumeHealthStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *VolumeHealthStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *VolumeHealthStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.HealthConditions) > 0 { + for iNdEx := len(m.HealthConditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.HealthConditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func (m *VolumeMount) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -14237,6 +14629,15 @@ func (m *VolumeMount) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.BindMountOptions) > 0 { + for iNdEx := len(m.BindMountOptions) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.BindMountOptions[iNdEx]) + copy(dAtA[i:], m.BindMountOptions[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.BindMountOptions[iNdEx]))) + i-- + dAtA[i] = 0x42 + } + } if m.RecursiveReadOnly != nil { i -= len(*m.RecursiveReadOnly) copy(dAtA[i:], *m.RecursiveReadOnly) @@ -15515,6 +15916,9 @@ func (m *ClusterTrustBundleProjection) Size() (n int) { if m.Optional != nil { n += 2 } + if m.User != nil { + n += 1 + sovGenerated(uint64(*m.User)) + } return n } @@ -15709,6 +16113,9 @@ func (m *ConfigMapVolumeSource) Size() (n int) { if m.Optional != nil { n += 2 } + if m.DefaultUser != nil { + n += 1 + sovGenerated(uint64(*m.DefaultUser)) + } return n } @@ -16090,6 +16497,9 @@ func (m *DownwardAPIVolumeFile) Size() (n int) { if m.Mode != nil { n += 1 + sovGenerated(uint64(*m.Mode)) } + if m.User != nil { + n += 1 + sovGenerated(uint64(*m.User)) + } return n } @@ -16108,6 +16518,9 @@ func (m *DownwardAPIVolumeSource) Size() (n int) { if m.DefaultMode != nil { n += 1 + sovGenerated(uint64(*m.DefaultMode)) } + if m.DefaultUser != nil { + n += 1 + sovGenerated(uint64(*m.DefaultUser)) + } return n } @@ -16123,6 +16536,9 @@ func (m *EmptyDirVolumeSource) Size() (n int) { l = m.SizeLimit.Size() n += 1 + l + sovGenerated(uint64(l)) } + if m.Mode != nil { + n += 1 + sovGenerated(uint64(*m.Mode)) + } return n } @@ -16505,6 +16921,20 @@ func (m *EventSource) Size() (n int) { return n } +func (m *EvictionResponder) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + return n +} + func (m *ExecAction) Size() (n int) { if m == nil { return 0 @@ -16656,6 +17086,10 @@ func (m *GRPCAction) Size() (n int) { l = len(*m.Service) n += 1 + l + sovGenerated(uint64(l)) } + if m.Mode != nil { + l = len(*m.Mode) + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -16726,6 +17160,10 @@ func (m *HTTPGetAction) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } + if m.Protocol != nil { + l = len(*m.Protocol) + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -16892,6 +17330,9 @@ func (m *KeyToPath) Size() (n int) { if m.Mode != nil { n += 1 + sovGenerated(uint64(*m.Mode)) } + if m.User != nil { + n += 1 + sovGenerated(uint64(*m.User)) + } return n } @@ -17296,6 +17737,40 @@ func (m *NodeAffinity) Size() (n int) { return n } +func (m *NodeAllocatableMappedResources) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.Quantity != nil { + l = m.Quantity.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableOverheadResources) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.PerPod != nil { + l = m.PerPod.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.PerContainer != nil { + l = m.PerContainer.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + func (m *NodeAllocatableResourceClaimStatus) Size() (n int) { if m == nil { return 0 @@ -17310,13 +17785,16 @@ func (m *NodeAllocatableResourceClaimStatus) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } - if len(m.Resources) > 0 { - for k, v := range m.Resources { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + if len(m.Mapping) > 0 { + for _, e := range m.Mapping { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.Overhead) > 0 { + for _, e := range m.Overhead { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) } } return n @@ -17419,6 +17897,21 @@ func (m *NodeList) Size() (n int) { return n } +func (m *NodePodPreemptionPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.DisableResizePreemption) > 0 { + for _, s := range m.DisableResizePreemption { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *NodeProxyOptions) Size() (n int) { if m == nil { return 0 @@ -17544,6 +18037,10 @@ func (m *NodeSpec) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } + if m.PodPreemptionPolicy != nil { + l = m.PodPreemptionPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -17672,6 +18169,9 @@ func (m *NodeSystemInfo) Size() (n int) { l = m.Swap.Size() n += 1 + l + sovGenerated(uint64(l)) } + if m.RunningInUserNamespace != nil { + n += 2 + } return n } @@ -17876,6 +18376,10 @@ func (m *PersistentVolumeClaimStatus) Size() (n int) { l = m.ModifyVolumeStatus.Size() n += 1 + l + sovGenerated(uint64(l)) } + if m.HealthStatus != nil { + l = m.HealthStatus.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -18238,6 +18742,9 @@ func (m *PodCertificateProjection) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if m.User != nil { + n += 1 + sovGenerated(uint64(*m.User)) + } return n } @@ -18751,6 +19258,12 @@ func (m *PodSpec) Size() (n int) { l = m.SchedulingGroup.Size() n += 2 + l + sovGenerated(uint64(l)) } + if len(m.EvictionResponders) > 0 { + for _, e := range m.EvictionResponders { + l = e.Size() + n += 2 + l + sovGenerated(uint64(l)) + } + } return n } @@ -18846,19 +19359,12 @@ func (m *PodStatus) Size() (n int) { n += 2 + l + sovGenerated(uint64(l)) } } - return n -} - -func (m *PodStatusResult) Size() (n int) { - if m == nil { - return 0 + if len(m.VolumeHealth) > 0 { + for _, e := range m.VolumeHealth { + l = e.Size() + n += 2 + l + sovGenerated(uint64(l)) + } } - var l int - _ = l - l = m.ObjectMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Status.Size() - n += 1 + l + sovGenerated(uint64(l)) return n } @@ -18905,6 +19411,25 @@ func (m *PodTemplateSpec) Size() (n int) { return n } +func (m *PodVolumeHealth) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.HealthConditions) > 0 { + for _, e := range m.HealthConditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = m.LastTransitionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *PortStatus) Size() (n int) { if m == nil { return 0 @@ -19036,6 +19561,9 @@ func (m *ProjectedVolumeSource) Size() (n int) { if m.DefaultMode != nil { n += 1 + sovGenerated(uint64(*m.DefaultMode)) } + if m.DefaultUser != nil { + n += 1 + sovGenerated(uint64(*m.DefaultUser)) + } return n } @@ -19674,6 +20202,9 @@ func (m *SecretVolumeSource) Size() (n int) { if m.Optional != nil { n += 2 } + if m.DefaultUser != nil { + n += 1 + sovGenerated(uint64(*m.DefaultUser)) + } return n } @@ -19810,6 +20341,9 @@ func (m *ServiceAccountTokenProjection) Size() (n int) { } l = len(m.Path) n += 1 + l + sovGenerated(uint64(l)) + if m.User != nil { + n += 1 + sovGenerated(uint64(*m.User)) + } return n } @@ -20222,6 +20756,38 @@ func (m *VolumeDevice) Size() (n int) { return n } +func (m *VolumeHealthCondition) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Status) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *VolumeHealthStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.HealthConditions) > 0 { + for _, e := range m.HealthConditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = m.LastTransitionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *VolumeMount) Size() (n int) { if m == nil { return 0 @@ -20245,6 +20811,12 @@ func (m *VolumeMount) Size() (n int) { l = len(*m.RecursiveReadOnly) n += 1 + l + sovGenerated(uint64(l)) } + if len(m.BindMountOptions) > 0 { + for _, s := range m.BindMountOptions { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -20797,6 +21369,7 @@ func (this *ClusterTrustBundleProjection) String() string { `LabelSelector:` + strings.Replace(fmt.Sprintf("%v", this.LabelSelector), "LabelSelector", "v1.LabelSelector", 1) + `,`, `Path:` + fmt.Sprintf("%v", this.Path) + `,`, `Optional:` + valueToStringGenerated(this.Optional) + `,`, + `User:` + valueToStringGenerated(this.User) + `,`, `}`, }, "") return s @@ -20963,6 +21536,7 @@ func (this *ConfigMapVolumeSource) String() string { `Items:` + repeatedStringForItems + `,`, `DefaultMode:` + valueToStringGenerated(this.DefaultMode) + `,`, `Optional:` + valueToStringGenerated(this.Optional) + `,`, + `DefaultUser:` + valueToStringGenerated(this.DefaultUser) + `,`, `}`, }, "") return s @@ -21243,6 +21817,7 @@ func (this *DownwardAPIVolumeFile) String() string { `FieldRef:` + strings.Replace(this.FieldRef.String(), "ObjectFieldSelector", "ObjectFieldSelector", 1) + `,`, `ResourceFieldRef:` + strings.Replace(this.ResourceFieldRef.String(), "ResourceFieldSelector", "ResourceFieldSelector", 1) + `,`, `Mode:` + valueToStringGenerated(this.Mode) + `,`, + `User:` + valueToStringGenerated(this.User) + `,`, `}`, }, "") return s @@ -21259,6 +21834,7 @@ func (this *DownwardAPIVolumeSource) String() string { s := strings.Join([]string{`&DownwardAPIVolumeSource{`, `Items:` + repeatedStringForItems + `,`, `DefaultMode:` + valueToStringGenerated(this.DefaultMode) + `,`, + `DefaultUser:` + valueToStringGenerated(this.DefaultUser) + `,`, `}`, }, "") return s @@ -21270,6 +21846,7 @@ func (this *EmptyDirVolumeSource) String() string { s := strings.Join([]string{`&EmptyDirVolumeSource{`, `Medium:` + fmt.Sprintf("%v", this.Medium) + `,`, `SizeLimit:` + strings.Replace(fmt.Sprintf("%v", this.SizeLimit), "Quantity", "resource.Quantity", 1) + `,`, + `Mode:` + valueToStringGenerated(this.Mode) + `,`, `}`, }, "") return s @@ -21549,6 +22126,17 @@ func (this *EventSource) String() string { }, "") return s } +func (this *EvictionResponder) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EvictionResponder{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `}`, + }, "") + return s +} func (this *ExecAction) String() string { if this == nil { return "nil" @@ -21665,6 +22253,7 @@ func (this *GRPCAction) String() string { s := strings.Join([]string{`&GRPCAction{`, `Port:` + fmt.Sprintf("%v", this.Port) + `,`, `Service:` + valueToStringGenerated(this.Service) + `,`, + `Mode:` + valueToStringGenerated(this.Mode) + `,`, `}`, }, "") return s @@ -21721,6 +22310,7 @@ func (this *HTTPGetAction) String() string { `Host:` + fmt.Sprintf("%v", this.Host) + `,`, `Scheme:` + fmt.Sprintf("%v", this.Scheme) + `,`, `HTTPHeaders:` + repeatedStringForHTTPHeaders + `,`, + `Protocol:` + valueToStringGenerated(this.Protocol) + `,`, `}`, }, "") return s @@ -21837,6 +22427,7 @@ func (this *KeyToPath) String() string { `Key:` + fmt.Sprintf("%v", this.Key) + `,`, `Path:` + fmt.Sprintf("%v", this.Path) + `,`, `Mode:` + valueToStringGenerated(this.Mode) + `,`, + `User:` + valueToStringGenerated(this.User) + `,`, `}`, }, "") return s @@ -22185,24 +22776,48 @@ func (this *NodeAffinity) String() string { }, "") return s } +func (this *NodeAllocatableMappedResources) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableMappedResources{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Quantity:` + strings.Replace(fmt.Sprintf("%v", this.Quantity), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableOverheadResources) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableOverheadResources{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `PerPod:` + strings.Replace(fmt.Sprintf("%v", this.PerPod), "Quantity", "resource.Quantity", 1) + `,`, + `PerContainer:` + strings.Replace(fmt.Sprintf("%v", this.PerContainer), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} func (this *NodeAllocatableResourceClaimStatus) String() string { if this == nil { return "nil" } - keysForResources := make([]string, 0, len(this.Resources)) - for k := range this.Resources { - keysForResources = append(keysForResources, string(k)) + repeatedStringForMapping := "[]NodeAllocatableMappedResources{" + for _, f := range this.Mapping { + repeatedStringForMapping += strings.Replace(strings.Replace(f.String(), "NodeAllocatableMappedResources", "NodeAllocatableMappedResources", 1), `&`, ``, 1) + "," } - sort.Strings(keysForResources) - mapStringForResources := "map[ResourceName]resource.Quantity{" - for _, k := range keysForResources { - mapStringForResources += fmt.Sprintf("%v: %v,", k, this.Resources[ResourceName(k)]) + repeatedStringForMapping += "}" + repeatedStringForOverhead := "[]NodeAllocatableOverheadResources{" + for _, f := range this.Overhead { + repeatedStringForOverhead += strings.Replace(strings.Replace(f.String(), "NodeAllocatableOverheadResources", "NodeAllocatableOverheadResources", 1), `&`, ``, 1) + "," } - mapStringForResources += "}" + repeatedStringForOverhead += "}" s := strings.Join([]string{`&NodeAllocatableResourceClaimStatus{`, `ResourceClaimName:` + fmt.Sprintf("%v", this.ResourceClaimName) + `,`, `Containers:` + fmt.Sprintf("%v", this.Containers) + `,`, - `Resources:` + mapStringForResources + `,`, + `Mapping:` + repeatedStringForMapping + `,`, + `Overhead:` + repeatedStringForOverhead + `,`, `}`, }, "") return s @@ -22281,6 +22896,16 @@ func (this *NodeList) String() string { }, "") return s } +func (this *NodePodPreemptionPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodePodPreemptionPolicy{`, + `DisableResizePreemption:` + fmt.Sprintf("%v", this.DisableResizePreemption) + `,`, + `}`, + }, "") + return s +} func (this *NodeProxyOptions) String() string { if this == nil { return "nil" @@ -22378,6 +23003,7 @@ func (this *NodeSpec) String() string { `Taints:` + repeatedStringForTaints + `,`, `ConfigSource:` + strings.Replace(this.ConfigSource.String(), "NodeConfigSource", "NodeConfigSource", 1) + `,`, `PodCIDRs:` + fmt.Sprintf("%v", this.PodCIDRs) + `,`, + `PodPreemptionPolicy:` + strings.Replace(this.PodPreemptionPolicy.String(), "NodePodPreemptionPolicy", "NodePodPreemptionPolicy", 1) + `,`, `}`, }, "") return s @@ -22476,6 +23102,7 @@ func (this *NodeSystemInfo) String() string { `OperatingSystem:` + fmt.Sprintf("%v", this.OperatingSystem) + `,`, `Architecture:` + fmt.Sprintf("%v", this.Architecture) + `,`, `Swap:` + strings.Replace(this.Swap.String(), "NodeSwapStatus", "NodeSwapStatus", 1) + `,`, + `RunningInUserNamespace:` + valueToStringGenerated(this.RunningInUserNamespace) + `,`, `}`, }, "") return s @@ -22628,6 +23255,7 @@ func (this *PersistentVolumeClaimStatus) String() string { `AllocatedResourceStatuses:` + mapStringForAllocatedResourceStatuses + `,`, `CurrentVolumeAttributesClassName:` + valueToStringGenerated(this.CurrentVolumeAttributesClassName) + `,`, `ModifyVolumeStatus:` + strings.Replace(this.ModifyVolumeStatus.String(), "ModifyVolumeStatus", "ModifyVolumeStatus", 1) + `,`, + `HealthStatus:` + strings.Replace(this.HealthStatus.String(), "VolumeHealthStatus", "VolumeHealthStatus", 1) + `,`, `}`, }, "") return s @@ -22859,6 +23487,7 @@ func (this *PodCertificateProjection) String() string { `KeyPath:` + fmt.Sprintf("%v", this.KeyPath) + `,`, `CertificateChainPath:` + fmt.Sprintf("%v", this.CertificateChainPath) + `,`, `UserAnnotations:` + mapStringForUserAnnotations + `,`, + `User:` + valueToStringGenerated(this.User) + `,`, `}`, }, "") return s @@ -23162,6 +23791,11 @@ func (this *PodSpec) String() string { repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodResourceClaim", "PodResourceClaim", 1), `&`, ``, 1) + "," } repeatedStringForResourceClaims += "}" + repeatedStringForEvictionResponders := "[]EvictionResponder{" + for _, f := range this.EvictionResponders { + repeatedStringForEvictionResponders += strings.Replace(strings.Replace(f.String(), "EvictionResponder", "EvictionResponder", 1), `&`, ``, 1) + "," + } + repeatedStringForEvictionResponders += "}" keysForNodeSelector := make([]string, 0, len(this.NodeSelector)) for k := range this.NodeSelector { keysForNodeSelector = append(keysForNodeSelector, k) @@ -23225,6 +23859,7 @@ func (this *PodSpec) String() string { `Resources:` + strings.Replace(this.Resources.String(), "ResourceRequirements", "ResourceRequirements", 1) + `,`, `HostnameOverride:` + valueToStringGenerated(this.HostnameOverride) + `,`, `SchedulingGroup:` + strings.Replace(this.SchedulingGroup.String(), "PodSchedulingGroup", "PodSchedulingGroup", 1) + `,`, + `EvictionResponders:` + repeatedStringForEvictionResponders + `,`, `}`, }, "") return s @@ -23273,6 +23908,11 @@ func (this *PodStatus) String() string { repeatedStringForNodeAllocatableResourceClaimStatuses += strings.Replace(strings.Replace(f.String(), "NodeAllocatableResourceClaimStatus", "NodeAllocatableResourceClaimStatus", 1), `&`, ``, 1) + "," } repeatedStringForNodeAllocatableResourceClaimStatuses += "}" + repeatedStringForVolumeHealth := "[]PodVolumeHealth{" + for _, f := range this.VolumeHealth { + repeatedStringForVolumeHealth += strings.Replace(strings.Replace(f.String(), "PodVolumeHealth", "PodVolumeHealth", 1), `&`, ``, 1) + "," + } + repeatedStringForVolumeHealth += "}" keysForAllocatedResources := make([]string, 0, len(this.AllocatedResources)) for k := range this.AllocatedResources { keysForAllocatedResources = append(keysForAllocatedResources, string(k)) @@ -23305,17 +23945,7 @@ func (this *PodStatus) String() string { `AllocatedResources:` + mapStringForAllocatedResources + `,`, `Resources:` + strings.Replace(this.Resources.String(), "ResourceRequirements", "ResourceRequirements", 1) + `,`, `NodeAllocatableResourceClaimStatuses:` + repeatedStringForNodeAllocatableResourceClaimStatuses + `,`, - `}`, - }, "") - return s -} -func (this *PodStatusResult) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PodStatusResult{`, - `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodStatus", "PodStatus", 1), `&`, ``, 1) + `,`, + `VolumeHealth:` + repeatedStringForVolumeHealth + `,`, `}`, }, "") return s @@ -23358,6 +23988,23 @@ func (this *PodTemplateSpec) String() string { }, "") return s } +func (this *PodVolumeHealth) String() string { + if this == nil { + return "nil" + } + repeatedStringForHealthConditions := "[]VolumeHealthCondition{" + for _, f := range this.HealthConditions { + repeatedStringForHealthConditions += strings.Replace(strings.Replace(f.String(), "VolumeHealthCondition", "VolumeHealthCondition", 1), `&`, ``, 1) + "," + } + repeatedStringForHealthConditions += "}" + s := strings.Join([]string{`&PodVolumeHealth{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `HealthConditions:` + repeatedStringForHealthConditions + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *PortStatus) String() string { if this == nil { return "nil" @@ -23457,6 +24104,7 @@ func (this *ProjectedVolumeSource) String() string { s := strings.Join([]string{`&ProjectedVolumeSource{`, `Sources:` + repeatedStringForSources + `,`, `DefaultMode:` + valueToStringGenerated(this.DefaultMode) + `,`, + `DefaultUser:` + valueToStringGenerated(this.DefaultUser) + `,`, `}`, }, "") return s @@ -23980,6 +24628,7 @@ func (this *SecretVolumeSource) String() string { `Items:` + repeatedStringForItems + `,`, `DefaultMode:` + valueToStringGenerated(this.DefaultMode) + `,`, `Optional:` + valueToStringGenerated(this.Optional) + `,`, + `DefaultUser:` + valueToStringGenerated(this.DefaultUser) + `,`, `}`, }, "") return s @@ -24074,6 +24723,7 @@ func (this *ServiceAccountTokenProjection) String() string { `Audience:` + fmt.Sprintf("%v", this.Audience) + `,`, `ExpirationSeconds:` + valueToStringGenerated(this.ExpirationSeconds) + `,`, `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `User:` + valueToStringGenerated(this.User) + `,`, `}`, }, "") return s @@ -24366,6 +25016,34 @@ func (this *VolumeDevice) String() string { }, "") return s } +func (this *VolumeHealthCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&VolumeHealthCondition{`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *VolumeHealthStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForHealthConditions := "[]VolumeHealthCondition{" + for _, f := range this.HealthConditions { + repeatedStringForHealthConditions += strings.Replace(strings.Replace(f.String(), "VolumeHealthCondition", "VolumeHealthCondition", 1), `&`, ``, 1) + "," + } + repeatedStringForHealthConditions += "}" + s := strings.Join([]string{`&VolumeHealthStatus{`, + `HealthConditions:` + repeatedStringForHealthConditions + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *VolumeMount) String() string { if this == nil { return "nil" @@ -24378,6 +25056,7 @@ func (this *VolumeMount) String() string { `MountPropagation:` + valueToStringGenerated(this.MountPropagation) + `,`, `SubPathExpr:` + fmt.Sprintf("%v", this.SubPathExpr) + `,`, `RecursiveReadOnly:` + valueToStringGenerated(this.RecursiveReadOnly) + `,`, + `BindMountOptions:` + fmt.Sprintf("%v", this.BindMountOptions) + `,`, `}`, }, "") return s @@ -27769,6 +28448,26 @@ func (m *ClusterTrustBundleProjection) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.Optional = &b + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.User = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -29403,6 +30102,26 @@ func (m *ConfigMapVolumeSource) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.Optional = &b + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultUser", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.DefaultUser = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -32698,6 +33417,26 @@ func (m *DownwardAPIVolumeFile) Unmarshal(dAtA []byte) error { } } m.Mode = &v + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.User = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -32802,6 +33541,26 @@ func (m *DownwardAPIVolumeSource) Unmarshal(dAtA []byte) error { } } m.DefaultMode = &v + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultUser", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.DefaultUser = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -32920,6 +33679,26 @@ func (m *EmptyDirVolumeSource) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Mode = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -36125,6 +36904,108 @@ func (m *EventSource) Unmarshal(dAtA []byte) error { } return nil } +func (m *EvictionResponder) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvictionResponder: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvictionResponder: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *ExecAction) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -37502,6 +38383,39 @@ func (m *GRPCAction) Unmarshal(dAtA []byte) error { s := string(dAtA[iNdEx:postIndex]) m.Service = &s iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := GRPCProbeMode(dAtA[iNdEx:postIndex]) + m.Mode = &s + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -38162,6 +39076,39 @@ func (m *HTTPGetAction) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := HTTPProtocol(dAtA[iNdEx:postIndex]) + m.Protocol = &s + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -39633,6 +40580,26 @@ func (m *KeyToPath) Unmarshal(dAtA []byte) error { } } m.Mode = &v + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.User = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -42489,8 +43456,206 @@ func (m *NamespaceList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, Namespace{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Items = append(m.Items, Namespace{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NamespaceSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NamespaceSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NamespaceSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Finalizers", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Finalizers = append(m.Finalizers, FinalizerName(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NamespaceStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NamespaceStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Phase = NamespacePhase(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, NamespaceCondition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -42515,7 +43680,7 @@ func (m *NamespaceList) Unmarshal(dAtA []byte) error { } return nil } -func (m *NamespaceSpec) Unmarshal(dAtA []byte) error { +func (m *Node) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -42538,17 +43703,17 @@ func (m *NamespaceSpec) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NamespaceSpec: wiretype end group for non-group") + return fmt.Errorf("proto: Node: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NamespaceSpec: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Node: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Finalizers", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -42558,23 +43723,90 @@ func (m *NamespaceSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Finalizers = append(m.Finalizers, FinalizerName(dAtA[iNdEx:postIndex])) + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -42597,7 +43829,7 @@ func (m *NamespaceSpec) Unmarshal(dAtA []byte) error { } return nil } -func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { +func (m *NodeAddress) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -42620,15 +43852,15 @@ func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NamespaceStatus: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAddress: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NamespaceStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAddress: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -42656,13 +43888,13 @@ func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Phase = NamespacePhase(dAtA[iNdEx:postIndex]) + m.Type = NodeAddressType(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -42672,25 +43904,23 @@ func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Conditions = append(m.Conditions, NamespaceCondition{}) - if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Address = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -42713,7 +43943,7 @@ func (m *NamespaceStatus) Unmarshal(dAtA []byte) error { } return nil } -func (m *Node) Unmarshal(dAtA []byte) error { +func (m *NodeAffinity) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -42736,15 +43966,15 @@ func (m *Node) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Node: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAffinity: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Node: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAffinity: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field RequiredDuringSchedulingIgnoredDuringExecution", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -42771,46 +44001,16 @@ func (m *Node) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF + if m.RequiredDuringSchedulingIgnoredDuringExecution == nil { + m.RequiredDuringSchedulingIgnoredDuringExecution = &NodeSelector{} } - if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.RequiredDuringSchedulingIgnoredDuringExecution.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 3: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PreferredDuringSchedulingIgnoredDuringExecution", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -42837,7 +44037,8 @@ func (m *Node) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.PreferredDuringSchedulingIgnoredDuringExecution = append(m.PreferredDuringSchedulingIgnoredDuringExecution, PreferredSchedulingTerm{}) + if err := m.PreferredDuringSchedulingIgnoredDuringExecution[len(m.PreferredDuringSchedulingIgnoredDuringExecution)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -42862,7 +44063,7 @@ func (m *Node) Unmarshal(dAtA []byte) error { } return nil } -func (m *NodeAddress) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableMappedResources) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -42885,15 +44086,15 @@ func (m *NodeAddress) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NodeAddress: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableMappedResources: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NodeAddress: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableMappedResources: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -42921,13 +44122,13 @@ func (m *NodeAddress) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Type = NodeAddressType(dAtA[iNdEx:postIndex]) + m.Name = ResourceName(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Quantity", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -42937,23 +44138,27 @@ func (m *NodeAddress) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Address = string(dAtA[iNdEx:postIndex]) + if m.Quantity == nil { + m.Quantity = &resource.Quantity{} + } + if err := m.Quantity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -42976,7 +44181,7 @@ func (m *NodeAddress) Unmarshal(dAtA []byte) error { } return nil } -func (m *NodeAffinity) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableOverheadResources) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -42999,15 +44204,83 @@ func (m *NodeAffinity) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NodeAffinity: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableOverheadResources: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NodeAffinity: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableOverheadResources: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequiredDuringSchedulingIgnoredDuringExecution", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = ResourceName(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PerPod", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PerPod == nil { + m.PerPod = &resource.Quantity{} + } + if err := m.PerPod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PerContainer", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -43034,44 +44307,10 @@ func (m *NodeAffinity) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.RequiredDuringSchedulingIgnoredDuringExecution == nil { - m.RequiredDuringSchedulingIgnoredDuringExecution = &NodeSelector{} - } - if err := m.RequiredDuringSchedulingIgnoredDuringExecution.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreferredDuringSchedulingIgnoredDuringExecution", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF + if m.PerContainer == nil { + m.PerContainer = &resource.Quantity{} } - m.PreferredDuringSchedulingIgnoredDuringExecution = append(m.PreferredDuringSchedulingIgnoredDuringExecution, PreferredSchedulingTerm{}) - if err := m.PreferredDuringSchedulingIgnoredDuringExecution[len(m.PreferredDuringSchedulingIgnoredDuringExecution)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.PerContainer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -43189,9 +44428,9 @@ func (m *NodeAllocatableResourceClaimStatus) Unmarshal(dAtA []byte) error { } m.Containers = append(m.Containers, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 3: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Mapping", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -43218,105 +44457,44 @@ func (m *NodeAllocatableResourceClaimStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Resources == nil { - m.Resources = make(map[ResourceName]resource.Quantity) + m.Mapping = append(m.Mapping, NodeAllocatableMappedResources{}) + if err := m.Mapping[len(m.Mapping)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - var mapkey ResourceName - mapvalue := &resource.Quantity{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Overhead", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = ResourceName(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &resource.Quantity{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy + if iNdEx >= l { + return io.ErrUnexpectedEOF } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Overhead = append(m.Overhead, NodeAllocatableOverheadResources{}) + if err := m.Overhead[len(m.Overhead)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.Resources[ResourceName(mapkey)] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -44130,6 +45308,88 @@ func (m *NodeList) Unmarshal(dAtA []byte) error { } return nil } +func (m *NodePodPreemptionPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodePodPreemptionPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodePodPreemptionPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisableResizePreemption", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DisableResizePreemption = append(m.DisableResizePreemption, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *NodeProxyOptions) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -45017,6 +46277,42 @@ func (m *NodeSpec) Unmarshal(dAtA []byte) error { } m.PodCIDRs = append(m.PodCIDRs, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodPreemptionPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PodPreemptionPolicy == nil { + m.PodPreemptionPolicy = &NodePodPreemptionPolicy{} + } + if err := m.PodPreemptionPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -46205,6 +47501,27 @@ func (m *NodeSystemInfo) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 12: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RunningInUserNamespace", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.RunningInUserNamespace = &b default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -48208,6 +49525,42 @@ func (m *PersistentVolumeClaimStatus) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field HealthStatus", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.HealthStatus == nil { + m.HealthStatus = &VolumeHealthStatus{} + } + if err := m.HealthStatus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -51313,6 +52666,26 @@ func (m *PodCertificateProjection) Unmarshal(dAtA []byte) error { } m.UserAnnotations[mapkey] = mapvalue iNdEx = postIndex + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.User = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -55517,6 +56890,40 @@ func (m *PodSpec) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 44: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EvictionResponders", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.EvictionResponders = append(m.EvictionResponders, EvictionResponder{}) + if err := m.EvictionResponders[len(m.EvictionResponders)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -56351,6 +57758,40 @@ func (m *PodStatus) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 22: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VolumeHealth", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.VolumeHealth = append(m.VolumeHealth, PodVolumeHealth{}) + if err := m.VolumeHealth[len(m.VolumeHealth)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -56372,7 +57813,7 @@ func (m *PodStatus) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodStatusResult) Unmarshal(dAtA []byte) error { +func (m *PodTemplate) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -56395,10 +57836,10 @@ func (m *PodStatusResult) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodStatusResult: wiretype end group for non-group") + return fmt.Errorf("proto: PodTemplate: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodStatusResult: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PodTemplate: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -56436,7 +57877,7 @@ func (m *PodStatusResult) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Template", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -56463,7 +57904,7 @@ func (m *PodStatusResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Template.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -56488,7 +57929,7 @@ func (m *PodStatusResult) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodTemplate) Unmarshal(dAtA []byte) error { +func (m *PodTemplateList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -56511,10 +57952,127 @@ func (m *PodTemplate) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodTemplate: wiretype end group for non-group") + return fmt.Errorf("proto: PodTemplateList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PodTemplateList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, PodTemplate{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodTemplateSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodTemplateSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodTemplateSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -56552,7 +58110,7 @@ func (m *PodTemplate) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Template", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -56579,7 +58137,7 @@ func (m *PodTemplate) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Template.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -56604,7 +58162,7 @@ func (m *PodTemplate) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodTemplateList) Unmarshal(dAtA []byte) error { +func (m *PodVolumeHealth) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -56627,17 +58185,17 @@ func (m *PodTemplateList) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodTemplateList: wiretype end group for non-group") + return fmt.Errorf("proto: PodVolumeHealth: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodTemplateList: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PodVolumeHealth: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -56647,28 +58205,27 @@ func (m *PodTemplateList) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field HealthConditions", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -56695,97 +58252,14 @@ func (m *PodTemplateList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, PodTemplate{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.HealthConditions = append(m.HealthConditions, VolumeHealthCondition{}) + if err := m.HealthConditions[len(m.HealthConditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PodTemplateSpec) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PodTemplateSpec: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PodTemplateSpec: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -56812,7 +58286,7 @@ func (m *PodTemplateSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -57945,6 +59419,26 @@ func (m *ProjectedVolumeSource) Unmarshal(dAtA []byte) error { } } m.DefaultMode = &v + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultUser", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.DefaultUser = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -63895,6 +65389,26 @@ func (m *SecretVolumeSource) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.Optional = &b + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultUser", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.DefaultUser = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -64937,6 +66451,26 @@ func (m *ServiceAccountTokenProjection) Unmarshal(dAtA []byte) error { } m.Path = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.User = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -68111,11 +69645,158 @@ func (m *TypedObjectReference) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } s := string(dAtA[iNdEx:postIndex]) - m.APIGroup = &s + m.APIGroup = &s + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Kind = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.Namespace = &s iNdEx = postIndex - case 2: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Volume) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Volume: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Volume: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -68143,9 +69824,92 @@ func (m *TypedObjectReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Kind = string(dAtA[iNdEx:postIndex]) + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VolumeSource", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.VolumeSource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *VolumeDevice) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: VolumeDevice: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: VolumeDevice: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } @@ -68177,9 +69941,9 @@ func (m *TypedObjectReference) Unmarshal(dAtA []byte) error { } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DevicePath", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -68207,8 +69971,7 @@ func (m *TypedObjectReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.Namespace = &s + m.DevicePath = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -68231,7 +69994,7 @@ func (m *TypedObjectReference) Unmarshal(dAtA []byte) error { } return nil } -func (m *Volume) Unmarshal(dAtA []byte) error { +func (m *VolumeHealthCondition) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -68254,15 +70017,15 @@ func (m *Volume) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Volume: wiretype end group for non-group") + return fmt.Errorf("proto: VolumeHealthCondition: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Volume: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: VolumeHealthCondition: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -68290,13 +70053,13 @@ func (m *Volume) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.Status = VolumeHealthStatusType(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VolumeSource", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -68306,24 +70069,55 @@ func (m *Volume) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.VolumeSource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + m.Reason = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -68346,7 +70140,7 @@ func (m *Volume) Unmarshal(dAtA []byte) error { } return nil } -func (m *VolumeDevice) Unmarshal(dAtA []byte) error { +func (m *VolumeHealthStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -68369,17 +70163,17 @@ func (m *VolumeDevice) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: VolumeDevice: wiretype end group for non-group") + return fmt.Errorf("proto: VolumeHealthStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: VolumeDevice: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: VolumeHealthStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field HealthConditions", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -68389,29 +70183,31 @@ func (m *VolumeDevice) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.HealthConditions = append(m.HealthConditions, VolumeHealthCondition{}) + if err := m.HealthConditions[len(m.HealthConditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DevicePath", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -68421,23 +70217,24 @@ func (m *VolumeDevice) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.DevicePath = string(dAtA[iNdEx:postIndex]) + if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -68703,6 +70500,38 @@ func (m *VolumeMount) Unmarshal(dAtA []byte) error { s := RecursiveReadOnlyMode(dAtA[iNdEx:postIndex]) m.RecursiveReadOnly = &s iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BindMountOptions", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.BindMountOptions = append(m.BindMountOptions, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/core/v1/generated.proto b/constraint/vendor/k8s.io/api/core/v1/generated.proto index ba4f80e5e..878555a6e 100644 --- a/constraint/vendor/k8s.io/api/core/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/core/v1/generated.proto @@ -185,6 +185,7 @@ message Binding { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // The target object that you want to bind to the standard object. @@ -466,6 +467,13 @@ message ClusterTrustBundleProjection { // Relative path from the volume root to write the bundle. optional string path = 4; + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 user = 6; } // Information about the condition of a component. @@ -495,6 +503,7 @@ message ComponentStatus { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // List of component conditions observed @@ -547,6 +556,8 @@ message ConfigMap { // the Data field, this is enforced during validation process. // Using this field will require 1.10+ apiserver and // kubelet. + // Note: BinaryData keys are not currently propagated to container env vars + // via ConfigMapKeyRef or ConfigMapRef env sources; only Data keys are used. // +optional map binaryData = 3; } @@ -556,6 +567,7 @@ message ConfigMap { // // The contents of the target ConfigMap's Data field will represent the // key-value pairs as environment variables. +// Keys in the BinaryData field are not currently propagated to container env vars. message ConfigMapEnvSource { // The ConfigMap to select from. optional LocalObjectReference localObjectReference = 1; @@ -571,7 +583,8 @@ message ConfigMapKeySelector { // The ConfigMap to select from. optional LocalObjectReference localObjectReference = 1; - // The key to select. + // The key to select from the ConfigMap's Data field. + // Keys in the BinaryData field are not currently propagated to container env vars. optional string key = 2; // Specify whether the ConfigMap or its key must be defined @@ -674,6 +687,13 @@ message ConfigMapVolumeSource { // optional specify whether the ConfigMap or its keys must be defined // +optional optional bool optional = 4; + + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 defaultUser = 5; } // A single application container that you want to run within a pod. @@ -1216,6 +1236,13 @@ message DownwardAPIVolumeFile { // mode, like fsGroup, and the result can be other mode bits set. // +optional optional int32 mode = 4; + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 user = 5; } // DownwardAPIVolumeSource represents a volume containing downward API info. @@ -1236,6 +1263,13 @@ message DownwardAPIVolumeSource { // mode, like fsGroup, and the result can be other mode bits set. // +optional optional int32 defaultMode = 2; + + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 defaultUser = 3; } // Represents an empty directory for a pod. @@ -1256,6 +1290,18 @@ message EmptyDirVolumeSource { // More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir // +optional optional .k8s.io.apimachinery.pkg.api.resource.Quantity sizeLimit = 2; + + // mode specifies the permission bits for the emptyDir directory, in numeric + // notation (e.g., 0755, 01777). Must be a value between 0000 and 01777. + // If not specified, defaults to 0777. + // This might be in conflict with other options that affect the file + // mode, like fsGroup. If fsGroup is specified, the fsGroup permissions + // will override the mode specified here. + // This field has no effect on Windows. + // This field is alpha and requires EmptyDirVolumeMode featuregate to be enabled. + // +featureGate=EmptyDirVolumeMode + // +optional + optional int32 mode = 3; } // EndpointAddress is a tuple that describes single IP address. @@ -1807,6 +1853,43 @@ message EventSource { optional string host = 2; } +// EvictionResponder allows you to specify the responder reacting to an Eviction. +// Responders should observe and communicate through the Eviction Resource API to help with +// the graceful eviction of a target (e.g. termination of a pod). +// +structType=atomic +message EvictionResponder { + // name allows you to identify the responder responding to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + // +k8s:customValidation + optional string name = 1; + + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required. + // +required + // +k8s:required + // +k8s:minimum=0 + // +k8s:maximum=100000 + // +k8s:customValidation + optional int32 priority = 2; +} + // ExecAction describes a "run in container" action. message ExecAction { // Command is the command line to execute inside the container, the working directory for the @@ -2001,6 +2084,14 @@ message GRPCAction { // +optional // +default="" optional string service = 2; + + // mode specifies the connection mode for the gRPC health probe. + // Set to "TLS" to use TLS without certificate verification. + // Set to "Plaintext" to use a plaintext (insecure) connection explicitly. + // If not specified, the probe uses a plaintext (insecure) connection. + // +featureGate=GRPCContainerProbeTLS + // +optional + optional string mode = 3; } // Represents a volume that is populated with the contents of a git repository. @@ -2092,6 +2183,12 @@ message HTTPGetAction { // +optional // +listType=atomic repeated HTTPHeader httpHeaders = 5; + + // Protocol selects the wire protocol for the probe connection. + // Nil defaults to HTTP/1.1. + // +optional + // +featureGate=H2CContainerProbe + optional string protocol = 6; } // HTTPHeader describes a custom header to be used in HTTP probes @@ -2303,6 +2400,13 @@ message KeyToPath { // mode, like fsGroup, and the result can be other mode bits set. // +optional optional int32 mode = 3; + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 user = 4; } // Lifecycle describes actions that the management system should take in response to container lifecycle @@ -2557,6 +2661,8 @@ message NFSVolumeSource { // Namespace provides a scope for Names. // Use of multiple namespaces is optional. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/finalize" message Namespace { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -2634,6 +2740,8 @@ message NamespaceStatus { // Node is a worker node in Kubernetes. // Each node will have a unique identifier in the cache (i.e. in etcd). +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/proxy" message Node { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -2686,20 +2794,86 @@ message NodeAffinity { repeated PreferredSchedulingTerm preferredDuringSchedulingIgnoredDuringExecution = 2; } +// NodeAllocatableMappedResources describes mapped node allocatable resource allocations. +message NodeAllocatableMappedResources { + // Name is the name of the resource (e.g., cpu, memory). + // +required + // +k8s:required + optional string name = 1; + + // Quantity is the total node allocatable resource capacity allocated for the claim. + // This claim's allocated devices is shared by all the containers referencing the claim. + // Kubelet adds this value to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. + // +required + // +k8s:required + optional .k8s.io.apimachinery.pkg.api.resource.Quantity quantity = 2; +} + +// NodeAllocatableOverheadResources describes auxiliary overhead resource allocations. +message NodeAllocatableOverheadResources { + // Name is the name of the resource (e.g., cpu, memory). + // +required + // +k8s:required + optional string name = 1; + + // PerPod is the flat overhead quantity allocated per pod. + // Adding to each container limit allows individual containers to utilize the overhead, while the parent pod-level cgroup limit caps the total usage at the pod boundary where the overhead is accounted for exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perPod = 2; + + // PerContainer is the variable overhead quantity applied for each container referencing the claim. + // The container references are recorded in `nodeAllocatableResourceClaimStatuses.containers`. + // The total overhead quantity allocated for the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perContainer = 3; +} + // NodeAllocatableResourceClaimStatus describes the status of node allocatable resources allocated via DRA. message NodeAllocatableResourceClaimStatus { // ResourceClaimName is the resource claim referenced by the pod that resulted in this node allocatable resource allocation. // +required + // +k8s:required optional string resourceClaimName = 1; // Containers lists the names of all containers in this pod that reference the claim. // +optional // +listType=set + // +k8s:optional + // +k8s:listType=set repeated string containers = 2; - // Resources is a map of the node-allocatable resource name to the aggregate quantity allocated to the claim. - // +required - map resources = 3; + // Mapping contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].mapping` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + // +optional + // +patchStrategy=merge + // +patchMergeKey=name + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + repeated NodeAllocatableMappedResources mapping = 4; + + // Overhead contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].overhead` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + // +optional + // +patchStrategy=merge + // +patchMergeKey=name + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + repeated NodeAllocatableOverheadResources overhead = 5; } // NodeCondition contains condition information for a node. @@ -2811,6 +2985,21 @@ message NodeList { repeated Node items = 2; } +// NodePodPreemptionPolicy defines the node-level policies governing preemption for pods on this node. +message NodePodPreemptionPolicy { + // DisableResizePreemption lists the owners (e.g., autoscalers, operators, administrators) + // that have requested to disable scheduler and Kubelet preemption for in-place pod resize on this node. + // If this list is non-empty, resize-induced preemption is disabled on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + // +listType=set + // +k8s:listType=set + // +optional + // +k8s:maxItems=20 + // +k8s:optional + // +k8s:eachVal=+k8s:format=k8s-label-key + repeated string disableResizePreemption = 1; +} + // NodeProxyOptions is the query options to a Node's proxy call. message NodeProxyOptions { // Path is the URL path to use for the current proxy request to node. @@ -2903,6 +3092,9 @@ message NodeSpec { // ID of the node assigned by the cloud provider in the format: :// // +optional + // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:alpha(since: "1.36")=+k8s:update=NoUnset optional string providerID = 3; // Unschedulable controls node schedulability of new pods. By default, node is schedulable. @@ -2923,6 +3115,14 @@ message NodeSpec { // see: https://issues.k8s.io/61966 // +optional optional string externalID = 2; + + // PodPreemptionPolicy controls the node-level preemption behaviors for pods on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + // +featureGate=InPlacePodVerticalScalingSchedulerPreemption + // +optional + // +k8s:optional + // +k8s:ifDisabled(InPlacePodVerticalScalingSchedulerPreemption)=+k8s:forbidden + optional NodePodPreemptionPolicy podPreemptionPolicy = 8; } // NodeStatus is information about the current status of a node. @@ -3059,6 +3259,11 @@ message NodeSystemInfo { // Swap Info reported by the node. optional NodeSwapStatus swap = 11; + + // Whether the node is running in a user namespace. + // +featureGate=KubeletInUserNamespace + // +optional + optional bool runningInUserNamespace = 12; } // ObjectFieldSelector selects an APIVersioned field of an object. @@ -3135,6 +3340,7 @@ message ObjectReference { // PersistentVolume (PV) is a storage resource provisioned by an administrator. // It is analogous to a node. // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes +// +k8s:supportsSubresource="/status" message PersistentVolume { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -3156,6 +3362,7 @@ message PersistentVolume { } // PersistentVolumeClaim is a user's request for and claim to a persistent volume +// +k8s:supportsSubresource="/status" message PersistentVolumeClaim { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -3256,8 +3463,8 @@ message PersistentVolumeClaimSpec { // * An existing PVC (PersistentVolumeClaim) // If the provisioner or an external controller can support the specified data source, // it will create a new volume based on the contents of the specified data source. - // When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, - // and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. + // dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be + // copied to dataSource when dataSourceRef.namespace is not specified. // If the namespace is specified, then dataSourceRef will not be copied to dataSource. // +optional optional TypedLocalObjectReference dataSource = 7; @@ -3283,7 +3490,6 @@ message PersistentVolumeClaimSpec { // specified. // * While dataSource only allows local objects, dataSourceRef allows objects // in any namespaces. - // (Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. // (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled. // +optional optional TypedObjectReference dataSourceRef = 8; @@ -3399,6 +3605,13 @@ message PersistentVolumeClaimStatus { // +featureGate=VolumeAttributesClass // +optional optional ModifyVolumeStatus modifyVolumeStatus = 9; + + // healthStatus contains the latest controller-reported health information + // for the volume bound to this claim. + // +featureGate=CSIVolumeHealth + // +optional + // +k8s:optional + optional VolumeHealthStatus healthStatus = 10; } // PersistentVolumeClaimTemplate is used to produce @@ -3409,6 +3622,7 @@ message PersistentVolumeClaimTemplate { // validation. // // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // The specification for the PersistentVolumeClaim. The entire content is @@ -3676,6 +3890,10 @@ message PhotonPersistentDiskVolumeSource { // Pod is a collection of containers that can run on a host. This resource is created // by clients and scheduled onto hosts. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/ephemeralcontainers" +// +k8s:supportsSubresource="/resize" +// +k8s:supportsSubresource="/eviction" message Pod { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -3931,6 +4149,13 @@ message PodCertificateProjection { // Signers should document the keys and values they support. Signers should // deny requests that contain keys they do not recognize. map userAnnotations = 7; + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 user = 8; } // PodCondition contains details for the current condition of this pod. @@ -4390,11 +4615,8 @@ message PodSecurityContext { // Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes // whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their // CSIDriver instance. Other volumes are always re-labelled recursively. - // "MountOption" value is allowed only when SELinuxMount feature gate is enabled. // - // If not specified and SELinuxMount feature gate is enabled, "MountOption" is used. - // If not specified and SELinuxMount feature gate is disabled, "MountOption" is used for ReadWriteOncePod volumes - // and "Recursive" for all other volumes. + // If not specified, "MountOption" is used. // // This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers. // @@ -4511,7 +4733,6 @@ message PodSpec { // DeprecatedServiceAccount is a deprecated alias for ServiceAccountName. // Deprecated: Use serviceAccountName instead. - // +k8s:conversion-gen=false // +optional optional string serviceAccount = 9; @@ -4532,19 +4753,16 @@ message PodSpec { // When `hostNetwork` is true, specified `hostPort` fields in port definitions must match `containerPort`, // and unspecified `hostPort` fields in port definitions are defaulted to match `containerPort`. // Default to false. - // +k8s:conversion-gen=false // +optional optional bool hostNetwork = 11; // Use the host's pid namespace. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional optional bool hostPID = 12; // Use the host's ipc namespace. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional optional bool hostIPC = 13; @@ -4553,7 +4771,6 @@ message PodSpec { // in the same pod, and the first process in each container will not be assigned PID 1. // HostPID and ShareProcessNamespace cannot both be set. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional optional bool shareProcessNamespace = 27; @@ -4594,6 +4811,7 @@ message PodSpec { // If specified, the pod's tolerations. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional repeated Toleration tolerations = 22; // HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts @@ -4652,6 +4870,8 @@ message PodSpec { // PreemptionPolicy is the Policy for preempting pods with lower priority. // One of Never, PreemptLowerPriority. + // When Priority Admission Controller is enabled, it prevents users from setting + // this field. The admission controller populates this field from PriorityClassName. // Defaults to PreemptLowerPriority if unset. // +optional optional string preemptionPolicy = 31; @@ -4728,7 +4948,6 @@ message PodSpec { // When set to false, a new userns is created for the pod. Setting false is useful for // mitigating container breakout vulnerabilities even allowing users to run their // containers as root without actually having root privileges on the host. - // +k8s:conversion-gen=false // +optional optional bool hostUsers = 37; @@ -4787,7 +5006,6 @@ message PodSpec { // - `hostNetwork` must be set to false. // // This field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters. - // Requires the HostnameOverride feature gate to be enabled. // // +featureGate=HostnameOverride // +optional @@ -4809,6 +5027,34 @@ message PodSpec { // +featureGate=GenericWorkload // +optional optional PodSchedulingGroup schedulingGroup = 43; + + // evictionResponders reference responders that react to Evictions based on EvictionRequests. + // Responders should observe and communicate through the Eviction Resource API to help with + // the graceful termination of a pod. The responders are selected sequentially, according to + // their specified priority. + // + // Responders should periodically report on an eviction progress by updating the + // .status.responders[].heartbeatTime field of the Eviction object. If this field is not updated + // within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the eviction + // is passed over to the next responder with a lower priority. If there is no other responder, + // the last default imperative-eviction.k8s.io/evictor responder with a priority of 100 will + // evict the pod using the imperative Eviction API (pods//eviction subresource). + // + // The maximum length of the responders list is 10. + // Responders are not supported when the pod is part of a PodGroup (.spec.schedulingGroup is set). + // This field can only be set on creation and is immutable afterwards. + // +featureGate=EvictionRequestAPI + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=10 + // +k8s:alpha(since: "1.37")=+k8s:dependentForbidden("schedulingGroup") + repeated EvictionResponder evictionResponders = 44; } // PodStatus represents information about the status of a pod. Status may trail the actual @@ -4993,24 +5239,25 @@ message PodStatus { // Examples include "cpu", "memory", "ephemeral-storage", and hugepages. // +featureGate=DRANodeAllocatableResources // +optional - // +listType=atomic + // +patchStrategy=merge + // +patchMergeKey=resourceClaimName + // +listType=map + // +listMapKey=resourceClaimName + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=resourceClaimName repeated NodeAllocatableResourceClaimStatus nodeAllocatableResourceClaimStatuses = 21; -} -// PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded -message PodStatusResult { - // Standard object's metadata. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // volumeHealth contains node-reported health for each volume the pod is using. + // Populated by the kubelet on the pod's node. + // +featureGate=CSIVolumeHealth // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - - // Most recently observed status of the pod. - // This data may not be up to date. - // Populated by the system. - // Read-only. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional - optional PodStatus status = 2; + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + repeated PodVolumeHealth volumeHealth = 22; } // PodTemplate describes a template for creating copies of a predefined pod. @@ -5042,6 +5289,7 @@ message PodTemplateSpec { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the pod. @@ -5050,6 +5298,35 @@ message PodTemplateSpec { optional PodSpec spec = 2; } +// PodVolumeHealth contains health information for a volume used by a pod, +// reported by the CSI node plugin via the kubelet. +message PodVolumeHealth { + // name matches an entry in pod.spec.volumes. + // +required + // +k8s:required + optional string name = 1; + + // conditions is the set of adverse conditions reported by + // the CSI node plugin for this volume on this node. + // At most 16 conditions may be reported. + // +optional + // +listType=map + // +listMapKey=status + // +patchMergeKey=status + // +patchStrategy=merge + // +listMapKey=reason + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=status + // +k8s:listMapKey=reason + // +k8s:maxItems=16 + repeated VolumeHealthCondition healthConditions = 2; + + // lastTransitionTime is when the current set of conditions first appeared. + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; +} + // PortStatus represents the error condition of a service port message PortStatus { // Port is the port number of the service port of which status is recorded here @@ -5208,6 +5485,13 @@ message ProjectedVolumeSource { // mode, like fsGroup, and the result can be other mode bits set. // +optional optional int32 defaultMode = 2; + + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 defaultUser = 3; } // Represents a Quobyte mount that lasts the lifetime of a pod. @@ -5357,6 +5641,7 @@ message RangeAllocation { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Range is string that identifies the range represented by 'data'. @@ -5372,8 +5657,8 @@ message ReplicationController { // be the same as the Pod(s) that the replication controller manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines the specification of the desired behavior of the replication controller. @@ -5430,18 +5715,18 @@ message ReplicationControllerSpec { // Defaults to 1. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=1 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 replicas = 1; // Minimum number of seconds for which a newly created pod should be ready // without any of its container crashing, for it to be considered available. // Defaults to 0 (pod will be considered available as soon as it is ready) // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 minReadySeconds = 4; // Selector is a label query over pods that should match the Replicas count. @@ -5458,6 +5743,7 @@ message ReplicationControllerSpec { // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional optional PodTemplateSpec template = 3; } @@ -5549,6 +5835,7 @@ message ResourceHealth { } // ResourceQuota sets aggregate quota restrictions enforced per namespace +// +k8s:supportsSubresource="/status" message ResourceQuota { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -5642,8 +5929,13 @@ message ResourceRequirements { // ResourceStatus represents the status of a single resource allocated to a Pod. message ResourceStatus { // Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. - // For DRA resources, the value must be "claim:/". - // When this status is reported about a container, the "claim_name" and "request" must match one of the claims of this container. + // For DRA resources, the value must be "claim:/" when + // container.resources.claims[*].request is set or "claim:" when + // container.resources.claims[*].request is empty. + // For DRA-backed extended resources, "claim:/" is used + // when the claim name and request name are recorded in pod.status.extendedResourceClaimStatus. + // When this status is reported about a container, the "claim_name" and "request" + // must match one of the claims of this container. // +required optional string name = 1; @@ -5854,6 +6146,8 @@ message Secret { // Used to facilitate programmatic handling of secret data. // More info: https://kubernetes.io/docs/concepts/configuration/secret/#secret-types // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable optional string type = 3; } @@ -5970,6 +6264,13 @@ message SecretVolumeSource { // optional field specify whether the Secret or its keys must be defined // +optional optional bool optional = 4; + + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 defaultUser = 5; } // SecurityContext holds security configuration that will be applied to a container. @@ -6076,6 +6377,8 @@ message SerializedReference { // Service is a named abstraction of software service (for example, mysql) consisting of local port // (for example 3306) that the proxy listens on, and the selector that determines which pods // will answer requests sent through the proxy. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/proxy" message Service { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -6169,6 +6472,13 @@ message ServiceAccountTokenProjection { // path is the path relative to the mount point of the file to project the // token into. optional string path = 3; + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + optional int64 user = 4; } // ServiceList holds a list of services. @@ -6511,6 +6821,7 @@ message ServiceStatus { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 2; } @@ -6638,6 +6949,8 @@ message Toleration { // Key is the taint key that the toleration applies to. Empty means match all taint keys. // If the key is empty, operator must be Exists; this combination means to match all values and all keys. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:format=k8s-label-key optional string key = 1; // Operator represents a key's relationship to the value. @@ -6890,6 +7203,57 @@ message VolumeDevice { optional string devicePath = 2; } +// VolumeHealthCondition represents an adverse health condition reported for a volume. +message VolumeHealthCondition { + // status is the machine-parseable health category. + // Possible values: + // - "Inaccessible": the volume cannot be accessed. + // - "DataLoss": data loss has been detected on the volume. + // - "Degraded": the volume is functioning with reduced capability. + // +required + // +k8s:required + optional string status = 1; + + // reason is a brief CamelCase machine-parseable reason. + // Together with status it forms the unique identity of a condition entry. + // Maximum permitted length of a reason is 256 bytes. + // +required + // +k8s:required + // +k8s:maxBytes=256 + optional string reason = 2; + + // message is a human-readable description. + // Maximum permitted length of a message is 1024 bytes. + // +optional + // +k8s:optional + // +k8s:maxBytes=1024 + optional string message = 3; +} + +// VolumeHealthStatus contains health information for a volume reported +// by the CSI controller plugin. +message VolumeHealthStatus { + // conditions is the set of adverse conditions reported by + // the CSI controller plugin. An empty list means no adverse condition. + // At most 16 conditions may be reported. + // +optional + // +listType=map + // +listMapKey=status + // +patchMergeKey=status + // +patchStrategy=merge + // +listMapKey=reason + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=status + // +k8s:listMapKey=reason + // +k8s:maxItems=16 + repeated VolumeHealthCondition healthConditions = 1; + + // lastTransitionTime is when the current set of conditions first appeared. + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 2; +} + // VolumeMount describes a mounting of a Volume within a container. message VolumeMount { // This must match the Name of a Volume. @@ -6919,8 +7283,7 @@ message VolumeMount { // +optional optional string recursiveReadOnly = 7; - // Path within the container at which the volume should be mounted. Must - // not contain ':'. + // Path within the container at which the volume should be mounted. optional string mountPath = 3; // Path within the volume from which the container's volume should be mounted. @@ -6943,6 +7306,17 @@ message VolumeMount { // SubPathExpr and SubPath are mutually exclusive. // +optional optional string subPathExpr = 6; + + // bindMountOptions is the list of additional bind mount options to apply when + // mounting this volume into the container. Allowed values are noexec, + // nodev, and nosuid. These are Linux mount options and have no effect on + // Windows nodes. + // This field is not supported with image volumes. + // This is an alpha field and requires enabling the VolumeBindMountOptions feature gate. + // +featureGate=VolumeBindMountOptions + // +optional + // +listType=set + repeated string bindMountOptions = 8; } // VolumeMountStatus shows status of volume mounts. diff --git a/constraint/vendor/k8s.io/api/core/v1/register.go b/constraint/vendor/k8s.io/api/core/v1/register.go index 1aac0cb41..0a42d182f 100644 --- a/constraint/vendor/k8s.io/api/core/v1/register.go +++ b/constraint/vendor/k8s.io/api/core/v1/register.go @@ -46,7 +46,6 @@ func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &Pod{}, &PodList{}, - &PodStatusResult{}, &PodTemplate{}, &PodTemplateList{}, &ReplicationController{}, diff --git a/constraint/vendor/k8s.io/api/core/v1/types.go b/constraint/vendor/k8s.io/api/core/v1/types.go index ac0494f3c..90b09fb9b 100644 --- a/constraint/vendor/k8s.io/api/core/v1/types.go +++ b/constraint/vendor/k8s.io/api/core/v1/types.go @@ -41,7 +41,7 @@ type Volume struct { // volumeSource represents the location and type of the mounted volume. // If not specified, the Volume is implied to be an EmptyDir. // This implied behavior is deprecated and will be removed in a future version. - VolumeSource `json:",inline" protobuf:"bytes,2,opt,name=volumeSource"` + VolumeSource `json:"" protobuf:"bytes,2,opt,name=volumeSource"` } // Represents the source of a volume to mount. @@ -360,8 +360,9 @@ const ( // PersistentVolume (PV) is a storage resource provisioned by an administrator. // It is analogous to a node. // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes +// +k8s:supportsSubresource="/status" type PersistentVolume struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -388,7 +389,7 @@ type PersistentVolumeSpec struct { // +optional Capacity ResourceList `json:"capacity,omitempty" protobuf:"bytes,1,rep,name=capacity,casttype=ResourceList,castkey=ResourceName"` // persistentVolumeSource is the actual volume backing the persistent volume. - PersistentVolumeSource `json:",inline" protobuf:"bytes,2,opt,name=persistentVolumeSource"` + PersistentVolumeSource `json:"" protobuf:"bytes,2,opt,name=persistentVolumeSource"` // accessModes contains all ways the volume can be mounted. // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes // +optional @@ -495,7 +496,7 @@ type PersistentVolumeStatus struct { // PersistentVolumeList is a list of PersistentVolume items. type PersistentVolumeList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -510,8 +511,9 @@ type PersistentVolumeList struct { // +k8s:prerelease-lifecycle-gen:introduced=1.0 // PersistentVolumeClaim is a user's request for and claim to a persistent volume +// +k8s:supportsSubresource="/status" type PersistentVolumeClaim struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -534,7 +536,7 @@ type PersistentVolumeClaim struct { // PersistentVolumeClaimList is a list of PersistentVolumeClaim items. type PersistentVolumeClaimList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -578,8 +580,8 @@ type PersistentVolumeClaimSpec struct { // * An existing PVC (PersistentVolumeClaim) // If the provisioner or an external controller can support the specified data source, // it will create a new volume based on the contents of the specified data source. - // When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, - // and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. + // dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be + // copied to dataSource when dataSourceRef.namespace is not specified. // If the namespace is specified, then dataSourceRef will not be copied to dataSource. // +optional DataSource *TypedLocalObjectReference `json:"dataSource,omitempty" protobuf:"bytes,7,opt,name=dataSource"` @@ -604,7 +606,6 @@ type PersistentVolumeClaimSpec struct { // specified. // * While dataSource only allows local objects, dataSourceRef allows objects // in any namespaces. - // (Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. // (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled. // +optional DataSourceRef *TypedObjectReference `json:"dataSourceRef,omitempty" protobuf:"bytes,8,opt,name=dataSourceRef"` @@ -678,7 +679,7 @@ const ( // slightly longer than actual in-use time or unused time because of processing delays or // when this feature was enabled in the cluster. // - // Requires PersistentVolumeClaimUnusedSinceTime alpha featuregate + // Requires PersistentVolumeClaimUnusedSinceTime beta featuregate PersistentVolumeClaimUnused PersistentVolumeClaimConditionType = "Unused" ) @@ -764,6 +765,95 @@ type PersistentVolumeClaimCondition struct { Message string `json:"message,omitempty" protobuf:"bytes,6,opt,name=message"` } +// VolumeHealthStatusType describes the health status category of a volume. +// +enum +// +k8s:enum +type VolumeHealthStatusType string + +const ( + // VolumeHealthInaccessible indicates the volume cannot be accessed. + VolumeHealthInaccessible VolumeHealthStatusType = "Inaccessible" + // VolumeHealthDataLoss indicates data loss has been detected on the volume. + VolumeHealthDataLoss VolumeHealthStatusType = "DataLoss" + // VolumeHealthDegraded indicates the volume is functioning but with reduced capability. + VolumeHealthDegraded VolumeHealthStatusType = "Degraded" +) + +// VolumeHealthCondition represents an adverse health condition reported for a volume. +type VolumeHealthCondition struct { + // status is the machine-parseable health category. + // Possible values: + // - "Inaccessible": the volume cannot be accessed. + // - "DataLoss": data loss has been detected on the volume. + // - "Degraded": the volume is functioning with reduced capability. + // +required + // +k8s:required + Status VolumeHealthStatusType `json:"status" protobuf:"bytes,1,opt,name=status,casttype=VolumeHealthStatusType"` + // reason is a brief CamelCase machine-parseable reason. + // Together with status it forms the unique identity of a condition entry. + // Maximum permitted length of a reason is 256 bytes. + // +required + // +k8s:required + // +k8s:maxBytes=256 + Reason string `json:"reason" protobuf:"bytes,2,opt,name=reason"` + // message is a human-readable description. + // Maximum permitted length of a message is 1024 bytes. + // +optional + // +k8s:optional + // +k8s:maxBytes=1024 + Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` +} + +// VolumeHealthStatus contains health information for a volume reported +// by the CSI controller plugin. +type VolumeHealthStatus struct { + // conditions is the set of adverse conditions reported by + // the CSI controller plugin. An empty list means no adverse condition. + // At most 16 conditions may be reported. + // +optional + // +listType=map + // +listMapKey=status + // +patchMergeKey=status + // +patchStrategy=merge + // +listMapKey=reason + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=status + // +k8s:listMapKey=reason + // +k8s:maxItems=16 + HealthConditions []VolumeHealthCondition `json:"healthConditions,omitempty" patchStrategy:"merge" patchMergeKey:"status" protobuf:"bytes,1,rep,name=healthConditions"` + // lastTransitionTime is when the current set of conditions first appeared. + // +optional + LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,2,opt,name=lastTransitionTime"` +} + +// PodVolumeHealth contains health information for a volume used by a pod, +// reported by the CSI node plugin via the kubelet. +type PodVolumeHealth struct { + // name matches an entry in pod.spec.volumes. + // +required + // +k8s:required + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // conditions is the set of adverse conditions reported by + // the CSI node plugin for this volume on this node. + // At most 16 conditions may be reported. + // +optional + // +listType=map + // +listMapKey=status + // +patchMergeKey=status + // +patchStrategy=merge + // +listMapKey=reason + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=status + // +k8s:listMapKey=reason + // +k8s:maxItems=16 + HealthConditions []VolumeHealthCondition `json:"healthConditions,omitempty" patchStrategy:"merge" patchMergeKey:"status" protobuf:"bytes,2,rep,name=healthConditions"` + // lastTransitionTime is when the current set of conditions first appeared. + // +optional + LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` +} + // PersistentVolumeClaimStatus is the current status of a persistent volume claim. type PersistentVolumeClaimStatus struct { // phase represents the current phase of PersistentVolumeClaim. @@ -857,6 +947,12 @@ type PersistentVolumeClaimStatus struct { // +featureGate=VolumeAttributesClass // +optional ModifyVolumeStatus *ModifyVolumeStatus `json:"modifyVolumeStatus,omitempty" protobuf:"bytes,9,opt,name=modifyVolumeStatus"` + // healthStatus contains the latest controller-reported health information + // for the volume bound to this claim. + // +featureGate=CSIVolumeHealth + // +optional + // +k8s:optional + HealthStatus *VolumeHealthStatus `json:"healthStatus,omitempty" protobuf:"bytes,10,opt,name=healthStatus"` } // +enum @@ -962,6 +1058,17 @@ type EmptyDirVolumeSource struct { // More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir // +optional SizeLimit *resource.Quantity `json:"sizeLimit,omitempty" protobuf:"bytes,2,opt,name=sizeLimit"` + // mode specifies the permission bits for the emptyDir directory, in numeric + // notation (e.g., 0755, 01777). Must be a value between 0000 and 01777. + // If not specified, defaults to 0777. + // This might be in conflict with other options that affect the file + // mode, like fsGroup. If fsGroup is specified, the fsGroup permissions + // will override the mode specified here. + // This field has no effect on Windows. + // This field is alpha and requires EmptyDirVolumeMode featuregate to be enabled. + // +featureGate=EmptyDirVolumeMode + // +optional + Mode *int32 `json:"mode,omitempty" protobuf:"varint,3,opt,name=mode"` } // Represents a Glusterfs mount that lasts the lifetime of a pod. @@ -1454,6 +1561,12 @@ type SecretVolumeSource struct { // optional field specify whether the Secret or its keys must be defined // +optional Optional *bool `json:"optional,omitempty" protobuf:"varint,4,opt,name=optional"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + DefaultUser *int64 `json:"defaultUser,omitempty" protobuf:"varint,5,opt,name=defaultUser"` } const ( @@ -1467,7 +1580,7 @@ const ( // Note that this is identical to a secret volume source without the default // mode. type SecretProjection struct { - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // items if unspecified, each key-value pair in the Data field of the referenced // Secret will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be @@ -1877,7 +1990,7 @@ type StorageOSPersistentVolumeSource struct { // the items element is populated with specific mappings of keys to paths. // ConfigMap volumes support ownership management and SELinux relabeling. type ConfigMapVolumeSource struct { - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // items if unspecified, each key-value pair in the Data field of the referenced // ConfigMap will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be @@ -1900,6 +2013,12 @@ type ConfigMapVolumeSource struct { // optional specify whether the ConfigMap or its keys must be defined // +optional Optional *bool `json:"optional,omitempty" protobuf:"varint,4,opt,name=optional"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + DefaultUser *int64 `json:"defaultUser,omitempty" protobuf:"varint,5,opt,name=defaultUser"` } const ( @@ -1914,7 +2033,7 @@ const ( // Note that this is identical to a configmap volume source without the default // mode. type ConfigMapProjection struct { - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // items if unspecified, each key-value pair in the Data field of the referenced // ConfigMap will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be @@ -1952,6 +2071,12 @@ type ServiceAccountTokenProjection struct { // path is the path relative to the mount point of the file to project the // token into. Path string `json:"path" protobuf:"bytes,3,opt,name=path"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + User *int64 `json:"user,omitempty" protobuf:"varint,4,opt,name=user"` } // ClusterTrustBundleProjection describes how to select a set of @@ -1986,6 +2111,13 @@ type ClusterTrustBundleProjection struct { // Relative path from the volume root to write the bundle. Path string `json:"path" protobuf:"bytes,4,rep,name=path"` + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + User *int64 `json:"user,omitempty" protobuf:"varint,6,opt,name=user"` } // PodCertificateProjection provides a private key and X.509 certificate in the @@ -2074,6 +2206,13 @@ type PodCertificateProjection struct { // Signers should document the keys and values they support. Signers should // deny requests that contain keys they do not recognize. UserAnnotations map[string]string `json:"userAnnotations,omitempty" protobuf:"bytes,7,rep,name=userAnnotations"` + + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + User *int64 `json:"user,omitempty" protobuf:"varint,8,opt,name=user"` } // Represents a projected volume source @@ -2091,6 +2230,12 @@ type ProjectedVolumeSource struct { // mode, like fsGroup, and the result can be other mode bits set. // +optional DefaultMode *int32 `json:"defaultMode,omitempty" protobuf:"varint,2,opt,name=defaultMode"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + DefaultUser *int64 `json:"defaultUser,omitempty" protobuf:"varint,3,opt,name=defaultUser"` } // Projection that may be projected along with other supported volume types. @@ -2189,6 +2334,12 @@ type KeyToPath struct { // mode, like fsGroup, and the result can be other mode bits set. // +optional Mode *int32 `json:"mode,omitempty" protobuf:"varint,3,opt,name=mode"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + User *int64 `json:"user,omitempty" protobuf:"varint,4,opt,name=user"` } // Local represents directly-attached storage with node affinity @@ -2339,6 +2490,7 @@ type PersistentVolumeClaimTemplate struct { // validation. // // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // The specification for the PersistentVolumeClaim. The entire content is @@ -2400,8 +2552,7 @@ type VolumeMount struct { // If this field is not specified, it is treated as an equivalent of Disabled. // +optional RecursiveReadOnly *RecursiveReadOnlyMode `json:"recursiveReadOnly,omitempty" protobuf:"bytes,7,opt,name=recursiveReadOnly,casttype=RecursiveReadOnlyMode"` - // Path within the container at which the volume should be mounted. Must - // not contain ':'. + // Path within the container at which the volume should be mounted. MountPath string `json:"mountPath" protobuf:"bytes,3,opt,name=mountPath"` // Path within the volume from which the container's volume should be mounted. // Defaults to "" (volume's root). @@ -2421,8 +2572,30 @@ type VolumeMount struct { // SubPathExpr and SubPath are mutually exclusive. // +optional SubPathExpr string `json:"subPathExpr,omitempty" protobuf:"bytes,6,opt,name=subPathExpr"` + // bindMountOptions is the list of additional bind mount options to apply when + // mounting this volume into the container. Allowed values are noexec, + // nodev, and nosuid. These are Linux mount options and have no effect on + // Windows nodes. + // This field is not supported with image volumes. + // This is an alpha field and requires enabling the VolumeBindMountOptions feature gate. + // +featureGate=VolumeBindMountOptions + // +optional + // +listType=set + BindMountOptions []string `json:"bindMountOptions,omitempty" protobuf:"bytes,8,rep,name=bindMountOptions"` } +// BindMountOption defines the supported bind mount options. +type BindMountOption string + +const ( + // BindMountOptionNoExec prevents execution of binaries on the mounted volume. + BindMountOptionNoExec BindMountOption = "noexec" + // BindMountOptionNoDev ignores device special files on the mounted volume. + BindMountOptionNoDev BindMountOption = "nodev" + // BindMountOptionNoSUID ignores set-user-identifier or set-group-identifier bits on the mounted volume. + BindMountOptionNoSUID BindMountOption = "nosuid" +) + // MountPropagationMode describes mount propagation. // +enum type MountPropagationMode string @@ -2571,8 +2744,9 @@ type ResourceFieldSelector struct { // +structType=atomic type ConfigMapKeySelector struct { // The ConfigMap to select from. - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` - // The key to select. + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` + // The key to select from the ConfigMap's Data field. + // Keys in the BinaryData field are not currently propagated to container env vars. Key string `json:"key" protobuf:"bytes,2,opt,name=key"` // Specify whether the ConfigMap or its key must be defined // +optional @@ -2583,7 +2757,7 @@ type ConfigMapKeySelector struct { // +structType=atomic type SecretKeySelector struct { // The name of the secret in the pod's namespace to select from. - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // The key of the secret to select from. Must be a valid secret key. Key string `json:"key" protobuf:"bytes,2,opt,name=key"` // Specify whether the Secret or its key must be defined @@ -2610,9 +2784,10 @@ type EnvFromSource struct { // // The contents of the target ConfigMap's Data field will represent the // key-value pairs as environment variables. +// Keys in the BinaryData field are not currently propagated to container env vars. type ConfigMapEnvSource struct { // The ConfigMap to select from. - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // Specify whether the ConfigMap must be defined // +optional Optional *bool `json:"optional,omitempty" protobuf:"varint,2,opt,name=optional"` @@ -2625,7 +2800,7 @@ type ConfigMapEnvSource struct { // key-value pairs as environment variables. type SecretEnvSource struct { // The Secret to select from. - LocalObjectReference `json:",inline" protobuf:"bytes,1,opt,name=localObjectReference"` + LocalObjectReference `json:"" protobuf:"bytes,1,opt,name=localObjectReference"` // Specify whether the Secret must be defined // +optional Optional *bool `json:"optional,omitempty" protobuf:"varint,2,opt,name=optional"` @@ -2640,6 +2815,19 @@ type HTTPHeader struct { Value string `json:"value" protobuf:"bytes,2,opt,name=value"` } +// HTTPProtocol selects the wire protocol for the HTTP probe, +// independently of the URI scheme. +// +enum +type HTTPProtocol string + +const ( + // HTTPProtocolHTTP1 uses HTTP/1.1 (the existing default). + HTTPProtocolHTTP1 HTTPProtocol = "HTTP1" + // HTTPProtocolHTTP2 uses HTTP/2. + // Currently, only cleartext with prior knowledge (h2c) is supported, and must be used with scheme HTTP. + HTTPProtocolHTTP2 HTTPProtocol = "HTTP2" +) + // HTTPGetAction describes an action based on HTTP Get requests. type HTTPGetAction struct { // Path to access on the HTTP server. @@ -2661,6 +2849,11 @@ type HTTPGetAction struct { // +optional // +listType=atomic HTTPHeaders []HTTPHeader `json:"httpHeaders,omitempty" protobuf:"bytes,5,rep,name=httpHeaders"` + // Protocol selects the wire protocol for the probe connection. + // Nil defaults to HTTP/1.1. + // +optional + // +featureGate=H2CContainerProbe + Protocol *HTTPProtocol `json:"protocol,omitempty" protobuf:"bytes,6,opt,name=protocol,casttype=HTTPProtocol"` } // URIScheme identifies the scheme used for connection to a host for Get actions @@ -2697,8 +2890,29 @@ type GRPCAction struct { // +optional // +default="" Service *string `json:"service" protobuf:"bytes,2,opt,name=service"` + + // mode specifies the connection mode for the gRPC health probe. + // Set to "TLS" to use TLS without certificate verification. + // Set to "Plaintext" to use a plaintext (insecure) connection explicitly. + // If not specified, the probe uses a plaintext (insecure) connection. + // +featureGate=GRPCContainerProbeTLS + // +optional + Mode *GRPCProbeMode `json:"mode,omitempty" protobuf:"bytes,3,opt,name=mode,casttype=GRPCProbeMode"` } +// GRPCProbeMode describes the connection mode for a gRPC probe. +// +enum +type GRPCProbeMode string + +const ( + // GRPCProbeModePlaintext indicates that the probe should use a plaintext + // (insecure) gRPC connection. + GRPCProbeModePlaintext GRPCProbeMode = "Plaintext" + // GRPCProbeModeTLS indicates that the probe should connect using TLS + // without certificate verification. + GRPCProbeModeTLS GRPCProbeMode = "TLS" +) + // ExecAction describes a "run in container" action. type ExecAction struct { // Command is the command line to execute inside the container, the working directory for the @@ -2721,7 +2935,7 @@ type SleepAction struct { // alive or ready to receive traffic. type Probe struct { // The action taken to determine the health of a container - ProbeHandler `json:",inline" protobuf:"bytes,1,opt,name=handler"` + ProbeHandler `json:"" protobuf:"bytes,1,opt,name=handler"` // Number of seconds after the container has started before liveness probes are initiated. // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes // +optional @@ -3407,8 +3621,13 @@ type ContainerStatus struct { // ResourceStatus represents the status of a single resource allocated to a Pod. type ResourceStatus struct { // Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. - // For DRA resources, the value must be "claim:/". - // When this status is reported about a container, the "claim_name" and "request" must match one of the claims of this container. + // For DRA resources, the value must be "claim:/" when + // container.resources.claims[*].request is set or "claim:" when + // container.resources.claims[*].request is empty. + // For DRA-backed extended resources, "claim:/" is used + // when the claim name and request name are recorded in pod.status.extendedResourceClaimStatus. + // When this status is reported about a container, the "claim_name" and "request" + // must match one of the claims of this container. // +required Name ResourceName `json:"name" protobuf:"bytes,1,opt,name=name"` // List of unique resources health. Each element in the list contains an unique resource ID and its health. @@ -4092,6 +4311,8 @@ type Toleration struct { // Key is the taint key that the toleration applies to. Empty means match all taint keys. // If the key is empty, operator must be Exists; this combination means to match all values and all keys. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:format=k8s-label-key Key string `json:"key,omitempty" protobuf:"bytes,1,opt,name=key"` // Operator represents a key's relationship to the value. // Valid operators are Exists, Equal, Lt, and Gt. Defaults to Equal. @@ -4222,7 +4443,6 @@ type PodSpec struct { ServiceAccountName string `json:"serviceAccountName,omitempty" protobuf:"bytes,8,opt,name=serviceAccountName"` // DeprecatedServiceAccount is a deprecated alias for ServiceAccountName. // Deprecated: Use serviceAccountName instead. - // +k8s:conversion-gen=false // +optional DeprecatedServiceAccount string `json:"serviceAccount,omitempty" protobuf:"bytes,9,opt,name=serviceAccount"` // AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. @@ -4241,17 +4461,14 @@ type PodSpec struct { // When `hostNetwork` is true, specified `hostPort` fields in port definitions must match `containerPort`, // and unspecified `hostPort` fields in port definitions are defaulted to match `containerPort`. // Default to false. - // +k8s:conversion-gen=false // +optional HostNetwork bool `json:"hostNetwork,omitempty" protobuf:"varint,11,opt,name=hostNetwork"` // Use the host's pid namespace. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional HostPID bool `json:"hostPID,omitempty" protobuf:"varint,12,opt,name=hostPID"` // Use the host's ipc namespace. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional HostIPC bool `json:"hostIPC,omitempty" protobuf:"varint,13,opt,name=hostIPC"` // Share a single process namespace between all of the containers in a pod. @@ -4259,7 +4476,6 @@ type PodSpec struct { // in the same pod, and the first process in each container will not be assigned PID 1. // HostPID and ShareProcessNamespace cannot both be set. // Optional: Default to false. - // +k8s:conversion-gen=false // +optional ShareProcessNamespace *bool `json:"shareProcessNamespace,omitempty" protobuf:"varint,27,opt,name=shareProcessNamespace"` // SecurityContext holds pod-level security attributes and common container settings. @@ -4293,6 +4509,7 @@ type PodSpec struct { // If specified, the pod's tolerations. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional Tolerations []Toleration `json:"tolerations,omitempty" protobuf:"bytes,22,opt,name=tolerations"` // HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts // file if specified. @@ -4343,6 +4560,8 @@ type PodSpec struct { EnableServiceLinks *bool `json:"enableServiceLinks,omitempty" protobuf:"varint,30,opt,name=enableServiceLinks"` // PreemptionPolicy is the Policy for preempting pods with lower priority. // One of Never, PreemptLowerPriority. + // When Priority Admission Controller is enabled, it prevents users from setting + // this field. The admission controller populates this field from PriorityClassName. // Defaults to PreemptLowerPriority if unset. // +optional PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,31,opt,name=preemptionPolicy"` @@ -4415,7 +4634,6 @@ type PodSpec struct { // When set to false, a new userns is created for the pod. Setting false is useful for // mitigating container breakout vulnerabilities even allowing users to run their // containers as root without actually having root privileges on the host. - // +k8s:conversion-gen=false // +optional HostUsers *bool `json:"hostUsers,omitempty" protobuf:"bytes,37,opt,name=hostUsers"` @@ -4471,7 +4689,6 @@ type PodSpec struct { // - `hostNetwork` must be set to false. // // This field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters. - // Requires the HostnameOverride feature gate to be enabled. // // +featureGate=HostnameOverride // +optional @@ -4497,6 +4714,34 @@ type PodSpec struct { // +featureGate=GenericWorkload // +optional SchedulingGroup *PodSchedulingGroup `json:"schedulingGroup,omitempty" protobuf:"bytes,43,opt,name=schedulingGroup"` + + // evictionResponders reference responders that react to Evictions based on EvictionRequests. + // Responders should observe and communicate through the Eviction Resource API to help with + // the graceful termination of a pod. The responders are selected sequentially, according to + // their specified priority. + // + // Responders should periodically report on an eviction progress by updating the + // .status.responders[].heartbeatTime field of the Eviction object. If this field is not updated + // within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the eviction + // is passed over to the next responder with a lower priority. If there is no other responder, + // the last default imperative-eviction.k8s.io/evictor responder with a priority of 100 will + // evict the pod using the imperative Eviction API (pods//eviction subresource). + // + // The maximum length of the responders list is 10. + // Responders are not supported when the pod is part of a PodGroup (.spec.schedulingGroup is set). + // This field can only be set on creation and is immutable afterwards. + // +featureGate=EvictionRequestAPI + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=10 + // +k8s:alpha(since: "1.37")=+k8s:dependentForbidden("schedulingGroup") + EvictionResponders []EvictionResponder `json:"evictionResponders,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,44,rep,name=evictionResponders"` } // PodResourceClaim references exactly one ResourceClaim, either directly @@ -4964,11 +5209,8 @@ type PodSecurityContext struct { // Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes // whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their // CSIDriver instance. Other volumes are always re-labelled recursively. - // "MountOption" value is allowed only when SELinuxMount feature gate is enabled. // - // If not specified and SELinuxMount feature gate is enabled, "MountOption" is used. - // If not specified and SELinuxMount feature gate is disabled, "MountOption" is used for ReadWriteOncePod volumes - // and "Recursive" for all other volumes. + // If not specified, "MountOption" is used. // // This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers. // @@ -5288,7 +5530,7 @@ type EphemeralContainer struct { // specific to ephemeral containers. Fields in common with Container are in the // following inlined struct so than an EphemeralContainer may easily be converted // to a Container. - EphemeralContainerCommon `json:",inline" protobuf:"bytes,1,req"` + EphemeralContainerCommon `json:"" protobuf:"bytes,1,req"` // If set, the name of the container from PodSpec that this ephemeral container targets. // The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. @@ -5300,6 +5542,43 @@ type EphemeralContainer struct { TargetContainerName string `json:"targetContainerName,omitempty" protobuf:"bytes,2,opt,name=targetContainerName"` } +// EvictionResponder allows you to specify the responder reacting to an Eviction. +// Responders should observe and communicate through the Eviction Resource API to help with +// the graceful eviction of a target (e.g. termination of a pod). +// +structType=atomic +type EvictionResponder struct { + // name allows you to identify the responder responding to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + // +k8s:customValidation + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required. + // +required + // +k8s:required + // +k8s:minimum=0 + // +k8s:maximum=100000 + // +k8s:customValidation + Priority *int32 `json:"priority" protobuf:"varint,2,opt,name=priority"` +} + // PodStatus represents information about the status of a pod. Status may trail the actual // state of a system, especially if the node that hosts the pod cannot contact the control // plane. @@ -5476,27 +5755,25 @@ type PodStatus struct { // Examples include "cpu", "memory", "ephemeral-storage", and hugepages. // +featureGate=DRANodeAllocatableResources // +optional - // +listType=atomic - NodeAllocatableResourceClaimStatuses []NodeAllocatableResourceClaimStatus `json:"nodeAllocatableResourceClaimStatuses,omitempty" protobuf:"bytes,21,rep,name=nodeAllocatableResourceClaimStatuses"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:prerelease-lifecycle-gen:introduced=1.0 + // +patchStrategy=merge + // +patchMergeKey=resourceClaimName + // +listType=map + // +listMapKey=resourceClaimName + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=resourceClaimName + NodeAllocatableResourceClaimStatuses []NodeAllocatableResourceClaimStatus `json:"nodeAllocatableResourceClaimStatuses,omitempty" patchStrategy:"merge" patchMergeKey:"resourceClaimName" protobuf:"bytes,21,rep,name=nodeAllocatableResourceClaimStatuses"` -// PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded -type PodStatusResult struct { - metav1.TypeMeta `json:",inline"` - // 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" protobuf:"bytes,1,opt,name=metadata"` - // Most recently observed status of the pod. - // This data may not be up to date. - // Populated by the system. - // Read-only. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // volumeHealth contains node-reported health for each volume the pod is using. + // Populated by the kubelet on the pod's node. + // +featureGate=CSIVolumeHealth // +optional - Status PodStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + VolumeHealth []PodVolumeHealth `json:"volumeHealth,omitempty" protobuf:"bytes,22,rep,name=volumeHealth"` } // +genclient @@ -5507,8 +5784,12 @@ type PodStatusResult struct { // Pod is a collection of containers that can run on a host. This resource is created // by clients and scheduled onto hosts. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/ephemeralcontainers" +// +k8s:supportsSubresource="/resize" +// +k8s:supportsSubresource="/eviction" type Pod struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -5533,7 +5814,7 @@ type Pod struct { // PodList is a list of Pods. type PodList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -5549,6 +5830,7 @@ type PodTemplateSpec struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the pod. @@ -5563,7 +5845,7 @@ type PodTemplateSpec struct { // PodTemplate describes a template for creating copies of a predefined pod. type PodTemplate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -5580,7 +5862,7 @@ type PodTemplate struct { // PodTemplateList is a list of PodTemplates. type PodTemplateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -5597,18 +5879,18 @@ type ReplicationControllerSpec struct { // Defaults to 1. // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=1 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Minimum number of seconds for which a newly created pod should be ready // without any of its container crashing, for it to be considered available. // Defaults to 0 (pod will be considered available as soon as it is ready) // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 MinReadySeconds int32 `json:"minReadySeconds,omitempty" protobuf:"varint,4,opt,name=minReadySeconds"` // Selector is a label query over pods that should match the Replicas count. @@ -5631,6 +5913,7 @@ type ReplicationControllerSpec struct { // The only allowed template.spec.restartPolicy value is "Always". // More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional Template *PodTemplateSpec `json:"template,omitempty" protobuf:"bytes,3,opt,name=template"` } @@ -5699,17 +5982,18 @@ type ReplicationControllerCondition struct { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.0 // +k8s:supportsSubresource="/scale" +// +k8s:supportsSubresource="/status" // ReplicationController represents the configuration of a replication controller. type ReplicationController struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // If the Labels of a ReplicationController are empty, they are defaulted to // be the same as the Pod(s) that the replication controller manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the specification of the desired behavior of the replication controller. @@ -5731,7 +6015,7 @@ type ReplicationController struct { // ReplicationControllerList is a collection of replication controllers. type ReplicationControllerList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -5891,6 +6175,7 @@ type ServiceStatus struct { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"` } @@ -6295,8 +6580,10 @@ type ServicePort struct { // Service is a named abstraction of software service (for example, mysql) consisting of local port // (for example 3306) that the proxy listens on, and the selector that determines which pods // will answer requests sent through the proxy. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/proxy" type Service struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -6326,7 +6613,7 @@ const ( // ServiceList holds a list of services. type ServiceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -6346,7 +6633,7 @@ type ServiceList struct { // * a principal that can be authenticated and authorized // * a set of secrets type ServiceAccount struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -6385,7 +6672,7 @@ type ServiceAccount struct { // ServiceAccountList is a list of ServiceAccount objects type ServiceAccountList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -6419,7 +6706,7 @@ type ServiceAccountList struct { // // Deprecated: This API is deprecated in v1.33+. Use discoveryv1.EndpointSlice. type Endpoints struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -6534,7 +6821,7 @@ type EndpointPort struct { // EndpointsList is a list of endpoints. // Deprecated: This API is deprecated in v1.33+. type EndpointsList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -6560,6 +6847,9 @@ type NodeSpec struct { // ID of the node assigned by the cloud provider in the format: :// // +optional + // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:alpha(since: "1.36")=+k8s:update=NoUnset ProviderID string `json:"providerID,omitempty" protobuf:"bytes,3,opt,name=providerID"` // Unschedulable controls node schedulability of new pods. By default, node is schedulable. // More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration @@ -6578,6 +6868,29 @@ type NodeSpec struct { // see: https://issues.k8s.io/61966 // +optional DoNotUseExternalID string `json:"externalID,omitempty" protobuf:"bytes,2,opt,name=externalID"` + + // PodPreemptionPolicy controls the node-level preemption behaviors for pods on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + // +featureGate=InPlacePodVerticalScalingSchedulerPreemption + // +optional + // +k8s:optional + // +k8s:ifDisabled(InPlacePodVerticalScalingSchedulerPreemption)=+k8s:forbidden + PodPreemptionPolicy *NodePodPreemptionPolicy `json:"podPreemptionPolicy,omitempty" protobuf:"bytes,8,opt,name=podPreemptionPolicy"` +} + +// NodePodPreemptionPolicy defines the node-level policies governing preemption for pods on this node. +type NodePodPreemptionPolicy struct { + // DisableResizePreemption lists the owners (e.g., autoscalers, operators, administrators) + // that have requested to disable scheduler and Kubelet preemption for in-place pod resize on this node. + // If this list is non-empty, resize-induced preemption is disabled on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + // +listType=set + // +k8s:listType=set + // +optional + // +k8s:maxItems=20 + // +k8s:optional + // +k8s:eachVal=+k8s:format=k8s-label-key + DisableResizePreemption []string `json:"disableResizePreemption,omitempty" protobuf:"bytes,1,rep,name=disableResizePreemption"` } // NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. @@ -6701,6 +7014,10 @@ type NodeSystemInfo struct { Architecture string `json:"architecture" protobuf:"bytes,10,opt,name=architecture"` // Swap Info reported by the node. Swap *NodeSwapStatus `json:"swap,omitempty" protobuf:"bytes,11,opt,name=swap"` + // Whether the node is running in a user namespace. + // +featureGate=KubeletInUserNamespace + // +optional + RunningInUserNamespace *bool `json:"runningInUserNamespace,omitempty" protobuf:"varint,12,opt,name=runningInUserNamespace"` } // NodeSwapStatus represents swap memory information. @@ -6918,6 +7235,37 @@ const ( NodePIDPressure NodeConditionType = "PIDPressure" // NodeNetworkUnavailable means that network for the node is not correctly configured. NodeNetworkUnavailable NodeConditionType = "NetworkUnavailable" + // NodeGracefulNodeShutdownInProgress reports whether Graceful Node Shutdown is determined to be in progress on this Node. + // + // The admin is responsible for setting and clearing this condition. + NodeGracefulNodeShutdownInProgress NodeConditionType = "GracefulNodeShutdownInProgress" + // NodeDrainInProgress reports that this Node is actively being drained, + // according to the admin's definition of drain. + // Commonly, this involves removing some amount of Pods, volumes, and networks. + // + // The admin is responsible for setting and clearing this condition. + NodeDrainInProgress NodeConditionType = "DrainInProgress" + // NodeDrained reports that this Node has reached the drain criteria selected by the admin. + // + // The admin is responsible for setting and clearing this condition. + NodeDrained NodeConditionType = "Drained" + // NodeMaintenancePlanned reports that this Node is expected to undergo a change in the future. + // If this change impacts Node users, the admin should drain the Node first. + // + // Admins can use the Node maintenance condition for cases like hardware or software rollout, + // remediation, decommissioning, or debugging. + // + // The admin is responsible for setting and clearing this condition. + NodeMaintenancePlanned NodeConditionType = "MaintenancePlanned" + // NodeMaintenanceInProgress reports that this Node is actively undergoing maintenance. + // + // The admin decides whether the change will impact Node users and require a Node drain. + // For example, it is recommended to drain a Node before a Kubernetes upgrade. + // In contrast, a kernel live patch may not require a Node drain, but it can still be useful + // to communicate that maintenance is in progress. + // + // The admin is responsible for setting and clearing this condition. + NodeMaintenanceInProgress NodeConditionType = "MaintenanceInProgress" ) // NodeCondition contains condition information for a node. @@ -7030,8 +7378,10 @@ type ResourceList map[ResourceName]resource.Quantity // Node is a worker node in Kubernetes. // Each node will have a unique identifier in the cache (i.e. in etcd). +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/proxy" type Node struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -7055,7 +7405,7 @@ type Node struct { // NodeList is the whole list of all Nodes which have been registered with master. type NodeList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -7157,8 +7507,10 @@ type NamespaceCondition struct { // Namespace provides a scope for Names. // Use of multiple namespaces is optional. +// +k8s:supportsSubresource="/status" +// +k8s:supportsSubresource="/finalize" type Namespace struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -7180,7 +7532,7 @@ type Namespace struct { // NamespaceList is a list of Namespaces. type NamespaceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -7196,10 +7548,11 @@ type NamespaceList struct { // Binding ties one object to another; for example, a pod is bound to a node by a scheduler. type Binding struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // The target object that you want to bind to the standard object. @@ -7229,7 +7582,7 @@ const ( // PodLogOptions is the query options for a Pod's logs REST call. type PodLogOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // The container for which to stream logs. Defaults to only container if there is one container in the pod. // +optional @@ -7294,7 +7647,7 @@ type PodLogOptions struct { // TODO: merge w/ PodExecOptions below for stdin, stdout, etc // and also when we cut V2, we should export a "StreamOptions" or somesuch that contains Stdin, Stdout, Stder and TTY type PodAttachOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Stdin if true, redirects the standard input stream of the pod for this call. // Defaults to false. @@ -7333,7 +7686,7 @@ type PodAttachOptions struct { // TODO: This is largely identical to PodAttachOptions above, make sure they stay in sync and see about merging // and also when we cut V2, we should export a "StreamOptions" or somesuch that contains Stdin, Stdout, Stder and TTY type PodExecOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Redirect the standard input stream of the pod for this call. // Defaults to false. @@ -7374,7 +7727,7 @@ type PodExecOptions struct { // Port forwarding over SPDY does not use these options. It requires the port // to be passed in the `port` header as part of request. type PodPortForwardOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // List of ports to forward // Required when using WebSockets @@ -7389,7 +7742,7 @@ type PodPortForwardOptions struct { // PodProxyOptions is the query options to a Pod's proxy call. type PodProxyOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Path is the URL path to use for the current proxy request to pod. // +optional @@ -7402,7 +7755,7 @@ type PodProxyOptions struct { // NodeProxyOptions is the query options to a Node's proxy call. type NodeProxyOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Path is the URL path to use for the current proxy request to node. // +optional @@ -7415,7 +7768,7 @@ type NodeProxyOptions struct { // ServiceProxyOptions is the query options to a Service's proxy call. type ServiceProxyOptions struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Path is the part of URLs that include service endpoints, suffixes, // and parameters to use for the current proxy request to service. @@ -7542,7 +7895,7 @@ type TypedLocalObjectReference struct { // SerializedReference is a reference to serialized object. type SerializedReference struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // The reference to an object in the system. // +optional Reference ObjectReference `json:"reference,omitempty" protobuf:"bytes,1,opt,name=reference"` @@ -7577,7 +7930,7 @@ const ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type Event struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metav1.ObjectMeta `json:"metadata" protobuf:"bytes,1,opt,name=metadata"` @@ -7657,7 +8010,7 @@ type EventSeries struct { // EventList is a list of events. type EventList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -7720,7 +8073,7 @@ type LimitRangeSpec struct { // LimitRange sets resource usage limits for each kind of resource in a Namespace. type LimitRange struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -7737,7 +8090,7 @@ type LimitRange struct { // LimitRangeList is a list of LimitRange items. type LimitRangeList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -7892,8 +8245,9 @@ type ResourceQuotaStatus struct { // +k8s:prerelease-lifecycle-gen:introduced=1.0 // ResourceQuota sets aggregate quota restrictions enforced per namespace +// +k8s:supportsSubresource="/status" type ResourceQuota struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -7915,7 +8269,7 @@ type ResourceQuota struct { // ResourceQuotaList is a list of ResourceQuota items. type ResourceQuotaList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -7933,7 +8287,7 @@ type ResourceQuotaList struct { // Secret holds secret data of a certain type. The total bytes of the values in // the Data field must be less than MaxSecretSize bytes. type Secret struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -7964,6 +8318,8 @@ type Secret struct { // Used to facilitate programmatic handling of secret data. // More info: https://kubernetes.io/docs/concepts/configuration/secret/#secret-types // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable Type SecretType `json:"type,omitempty" protobuf:"bytes,3,opt,name=type,casttype=SecretType"` } @@ -8059,7 +8415,7 @@ const ( // SecretList is a list of Secret. type SecretList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -8076,7 +8432,7 @@ type SecretList struct { // ConfigMap holds configuration data for pods to consume. type ConfigMap struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -8104,6 +8460,8 @@ type ConfigMap struct { // the Data field, this is enforced during validation process. // Using this field will require 1.10+ apiserver and // kubelet. + // Note: BinaryData keys are not currently propagated to container env vars + // via ConfigMapKeyRef or ConfigMapRef env sources; only Data keys are used. // +optional BinaryData map[string][]byte `json:"binaryData,omitempty" protobuf:"bytes,3,rep,name=binaryData"` } @@ -8113,7 +8471,7 @@ type ConfigMap struct { // ConfigMapList is a resource containing a list of ConfigMap objects. type ConfigMapList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -8157,10 +8515,11 @@ type ComponentCondition struct { // ComponentStatus (and ComponentStatusList) holds the cluster validation info. // Deprecated: This API is deprecated in v1.19+ type ComponentStatus struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of component conditions observed @@ -8178,7 +8537,7 @@ type ComponentStatus struct { // Status of all the conditions for the component as a list of ComponentStatus objects. // Deprecated: This API is deprecated in v1.19+ type ComponentStatusList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -8205,6 +8564,12 @@ type DownwardAPIVolumeSource struct { // mode, like fsGroup, and the result can be other mode bits set. // +optional DefaultMode *int32 `json:"defaultMode,omitempty" protobuf:"varint,2,opt,name=defaultMode"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + DefaultUser *int64 `json:"defaultUser,omitempty" protobuf:"varint,3,opt,name=defaultUser"` } const ( @@ -8230,6 +8595,12 @@ type DownwardAPIVolumeFile struct { // mode, like fsGroup, and the result can be other mode bits set. // +optional Mode *int32 `json:"mode,omitempty" protobuf:"varint,4,opt,name=mode"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + // +featureGate=AtomicWriteVolumeUserFields + // +optional + User *int64 `json:"user,omitempty" protobuf:"varint,5,opt,name=user"` } // Represents downward API info for projecting into a projected volume. @@ -8388,10 +8759,11 @@ type WindowsSecurityContextOptions struct { // RangeAllocation is not a public type. type RangeAllocation struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Range is string that identifies the range represented by 'data'. @@ -8518,12 +8890,78 @@ type ImageVolumeSource struct { type NodeAllocatableResourceClaimStatus struct { // ResourceClaimName is the resource claim referenced by the pod that resulted in this node allocatable resource allocation. // +required + // +k8s:required ResourceClaimName string `json:"resourceClaimName" protobuf:"bytes,1,opt,name=resourceClaimName"` // Containers lists the names of all containers in this pod that reference the claim. // +optional // +listType=set + // +k8s:optional + // +k8s:listType=set Containers []string `json:"containers,omitempty" protobuf:"bytes,2,rep,name=containers"` - // Resources is a map of the node-allocatable resource name to the aggregate quantity allocated to the claim. + + // Resources is tombstoned since it got replaced with more granular Mapping and Overhead fields. + // Resources map[ResourceName]resource.Quantity `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"` + + // Mapping contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].mapping` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + // +optional + // +patchStrategy=merge + // +patchMergeKey=name + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + Mapping []NodeAllocatableMappedResources `json:"mapping,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,4,rep,name=mapping"` + // Overhead contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].overhead` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + // +optional + // +patchStrategy=merge + // +patchMergeKey=name + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + Overhead []NodeAllocatableOverheadResources `json:"overhead,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,5,rep,name=overhead"` +} + +// NodeAllocatableMappedResources describes mapped node allocatable resource allocations. +type NodeAllocatableMappedResources struct { + // Name is the name of the resource (e.g., cpu, memory). + // +required + // +k8s:required + Name ResourceName `json:"name" protobuf:"bytes,1,opt,name=name,casttype=ResourceName"` + // Quantity is the total node allocatable resource capacity allocated for the claim. + // This claim's allocated devices is shared by all the containers referencing the claim. + // Kubelet adds this value to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. + // +required + // +k8s:required + Quantity *resource.Quantity `json:"quantity" protobuf:"bytes,2,opt,name=quantity"` +} + +// NodeAllocatableOverheadResources describes auxiliary overhead resource allocations. +type NodeAllocatableOverheadResources struct { + // Name is the name of the resource (e.g., cpu, memory). // +required - Resources map[ResourceName]resource.Quantity `json:"resources" protobuf:"bytes,3,rep,name=resources"` + // +k8s:required + Name ResourceName `json:"name" protobuf:"bytes,1,opt,name=name,casttype=ResourceName"` + // PerPod is the flat overhead quantity allocated per pod. + // Adding to each container limit allows individual containers to utilize the overhead, while the parent pod-level cgroup limit caps the total usage at the pod boundary where the overhead is accounted for exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + // +optional + // +k8s:optional + PerPod *resource.Quantity `json:"perPod,omitempty" protobuf:"bytes,2,opt,name=perPod"` + // PerContainer is the variable overhead quantity applied for each container referencing the claim. + // The container references are recorded in `nodeAllocatableResourceClaimStatuses.containers`. + // The total overhead quantity allocated for the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + // +optional + // +k8s:optional + PerContainer *resource.Quantity `json:"perContainer,omitempty" protobuf:"bytes,3,opt,name=perContainer"` } diff --git a/constraint/vendor/k8s.io/api/core/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/core/v1/types_swagger_doc_generated.go index 97eb5ceec..4b68c5685 100644 --- a/constraint/vendor/k8s.io/api/core/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/core/v1/types_swagger_doc_generated.go @@ -235,6 +235,7 @@ var map_ClusterTrustBundleProjection = map[string]string{ "labelSelector": "Select all ClusterTrustBundles that match this label selector. Only has effect if signerName is set. Mutually-exclusive with name. If unset, interpreted as \"match nothing\". If set but empty, interpreted as \"match everything\".", "optional": "If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles.", "path": "Relative path from the volume root to write the bundle.", + "user": "user is Optional: The owner UID of the created file. If specified, the item-level user field takes precedence over defaultUser. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (ClusterTrustBundleProjection) SwaggerDoc() map[string]string { @@ -278,7 +279,7 @@ var map_ConfigMap = map[string]string{ "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "immutable": "Immutable, if set to true, ensures that data stored in the ConfigMap cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.", "data": "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", - "binaryData": "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet.", + "binaryData": "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet. Note: BinaryData keys are not currently propagated to container env vars via ConfigMapKeyRef or ConfigMapRef env sources; only Data keys are used.", } func (ConfigMap) SwaggerDoc() map[string]string { @@ -286,7 +287,7 @@ func (ConfigMap) SwaggerDoc() map[string]string { } var map_ConfigMapEnvSource = map[string]string{ - "": "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables.", + "": "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables. Keys in the BinaryData field are not currently propagated to container env vars.", "optional": "Specify whether the ConfigMap must be defined", } @@ -296,7 +297,7 @@ func (ConfigMapEnvSource) SwaggerDoc() map[string]string { var map_ConfigMapKeySelector = map[string]string{ "": "Selects a key from a ConfigMap.", - "key": "The key to select.", + "key": "The key to select from the ConfigMap's Data field. Keys in the BinaryData field are not currently propagated to container env vars.", "optional": "Specify whether the ConfigMap or its key must be defined", } @@ -342,6 +343,7 @@ var map_ConfigMapVolumeSource = map[string]string{ "items": "items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", "defaultMode": "defaultMode is optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", "optional": "optional specify whether the ConfigMap or its keys must be defined", + "defaultUser": "defaultUser is Optional: The owner UID of the created files by default. The defaultUser field is only used as a fallback when the item-level user field is unset. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (ConfigMapVolumeSource) SwaggerDoc() map[string]string { @@ -546,6 +548,7 @@ var map_DownwardAPIVolumeFile = map[string]string{ "fieldRef": "Required: Selects a field of the pod: only annotations, labels, name, namespace and uid are supported.", "resourceFieldRef": "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.", "mode": "Optional: mode bits used to set permissions on this file, must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", + "user": "user is Optional: The owner UID of the created file. If specified, the item-level user field takes precedence over defaultUser. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (DownwardAPIVolumeFile) SwaggerDoc() map[string]string { @@ -556,6 +559,7 @@ var map_DownwardAPIVolumeSource = map[string]string{ "": "DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.", "items": "Items is a list of downward API volume file", "defaultMode": "Optional: mode bits to use on created files by default. Must be a Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", + "defaultUser": "defaultUser is Optional: The owner UID of the created files by default. The defaultUser field is only used as a fallback when the item-level user field is unset. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (DownwardAPIVolumeSource) SwaggerDoc() map[string]string { @@ -566,6 +570,7 @@ var map_EmptyDirVolumeSource = map[string]string{ "": "Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling.", "medium": "medium represents what type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", "sizeLimit": "sizeLimit is the total amount of local storage required for this EmptyDir volume. The size limit is also applicable for memory medium. The maximum usage on memory medium EmptyDir would be the minimum value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. The default is nil which means that the limit is undefined. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", + "mode": "mode specifies the permission bits for the emptyDir directory, in numeric notation (e.g., 0755, 01777). Must be a value between 0000 and 01777. If not specified, defaults to 0777. This might be in conflict with other options that affect the file mode, like fsGroup. If fsGroup is specified, the fsGroup permissions will override the mode specified here. This field has no effect on Windows. This field is alpha and requires EmptyDirVolumeMode featuregate to be enabled.", } func (EmptyDirVolumeSource) SwaggerDoc() map[string]string { @@ -766,6 +771,16 @@ func (EventSource) SwaggerDoc() map[string]string { return map_EventSource } +var map_EvictionResponder = map[string]string{ + "": "EvictionResponder allows you to specify the responder reacting to an Eviction. Responders should observe and communicate through the Eviction Resource API to help with the graceful eviction of a target (e.g. termination of a pod).", + "name": "name allows you to identify the responder responding to the Eviction.\n\nIt must be a valid domain-prefixed key (such as \"acme.io/foo\"). Domain names *.k8s.io and *.kubernetes.io are reserved. This field must be unique for each responder. This field is required.", + "priority": "priority for this responder. Higher priorities are selected first by the evictionrequest-controller. If there are responders with the same priority, the responder whose domain name comes first in the alphabetical higher domain order, will be picked. This means that the top domain labels are compared alphabetically first, followed by the lower domain labels. The key is compared last.\n\nThe responder that is the managing controller of the pod should set the value of this field to 10000 to allow both for preemption or fallback registration by other responders.\n\nThe minimum value is 0 and the maximum value is 100000. The interval 0-999 is reserved for responders with *.k8s.io suffix. This field is required.", +} + +func (EvictionResponder) SwaggerDoc() map[string]string { + return map_EvictionResponder +} + var map_ExecAction = map[string]string{ "": "ExecAction describes a \"run in container\" action.", "command": "Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.", @@ -852,6 +867,7 @@ var map_GRPCAction = map[string]string{ "": "GRPCAction specifies an action involving a GRPC service.", "port": "Port number of the gRPC service. Number must be in the range 1 to 65535.", "service": "Service is the name of the service to place in the gRPC HealthCheckRequest (see https://github.com/grpc/grpc/blob/master/doc/health-checking.md).\n\nIf this is not specified, the default behavior is defined by gRPC.", + "mode": "mode specifies the connection mode for the gRPC health probe. Set to \"TLS\" to use TLS without certificate verification. Set to \"Plaintext\" to use a plaintext (insecure) connection explicitly. If not specified, the probe uses a plaintext (insecure) connection.", } func (GRPCAction) SwaggerDoc() map[string]string { @@ -899,6 +915,7 @@ var map_HTTPGetAction = map[string]string{ "host": "Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead.", "scheme": "Scheme to use for connecting to the host. Defaults to HTTP.", "httpHeaders": "Custom headers to set in the request. HTTP allows repeated headers.", + "protocol": "Protocol selects the wire protocol for the probe connection. Nil defaults to HTTP/1.1.", } func (HTTPGetAction) SwaggerDoc() map[string]string { @@ -1006,6 +1023,7 @@ var map_KeyToPath = map[string]string{ "key": "key is the key to project.", "path": "path is the relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", "mode": "mode is Optional: mode bits used to set permissions on this file. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", + "user": "user is Optional: The owner UID of the created file. If specified, the item-level user field takes precedence over defaultUser. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (KeyToPath) SwaggerDoc() map[string]string { @@ -1234,11 +1252,33 @@ func (NodeAffinity) SwaggerDoc() map[string]string { return map_NodeAffinity } +var map_NodeAllocatableMappedResources = map[string]string{ + "": "NodeAllocatableMappedResources describes mapped node allocatable resource allocations.", + "name": "Name is the name of the resource (e.g., cpu, memory).", + "quantity": "Quantity is the total node allocatable resource capacity allocated for the claim. This claim's allocated devices is shared by all the containers referencing the claim. Kubelet adds this value to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim.", +} + +func (NodeAllocatableMappedResources) SwaggerDoc() map[string]string { + return map_NodeAllocatableMappedResources +} + +var map_NodeAllocatableOverheadResources = map[string]string{ + "": "NodeAllocatableOverheadResources describes auxiliary overhead resource allocations.", + "name": "Name is the name of the resource (e.g., cpu, memory).", + "perPod": "PerPod is the flat overhead quantity allocated per pod. Adding to each container limit allows individual containers to utilize the overhead, while the parent pod-level cgroup limit caps the total usage at the pod boundary where the overhead is accounted for exactly once. At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration.", + "perContainer": "PerContainer is the variable overhead quantity applied for each container referencing the claim. The container references are recorded in `nodeAllocatableResourceClaimStatuses.containers`. The total overhead quantity allocated for the claim is computed as: Quantity = PerPod + (PerContainer * NumReferences) Kubelet accounts for this overhead in cgroups: - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration.", +} + +func (NodeAllocatableOverheadResources) SwaggerDoc() map[string]string { + return map_NodeAllocatableOverheadResources +} + var map_NodeAllocatableResourceClaimStatus = map[string]string{ "": "NodeAllocatableResourceClaimStatus describes the status of node allocatable resources allocated via DRA.", "resourceClaimName": "ResourceClaimName is the resource claim referenced by the pod that resulted in this node allocatable resource allocation.", "containers": "Containers lists the names of all containers in this pod that reference the claim.", - "resources": "Resources is a map of the node-allocatable resource name to the aggregate quantity allocated to the claim.", + "mapping": "Mapping contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].mapping` field. This is used by kubelet for pod level and container-level cgroup enforcement.", + "overhead": "Overhead contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].overhead` field. This is used by kubelet for pod level and container-level cgroup enforcement.", } func (NodeAllocatableResourceClaimStatus) SwaggerDoc() map[string]string { @@ -1308,6 +1348,15 @@ func (NodeList) SwaggerDoc() map[string]string { return map_NodeList } +var map_NodePodPreemptionPolicy = map[string]string{ + "": "NodePodPreemptionPolicy defines the node-level policies governing preemption for pods on this node.", + "disableResizePreemption": "DisableResizePreemption lists the owners (e.g., autoscalers, operators, administrators) that have requested to disable scheduler and Kubelet preemption for in-place pod resize on this node. If this list is non-empty, resize-induced preemption is disabled on this node. This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate.", +} + +func (NodePodPreemptionPolicy) SwaggerDoc() map[string]string { + return map_NodePodPreemptionPolicy +} + var map_NodeProxyOptions = map[string]string{ "": "NodeProxyOptions is the query options to a Node's proxy call.", "path": "Path is the URL path to use for the current proxy request to node.", @@ -1368,14 +1417,15 @@ func (NodeSelectorTerm) SwaggerDoc() map[string]string { } var map_NodeSpec = map[string]string{ - "": "NodeSpec describes the attributes that a node is created with.", - "podCIDR": "PodCIDR represents the pod IP range assigned to the node.", - "podCIDRs": "podCIDRs represents the IP ranges assigned to the node for usage by Pods on that node. If this field is specified, the 0th entry must match the podCIDR field. It may contain at most 1 value for each of IPv4 and IPv6.", - "providerID": "ID of the node assigned by the cloud provider in the format: ://", - "unschedulable": "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration", - "taints": "If specified, the node's taints.", - "configSource": "Deprecated: Previously used to specify the source of the node's configuration for the DynamicKubeletConfig feature. This feature is removed.", - "externalID": "Deprecated. Not all kubelets will set this field. Remove field after 1.13. see: https://issues.k8s.io/61966", + "": "NodeSpec describes the attributes that a node is created with.", + "podCIDR": "PodCIDR represents the pod IP range assigned to the node.", + "podCIDRs": "podCIDRs represents the IP ranges assigned to the node for usage by Pods on that node. If this field is specified, the 0th entry must match the podCIDR field. It may contain at most 1 value for each of IPv4 and IPv6.", + "providerID": "ID of the node assigned by the cloud provider in the format: ://", + "unschedulable": "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration", + "taints": "If specified, the node's taints.", + "configSource": "Deprecated: Previously used to specify the source of the node's configuration for the DynamicKubeletConfig feature. This feature is removed.", + "externalID": "Deprecated. Not all kubelets will set this field. Remove field after 1.13. see: https://issues.k8s.io/61966", + "podPreemptionPolicy": "PodPreemptionPolicy controls the node-level preemption behaviors for pods on this node. This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate.", } func (NodeSpec) SwaggerDoc() map[string]string { @@ -1426,6 +1476,7 @@ var map_NodeSystemInfo = map[string]string{ "operatingSystem": "The Operating System reported by the node", "architecture": "The Architecture reported by the node", "swap": "Swap Info reported by the node.", + "runningInUserNamespace": "Whether the node is running in a user namespace.", } func (NodeSystemInfo) SwaggerDoc() map[string]string { @@ -1511,8 +1562,8 @@ var map_PersistentVolumeClaimSpec = map[string]string{ "volumeName": "volumeName is the binding reference to the PersistentVolume backing this claim.", "storageClassName": "storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", "volumeMode": "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec.", - "dataSource": "dataSource field can be used to specify either: * An existing VolumeSnapshot object (snapshot.storage.k8s.io/VolumeSnapshot) * An existing PVC (PersistentVolumeClaim) If the provisioner or an external controller can support the specified data source, it will create a new volume based on the contents of the specified data source. When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. If the namespace is specified, then dataSourceRef will not be copied to dataSource.", - "dataSourceRef": "dataSourceRef specifies the object from which to populate the volume with data, if a non-empty volume is desired. This may be any object from a non-empty API group (non core object) or a PersistentVolumeClaim object. When this field is specified, volume binding will only succeed if the type of the specified object matches some installed volume populator or dynamic provisioner. This field will replace the functionality of the dataSource field and as such if both fields are non-empty, they must have the same value. For backwards compatibility, when namespace isn't specified in dataSourceRef, both fields (dataSource and dataSourceRef) will be set to the same value automatically if one of them is empty and the other is non-empty. When namespace is specified in dataSourceRef, dataSource isn't set to the same value and must be empty. There are three important differences between dataSource and dataSourceRef: * While dataSource only allows two specific types of objects, dataSourceRef\n allows any non-core object, as well as PersistentVolumeClaim objects.\n* While dataSource ignores disallowed values (dropping them), dataSourceRef\n preserves all values, and generates an error if a disallowed value is\n specified.\n* While dataSource only allows local objects, dataSourceRef allows objects\n in any namespaces.\n(Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", + "dataSource": "dataSource field can be used to specify either: * An existing VolumeSnapshot object (snapshot.storage.k8s.io/VolumeSnapshot) * An existing PVC (PersistentVolumeClaim) If the provisioner or an external controller can support the specified data source, it will create a new volume based on the contents of the specified data source. dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. If the namespace is specified, then dataSourceRef will not be copied to dataSource.", + "dataSourceRef": "dataSourceRef specifies the object from which to populate the volume with data, if a non-empty volume is desired. This may be any object from a non-empty API group (non core object) or a PersistentVolumeClaim object. When this field is specified, volume binding will only succeed if the type of the specified object matches some installed volume populator or dynamic provisioner. This field will replace the functionality of the dataSource field and as such if both fields are non-empty, they must have the same value. For backwards compatibility, when namespace isn't specified in dataSourceRef, both fields (dataSource and dataSourceRef) will be set to the same value automatically if one of them is empty and the other is non-empty. When namespace is specified in dataSourceRef, dataSource isn't set to the same value and must be empty. There are three important differences between dataSource and dataSourceRef: * While dataSource only allows two specific types of objects, dataSourceRef\n allows any non-core object, as well as PersistentVolumeClaim objects.\n* While dataSource ignores disallowed values (dropping them), dataSourceRef\n preserves all values, and generates an error if a disallowed value is\n specified.\n* While dataSource only allows local objects, dataSourceRef allows objects\n in any namespaces.\n(Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", "volumeAttributesClassName": "volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string or nil value indicates that no VolumeAttributesClass will be applied to the claim. If the claim enters an Infeasible error state, this field can be reset to its previous value (including nil) to cancel the modification. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/", } @@ -1530,6 +1581,7 @@ var map_PersistentVolumeClaimStatus = map[string]string{ "allocatedResourceStatuses": "allocatedResourceStatuses stores status of resource being resized for the given PVC. Key names follow standard Kubernetes label syntax. Valid values are either:\n\t* Un-prefixed keys:\n\t\t- storage - the capacity of the volume.\n\t* Custom resources must use implementation-defined prefixed names such as \"example.com/my-custom-resource\"\nApart from above values - keys that are unprefixed or have kubernetes.io prefix are considered reserved and hence may not be used.\n\nClaimResourceStatus can be in any of following states:\n\t- ControllerResizeInProgress:\n\t\tState set when resize controller starts resizing the volume in control-plane.\n\t- ControllerResizeFailed:\n\t\tState set when resize has failed in resize controller with a terminal error.\n\t- NodeResizePending:\n\t\tState set when resize controller has finished resizing the volume but further resizing of\n\t\tvolume is needed on the node.\n\t- NodeResizeInProgress:\n\t\tState set when kubelet starts resizing the volume.\n\t- NodeResizeFailed:\n\t\tState set when resizing has failed in kubelet with a terminal error. Transient errors don't set\n\t\tNodeResizeFailed.\nFor example: if expanding a PVC for more capacity - this field can be one of the following states:\n\t- pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeFailed\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizePending\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeFailed\"\nWhen this field is not set, it means that no resize operation is in progress for the given PVC.\n\nA controller that receives PVC update with previously unknown resourceName or ClaimResourceStatus should ignore the update for the purpose it was designed. For example - a controller that only is responsible for resizing capacity of the volume, should ignore PVC updates that change other valid resources associated with PVC.", "currentVolumeAttributesClassName": "currentVolumeAttributesClassName is the current name of the VolumeAttributesClass the PVC is using. When unset, there is no VolumeAttributeClass applied to this PersistentVolumeClaim", "modifyVolumeStatus": "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. When this is unset, there is no ModifyVolume operation being attempted.", + "healthStatus": "healthStatus contains the latest controller-reported health information for the volume bound to this claim.", } func (PersistentVolumeClaimStatus) SwaggerDoc() map[string]string { @@ -1702,6 +1754,7 @@ var map_PodCertificateProjection = map[string]string{ "keyPath": "Write the key at this path in the projected volume.\n\nMost applications should use credentialBundlePath. When using keyPath and certificateChainPath, your application needs to check that the key and leaf certificate are consistent, because it is possible to read the files mid-rotation.", "certificateChainPath": "Write the certificate chain at this path in the projected volume.\n\nMost applications should use credentialBundlePath. When using keyPath and certificateChainPath, your application needs to check that the key and leaf certificate are consistent, because it is possible to read the files mid-rotation.", "userAnnotations": "userAnnotations allow pod authors to pass additional information to the signer implementation. Kubernetes does not restrict or validate this metadata in any way.\n\nThese values are copied verbatim into the `spec.unverifiedUserAnnotations` field of the PodCertificateRequest objects that Kubelet creates.\n\nEntries are subject to the same validation as object metadata annotations, with the addition that all keys must be domain-prefixed. No restrictions are placed on values, except an overall size limitation on the entire field.\n\nSigners should document the keys and values they support. Signers should deny requests that contain keys they do not recognize.", + "user": "user is Optional: The owner UID of the created file. If specified, the item-level user field takes precedence over defaultUser. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (PodCertificateProjection) SwaggerDoc() map[string]string { @@ -1894,7 +1947,7 @@ var map_PodSecurityContext = map[string]string{ "fsGroupChangePolicy": "fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are \"OnRootMismatch\" and \"Always\". If not specified, \"Always\" is used. Note that this field cannot be set when spec.os.name is windows.", "seccompProfile": "The seccomp options to use by the containers in this pod. Note that this field cannot be set when spec.os.name is windows.", "appArmorProfile": "appArmorProfile is the AppArmor options to use by the containers in this pod. Note that this field cannot be set when spec.os.name is windows.", - "seLinuxChangePolicy": "seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. Valid values are \"MountOption\" and \"Recursive\".\n\n\"Recursive\" means relabeling of all files on all Pod volumes by the container runtime. This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node.\n\n\"MountOption\" mounts all eligible Pod volumes with `-o context` mount option. This requires all Pods that share the same volume to use the same SELinux label. It is not possible to share the same volume among privileged and unprivileged Pods. Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their CSIDriver instance. Other volumes are always re-labelled recursively. \"MountOption\" value is allowed only when SELinuxMount feature gate is enabled.\n\nIf not specified and SELinuxMount feature gate is enabled, \"MountOption\" is used. If not specified and SELinuxMount feature gate is disabled, \"MountOption\" is used for ReadWriteOncePod volumes and \"Recursive\" for all other volumes.\n\nThis field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers.\n\nAll Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. Note that this field cannot be set when spec.os.name is windows.", + "seLinuxChangePolicy": "seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. Valid values are \"MountOption\" and \"Recursive\".\n\n\"Recursive\" means relabeling of all files on all Pod volumes by the container runtime. This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node.\n\n\"MountOption\" mounts all eligible Pod volumes with `-o context` mount option. This requires all Pods that share the same volume to use the same SELinux label. It is not possible to share the same volume among privileged and unprivileged Pods. Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their CSIDriver instance. Other volumes are always re-labelled recursively.\n\nIf not specified, \"MountOption\" is used.\n\nThis field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers.\n\nAll Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. Note that this field cannot be set when spec.os.name is windows.", } func (PodSecurityContext) SwaggerDoc() map[string]string { @@ -1943,7 +1996,7 @@ var map_PodSpec = map[string]string{ "readinessGates": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", "runtimeClassName": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", "enableServiceLinks": "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", - "preemptionPolicy": "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.", + "preemptionPolicy": "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. Defaults to PreemptLowerPriority if unset.", "overhead": "Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md", "topologySpreadConstraints": "TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", "setHostnameAsFQDN": "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", @@ -1952,8 +2005,9 @@ var map_PodSpec = map[string]string{ "schedulingGates": "SchedulingGates is an opaque list of values that if specified will block scheduling the pod. If schedulingGates is not empty, the pod will stay in the SchedulingGated state and the scheduler will not attempt to schedule the pod.\n\nSchedulingGates can only be set at pod creation time, and be removed only afterwards.", "resourceClaims": "ResourceClaims defines which ResourceClaims must be allocated and reserved before the Pod is allowed to start. The resources will be made available to those containers which consume them by name.\n\nThis is a stable field but requires that the DynamicResourceAllocation feature gate is enabled.\n\nThis field is immutable.", "resources": "Resources is the total amount of CPU and Memory resources required by all containers in the pod. It supports specifying Requests and Limits for \"cpu\", \"memory\" and \"hugepages-\" resource names only. ResourceClaims are not supported.\n\nThis field enables fine-grained control over resource allocation for the entire pod, allowing resource sharing among containers in a pod.\n\nThis is an alpha field and requires enabling the PodLevelResources feature gate.", - "hostnameOverride": "HostnameOverride specifies an explicit override for the pod's hostname as perceived by the pod. This field only specifies the pod's hostname and does not affect its DNS records. When this field is set to a non-empty string: - It takes precedence over the values set in `hostname` and `subdomain`. - The Pod's hostname will be set to this value. - `setHostnameAsFQDN` must be nil or set to false. - `hostNetwork` must be set to false.\n\nThis field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters. Requires the HostnameOverride feature gate to be enabled.", + "hostnameOverride": "HostnameOverride specifies an explicit override for the pod's hostname as perceived by the pod. This field only specifies the pod's hostname and does not affect its DNS records. When this field is set to a non-empty string: - It takes precedence over the values set in `hostname` and `subdomain`. - The Pod's hostname will be set to this value. - `setHostnameAsFQDN` must be nil or set to false. - `hostNetwork` must be set to false.\n\nThis field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters.", "schedulingGroup": "SchedulingGroup provides a reference to the immediate scheduling runtime grouping object that this Pod belongs to. This field is used by the scheduler to identify the group and apply the correct group scheduling policies. The association with a group also impacts other lifecycle aspects of a Pod that are relevant in a wider context of scheduling like preemption, resource attachment, etc. If not specified, the Pod is treated as a single unit in all of these aspects. The group object referenced by this field may not exist at the time the Pod is created. This field is immutable, but a group object with the same name may be recreated with different policies. Doing this during pod scheduling may result in the placement not conforming to the expected policies.", + "evictionResponders": "evictionResponders reference responders that react to Evictions based on EvictionRequests. Responders should observe and communicate through the Eviction Resource API to help with the graceful termination of a pod. The responders are selected sequentially, according to their specified priority.\n\nResponders should periodically report on an eviction progress by updating the .status.responders[].heartbeatTime field of the Eviction object. If this field is not updated within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder with a lower priority. If there is no other responder, the last default imperative-eviction.k8s.io/evictor responder with a priority of 100 will evict the pod using the imperative Eviction API (pods//eviction subresource).\n\nThe maximum length of the responders list is 10. Responders are not supported when the pod is part of a PodGroup (.spec.schedulingGroup is set). This field can only be set on creation and is immutable afterwards.", } func (PodSpec) SwaggerDoc() map[string]string { @@ -1983,22 +2037,13 @@ var map_PodStatus = map[string]string{ "allocatedResources": "AllocatedResources is the total requests allocated for this pod by the node. If pod-level requests are not set, this will be the total requests aggregated across containers in the pod.", "resources": "Resources represents the compute resource requests and limits that have been applied at the pod level if pod-level requests or limits are set in PodSpec.Resources", "nodeAllocatableResourceClaimStatuses": "NodeAllocatableResourceClaimStatuses contains the status of node-allocatable resources that were allocated for this pod through DRA claims. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages.", + "volumeHealth": "volumeHealth contains node-reported health for each volume the pod is using. Populated by the kubelet on the pod's node.", } func (PodStatus) SwaggerDoc() map[string]string { return map_PodStatus } -var map_PodStatusResult = map[string]string{ - "": "PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "status": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", -} - -func (PodStatusResult) SwaggerDoc() map[string]string { - return map_PodStatusResult -} - var map_PodTemplate = map[string]string{ "": "PodTemplate describes a template for creating copies of a predefined pod.", "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", @@ -2029,6 +2074,17 @@ func (PodTemplateSpec) SwaggerDoc() map[string]string { return map_PodTemplateSpec } +var map_PodVolumeHealth = map[string]string{ + "": "PodVolumeHealth contains health information for a volume used by a pod, reported by the CSI node plugin via the kubelet.", + "name": "name matches an entry in pod.spec.volumes.", + "healthConditions": "conditions is the set of adverse conditions reported by the CSI node plugin for this volume on this node. At most 16 conditions may be reported.", + "lastTransitionTime": "lastTransitionTime is when the current set of conditions first appeared.", +} + +func (PodVolumeHealth) SwaggerDoc() map[string]string { + return map_PodVolumeHealth +} + var map_PortStatus = map[string]string{ "": "PortStatus represents the error condition of a service port", "port": "Port is the port number of the service port of which status is recorded here", @@ -2112,6 +2168,7 @@ var map_ProjectedVolumeSource = map[string]string{ "": "Represents a projected volume source", "sources": "sources is the list of volume projections. Each entry in this list handles one source.", "defaultMode": "defaultMode are the mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", + "defaultUser": "defaultUser is Optional: The owner UID of the created files by default. The defaultUser field is only used as a fallback when the item-level user field is unset. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (ProjectedVolumeSource) SwaggerDoc() map[string]string { @@ -2322,7 +2379,7 @@ func (ResourceRequirements) SwaggerDoc() map[string]string { var map_ResourceStatus = map[string]string{ "": "ResourceStatus represents the status of a single resource allocated to a Pod.", - "name": "Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. For DRA resources, the value must be \"claim:/\". When this status is reported about a container, the \"claim_name\" and \"request\" must match one of the claims of this container.", + "name": "Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. For DRA resources, the value must be \"claim:/\" when container.resources.claims[*].request is set or \"claim:\" when container.resources.claims[*].request is empty. For DRA-backed extended resources, \"claim:/\" is used when the claim name and request name are recorded in pod.status.extendedResourceClaimStatus. When this status is reported about a container, the \"claim_name\" and \"request\" must match one of the claims of this container.", "resources": "List of unique resources health. Each element in the list contains an unique resource ID and its health. At a minimum, for the lifetime of a Pod, resource ID must uniquely identify the resource allocated to the Pod on the Node. If other Pod on the same Node reports the status with the same resource ID, it must be the same resource they share. See ResourceID type definition for a specific format it has in various use cases.", } @@ -2476,6 +2533,7 @@ var map_SecretVolumeSource = map[string]string{ "items": "items If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", "defaultMode": "defaultMode is Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", "optional": "optional field specify whether the Secret or its keys must be defined", + "defaultUser": "defaultUser is Optional: The owner UID of the created files by default. The defaultUser field is only used as a fallback when the item-level user field is unset. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (SecretVolumeSource) SwaggerDoc() map[string]string { @@ -2549,6 +2607,7 @@ var map_ServiceAccountTokenProjection = map[string]string{ "audience": "audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.", "expirationSeconds": "expirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.", "path": "path is the path relative to the mount point of the file to project the token into.", + "user": "user is Optional: The owner UID of the created file. If specified, the item-level user field takes precedence over defaultUser. (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled.", } func (ServiceAccountTokenProjection) SwaggerDoc() map[string]string { @@ -2792,15 +2851,37 @@ func (VolumeDevice) SwaggerDoc() map[string]string { return map_VolumeDevice } +var map_VolumeHealthCondition = map[string]string{ + "": "VolumeHealthCondition represents an adverse health condition reported for a volume.", + "status": "status is the machine-parseable health category. Possible values: - \"Inaccessible\": the volume cannot be accessed. - \"DataLoss\": data loss has been detected on the volume. - \"Degraded\": the volume is functioning with reduced capability.", + "reason": "reason is a brief CamelCase machine-parseable reason. Together with status it forms the unique identity of a condition entry. Maximum permitted length of a reason is 256 bytes.", + "message": "message is a human-readable description. Maximum permitted length of a message is 1024 bytes.", +} + +func (VolumeHealthCondition) SwaggerDoc() map[string]string { + return map_VolumeHealthCondition +} + +var map_VolumeHealthStatus = map[string]string{ + "": "VolumeHealthStatus contains health information for a volume reported by the CSI controller plugin.", + "healthConditions": "conditions is the set of adverse conditions reported by the CSI controller plugin. An empty list means no adverse condition. At most 16 conditions may be reported.", + "lastTransitionTime": "lastTransitionTime is when the current set of conditions first appeared.", +} + +func (VolumeHealthStatus) SwaggerDoc() map[string]string { + return map_VolumeHealthStatus +} + var map_VolumeMount = map[string]string{ "": "VolumeMount describes a mounting of a Volume within a container.", "name": "This must match the Name of a Volume.", "readOnly": "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", "recursiveReadOnly": "RecursiveReadOnly specifies whether read-only mounts should be handled recursively.\n\nIf ReadOnly is false, this field has no meaning and must be unspecified.\n\nIf ReadOnly is true, and this field is set to Disabled, the mount is not made recursively read-only. If this field is set to IfPossible, the mount is made recursively read-only, if it is supported by the container runtime. If this field is set to Enabled, the mount is made recursively read-only if it is supported by the container runtime, otherwise the pod will not be started and an error will be generated to indicate the reason.\n\nIf this field is set to IfPossible or Enabled, MountPropagation must be set to None (or be unspecified, which defaults to None).\n\nIf this field is not specified, it is treated as an equivalent of Disabled.", - "mountPath": "Path within the container at which the volume should be mounted. Must not contain ':'.", + "mountPath": "Path within the container at which the volume should be mounted.", "subPath": "Path within the volume from which the container's volume should be mounted. Defaults to \"\" (volume's root).", "mountPropagation": "mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10. When RecursiveReadOnly is set to IfPossible or to Enabled, MountPropagation must be None or unspecified (which defaults to None).", "subPathExpr": "Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to \"\" (volume's root). SubPathExpr and SubPath are mutually exclusive.", + "bindMountOptions": "bindMountOptions is the list of additional bind mount options to apply when mounting this volume into the container. Allowed values are noexec, nodev, and nosuid. These are Linux mount options and have no effect on Windows nodes. This field is not supported with image volumes. This is an alpha field and requires enabling the VolumeBindMountOptions feature gate.", } func (VolumeMount) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/core/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/core/v1/zz_generated.deepcopy.go index 10af6c17d..4a0b717f3 100644 --- a/constraint/vendor/k8s.io/api/core/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/core/v1/zz_generated.deepcopy.go @@ -22,7 +22,6 @@ limitations under the License. package v1 import ( - resource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" types "k8s.io/apimachinery/pkg/types" @@ -485,6 +484,11 @@ func (in *ClusterTrustBundleProjection) DeepCopyInto(out *ClusterTrustBundleProj *out = new(bool) **out = **in } + if in.User != nil { + in, out := &in.User, &out.User + *out = new(int64) + **out = **in + } return } @@ -774,6 +778,11 @@ func (in *ConfigMapVolumeSource) DeepCopyInto(out *ConfigMapVolumeSource) { *out = new(bool) **out = **in } + if in.DefaultUser != nil { + in, out := &in.DefaultUser, &out.DefaultUser + *out = new(int64) + **out = **in + } return } @@ -1217,6 +1226,11 @@ func (in *DownwardAPIVolumeFile) DeepCopyInto(out *DownwardAPIVolumeFile) { *out = new(int32) **out = **in } + if in.User != nil { + in, out := &in.User, &out.User + *out = new(int64) + **out = **in + } return } @@ -1245,6 +1259,11 @@ func (in *DownwardAPIVolumeSource) DeepCopyInto(out *DownwardAPIVolumeSource) { *out = new(int32) **out = **in } + if in.DefaultUser != nil { + in, out := &in.DefaultUser, &out.DefaultUser + *out = new(int64) + **out = **in + } return } @@ -1266,6 +1285,11 @@ func (in *EmptyDirVolumeSource) DeepCopyInto(out *EmptyDirVolumeSource) { x := (*in).DeepCopy() *out = &x } + if in.Mode != nil { + in, out := &in.Mode, &out.Mode + *out = new(int32) + **out = **in + } return } @@ -1762,6 +1786,27 @@ func (in *EventSource) DeepCopy() *EventSource { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionResponder) DeepCopyInto(out *EvictionResponder) { + *out = *in + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionResponder. +func (in *EvictionResponder) DeepCopy() *EvictionResponder { + if in == nil { + return nil + } + out := new(EvictionResponder) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExecAction) DeepCopyInto(out *ExecAction) { *out = *in @@ -1931,6 +1976,11 @@ func (in *GRPCAction) DeepCopyInto(out *GRPCAction) { *out = new(string) **out = **in } + if in.Mode != nil { + in, out := &in.Mode, &out.Mode + *out = new(GRPCProbeMode) + **out = **in + } return } @@ -2006,6 +2056,11 @@ func (in *HTTPGetAction) DeepCopyInto(out *HTTPGetAction) { *out = make([]HTTPHeader, len(*in)) copy(*out, *in) } + if in.Protocol != nil { + in, out := &in.Protocol, &out.Protocol + *out = new(HTTPProtocol) + **out = **in + } return } @@ -2195,6 +2250,11 @@ func (in *KeyToPath) DeepCopyInto(out *KeyToPath) { *out = new(int32) **out = **in } + if in.User != nil { + in, out := &in.User, &out.User + *out = new(int64) + **out = **in + } return } @@ -2777,6 +2837,53 @@ func (in *NodeAffinity) DeepCopy() *NodeAffinity { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableMappedResources) DeepCopyInto(out *NodeAllocatableMappedResources) { + *out = *in + if in.Quantity != nil { + in, out := &in.Quantity, &out.Quantity + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableMappedResources. +func (in *NodeAllocatableMappedResources) DeepCopy() *NodeAllocatableMappedResources { + if in == nil { + return nil + } + out := new(NodeAllocatableMappedResources) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableOverheadResources) DeepCopyInto(out *NodeAllocatableOverheadResources) { + *out = *in + if in.PerPod != nil { + in, out := &in.PerPod, &out.PerPod + x := (*in).DeepCopy() + *out = &x + } + if in.PerContainer != nil { + in, out := &in.PerContainer, &out.PerContainer + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableOverheadResources. +func (in *NodeAllocatableOverheadResources) DeepCopy() *NodeAllocatableOverheadResources { + if in == nil { + return nil + } + out := new(NodeAllocatableOverheadResources) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeAllocatableResourceClaimStatus) DeepCopyInto(out *NodeAllocatableResourceClaimStatus) { *out = *in @@ -2785,11 +2892,18 @@ func (in *NodeAllocatableResourceClaimStatus) DeepCopyInto(out *NodeAllocatableR *out = make([]string, len(*in)) copy(*out, *in) } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make(map[ResourceName]resource.Quantity, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() + if in.Mapping != nil { + in, out := &in.Mapping, &out.Mapping + *out = make([]NodeAllocatableMappedResources, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Overhead != nil { + in, out := &in.Overhead, &out.Overhead + *out = make([]NodeAllocatableOverheadResources, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) } } return @@ -2946,6 +3060,27 @@ func (in *NodeList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodePodPreemptionPolicy) DeepCopyInto(out *NodePodPreemptionPolicy) { + *out = *in + if in.DisableResizePreemption != nil { + in, out := &in.DisableResizePreemption, &out.DisableResizePreemption + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodePodPreemptionPolicy. +func (in *NodePodPreemptionPolicy) DeepCopy() *NodePodPreemptionPolicy { + if in == nil { + return nil + } + out := new(NodePodPreemptionPolicy) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NodeProxyOptions) DeepCopyInto(out *NodeProxyOptions) { *out = *in @@ -3112,6 +3247,11 @@ func (in *NodeSpec) DeepCopyInto(out *NodeSpec) { *out = new(NodeConfigSource) (*in).DeepCopyInto(*out) } + if in.PodPreemptionPolicy != nil { + in, out := &in.PodPreemptionPolicy, &out.PodPreemptionPolicy + *out = new(NodePodPreemptionPolicy) + (*in).DeepCopyInto(*out) + } return } @@ -3237,6 +3377,11 @@ func (in *NodeSystemInfo) DeepCopyInto(out *NodeSystemInfo) { *out = new(NodeSwapStatus) (*in).DeepCopyInto(*out) } + if in.RunningInUserNamespace != nil { + in, out := &in.RunningInUserNamespace, &out.RunningInUserNamespace + *out = new(bool) + **out = **in + } return } @@ -3495,6 +3640,11 @@ func (in *PersistentVolumeClaimStatus) DeepCopyInto(out *PersistentVolumeClaimSt *out = new(ModifyVolumeStatus) **out = **in } + if in.HealthStatus != nil { + in, out := &in.HealthStatus, &out.HealthStatus + *out = new(VolumeHealthStatus) + (*in).DeepCopyInto(*out) + } return } @@ -3960,6 +4110,11 @@ func (in *PodCertificateProjection) DeepCopyInto(out *PodCertificateProjection) (*out)[key] = val } } + if in.User != nil { + in, out := &in.User, &out.User + *out = new(int64) + **out = **in + } return } @@ -4640,6 +4795,13 @@ func (in *PodSpec) DeepCopyInto(out *PodSpec) { *out = new(PodSchedulingGroup) (*in).DeepCopyInto(*out) } + if in.EvictionResponders != nil { + in, out := &in.EvictionResponders, &out.EvictionResponders + *out = make([]EvictionResponder, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } return } @@ -4729,6 +4891,13 @@ func (in *PodStatus) DeepCopyInto(out *PodStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.VolumeHealth != nil { + in, out := &in.VolumeHealth, &out.VolumeHealth + *out = make([]PodVolumeHealth, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } return } @@ -4742,33 +4911,6 @@ func (in *PodStatus) DeepCopy() *PodStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodStatusResult) DeepCopyInto(out *PodStatusResult) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodStatusResult. -func (in *PodStatusResult) DeepCopy() *PodStatusResult { - if in == nil { - return nil - } - out := new(PodStatusResult) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PodStatusResult) 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 *PodTemplate) DeepCopyInto(out *PodTemplate) { *out = *in @@ -4847,6 +4989,28 @@ func (in *PodTemplateSpec) DeepCopy() *PodTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodVolumeHealth) DeepCopyInto(out *PodVolumeHealth) { + *out = *in + if in.HealthConditions != nil { + in, out := &in.HealthConditions, &out.HealthConditions + *out = make([]VolumeHealthCondition, len(*in)) + copy(*out, *in) + } + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodVolumeHealth. +func (in *PodVolumeHealth) DeepCopy() *PodVolumeHealth { + if in == nil { + return nil + } + out := new(PodVolumeHealth) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PortStatus) DeepCopyInto(out *PortStatus) { *out = *in @@ -5013,6 +5177,11 @@ func (in *ProjectedVolumeSource) DeepCopyInto(out *ProjectedVolumeSource) { *out = new(int32) **out = **in } + if in.DefaultUser != nil { + in, out := &in.DefaultUser, &out.DefaultUser + *out = new(int64) + **out = **in + } return } @@ -5835,6 +6004,11 @@ func (in *SecretVolumeSource) DeepCopyInto(out *SecretVolumeSource) { *out = new(bool) **out = **in } + if in.DefaultUser != nil { + in, out := &in.DefaultUser, &out.DefaultUser + *out = new(int64) + **out = **in + } return } @@ -6060,6 +6234,11 @@ func (in *ServiceAccountTokenProjection) DeepCopyInto(out *ServiceAccountTokenPr *out = new(int64) **out = **in } + if in.User != nil { + in, out := &in.User, &out.User + *out = new(int64) + **out = **in + } return } @@ -6575,6 +6754,44 @@ func (in *VolumeDevice) DeepCopy() *VolumeDevice { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *VolumeHealthCondition) DeepCopyInto(out *VolumeHealthCondition) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeHealthCondition. +func (in *VolumeHealthCondition) DeepCopy() *VolumeHealthCondition { + if in == nil { + return nil + } + out := new(VolumeHealthCondition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *VolumeHealthStatus) DeepCopyInto(out *VolumeHealthStatus) { + *out = *in + if in.HealthConditions != nil { + in, out := &in.HealthConditions, &out.HealthConditions + *out = make([]VolumeHealthCondition, len(*in)) + copy(*out, *in) + } + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeHealthStatus. +func (in *VolumeHealthStatus) DeepCopy() *VolumeHealthStatus { + if in == nil { + return nil + } + out := new(VolumeHealthStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeMount) DeepCopyInto(out *VolumeMount) { *out = *in @@ -6588,6 +6805,11 @@ func (in *VolumeMount) DeepCopyInto(out *VolumeMount) { *out = new(MountPropagationMode) **out = **in } + if in.BindMountOptions != nil { + in, out := &in.BindMountOptions, &out.BindMountOptions + *out = make([]string, len(*in)) + copy(*out, *in) + } return } diff --git a/constraint/vendor/k8s.io/api/core/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/core/v1/zz_generated.model_name.go index 8e79ad909..65cfb59c1 100644 --- a/constraint/vendor/k8s.io/api/core/v1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/core/v1/zz_generated.model_name.go @@ -326,6 +326,11 @@ func (in EventSource) OpenAPIModelName() string { return "io.k8s.api.core.v1.EventSource" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionResponder) OpenAPIModelName() string { + return "io.k8s.api.core.v1.EvictionResponder" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in ExecAction) OpenAPIModelName() string { return "io.k8s.api.core.v1.ExecAction" @@ -541,6 +546,16 @@ func (in NodeAffinity) OpenAPIModelName() string { return "io.k8s.api.core.v1.NodeAffinity" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableMappedResources) OpenAPIModelName() string { + return "io.k8s.api.core.v1.NodeAllocatableMappedResources" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableOverheadResources) OpenAPIModelName() string { + return "io.k8s.api.core.v1.NodeAllocatableOverheadResources" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in NodeAllocatableResourceClaimStatus) OpenAPIModelName() string { return "io.k8s.api.core.v1.NodeAllocatableResourceClaimStatus" @@ -576,6 +591,11 @@ func (in NodeList) OpenAPIModelName() string { return "io.k8s.api.core.v1.NodeList" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodePodPreemptionPolicy) OpenAPIModelName() string { + return "io.k8s.api.core.v1.NodePodPreemptionPolicy" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in NodeProxyOptions) OpenAPIModelName() string { return "io.k8s.api.core.v1.NodeProxyOptions" @@ -831,11 +851,6 @@ func (in PodStatus) OpenAPIModelName() string { return "io.k8s.api.core.v1.PodStatus" } -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodStatusResult) OpenAPIModelName() string { - return "io.k8s.api.core.v1.PodStatusResult" -} - // OpenAPIModelName returns the OpenAPI model name for this type. func (in PodTemplate) OpenAPIModelName() string { return "io.k8s.api.core.v1.PodTemplate" @@ -851,6 +866,11 @@ func (in PodTemplateSpec) OpenAPIModelName() string { return "io.k8s.api.core.v1.PodTemplateSpec" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodVolumeHealth) OpenAPIModelName() string { + return "io.k8s.api.core.v1.PodVolumeHealth" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in PortStatus) OpenAPIModelName() string { return "io.k8s.api.core.v1.PortStatus" @@ -1176,6 +1196,16 @@ func (in VolumeDevice) OpenAPIModelName() string { return "io.k8s.api.core.v1.VolumeDevice" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in VolumeHealthCondition) OpenAPIModelName() string { + return "io.k8s.api.core.v1.VolumeHealthCondition" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in VolumeHealthStatus) OpenAPIModelName() string { + return "io.k8s.api.core.v1.VolumeHealthStatus" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in VolumeMount) OpenAPIModelName() string { return "io.k8s.api.core.v1.VolumeMount" diff --git a/constraint/vendor/k8s.io/api/core/v1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/core/v1/zz_generated.prerelease-lifecycle.go index 6710a96d1..d473e3099 100644 --- a/constraint/vendor/k8s.io/api/core/v1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/core/v1/zz_generated.prerelease-lifecycle.go @@ -177,12 +177,6 @@ func (in *PodProxyOptions) APILifecycleIntroduced() (major, minor int) { return 1, 0 } -// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. -func (in *PodStatusResult) APILifecycleIntroduced() (major, minor int) { - return 1, 0 -} - // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *PodTemplate) APILifecycleIntroduced() (major, minor int) { diff --git a/constraint/vendor/k8s.io/api/discovery/v1/generated.proto b/constraint/vendor/k8s.io/api/discovery/v1/generated.proto index edbc4304b..a1713290d 100644 --- a/constraint/vendor/k8s.io/api/discovery/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/discovery/v1/generated.proto @@ -39,8 +39,8 @@ message Endpoint { // additional addresses beyond the first, and kube-proxy does not look at them. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxItems=100 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxItems=100 repeated string addresses = 1; // conditions contains information about the current status of the endpoint. @@ -185,15 +185,15 @@ message EndpointSlice { // slices of addressType "IPv4" and "IPv6". No semantics are defined for // the "FQDN" type. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional string addressType = 4; // endpoints is a list of unique endpoints in this slice. Each slice may // include a maximum of 1000 endpoints. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Endpoint endpoints = 2; // ports specifies the list of network ports exposed by each endpoint in diff --git a/constraint/vendor/k8s.io/api/discovery/v1/types.go b/constraint/vendor/k8s.io/api/discovery/v1/types.go index c291ed85d..a5b5f827b 100644 --- a/constraint/vendor/k8s.io/api/discovery/v1/types.go +++ b/constraint/vendor/k8s.io/api/discovery/v1/types.go @@ -32,7 +32,7 @@ import ( // by listing EndpointSlices in the service's namespace whose `kubernetes.io/service-name` // label contains the service's name. type EndpointSlice struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional @@ -49,15 +49,15 @@ type EndpointSlice struct { // slices of addressType "IPv4" and "IPv6". No semantics are defined for // the "FQDN" type. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable AddressType AddressType `json:"addressType" protobuf:"bytes,4,rep,name=addressType"` // endpoints is a list of unique endpoints in this slice. Each slice may // include a maximum of 1000 endpoints. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Endpoints []Endpoint `json:"endpoints" protobuf:"bytes,2,rep,name=endpoints"` // ports specifies the list of network ports exposed by each endpoint in @@ -73,7 +73,7 @@ type EndpointSlice struct { // AddressType represents the type of address referred to by an endpoint. // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type AddressType string const ( @@ -97,8 +97,8 @@ type Endpoint struct { // additional addresses beyond the first, and kube-proxy does not look at them. // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxItems=100 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxItems=100 Addresses []string `json:"addresses" protobuf:"bytes,1,rep,name=addresses"` // conditions contains information about the current status of the endpoint. @@ -238,7 +238,7 @@ type EndpointPort struct { // EndpointSliceList represents a list of endpoint slices type EndpointSliceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional diff --git a/constraint/vendor/k8s.io/api/discovery/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/discovery/v1beta1/generated.proto index 9b6edb147..fa45b0ed9 100644 --- a/constraint/vendor/k8s.io/api/discovery/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/discovery/v1beta1/generated.proto @@ -39,8 +39,8 @@ message Endpoint { // use the first element. Refer to: https://issue.k8s.io/106267 // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxItems=100 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxItems=100 repeated string addresses = 1; // conditions contains information about the current status of the endpoint. @@ -171,14 +171,14 @@ message EndpointSlice { // * IPv6: Represents an IPv6 Address. // * FQDN: Represents a Fully Qualified Domain Name. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional string addressType = 4; // endpoints is a list of unique endpoints in this slice. Each slice may // include a maximum of 1000 endpoints. // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Endpoint endpoints = 2; // ports specifies the list of network ports exposed by each endpoint in diff --git a/constraint/vendor/k8s.io/api/discovery/v1beta1/types.go b/constraint/vendor/k8s.io/api/discovery/v1beta1/types.go index 1334194d2..ef7cf4ab3 100644 --- a/constraint/vendor/k8s.io/api/discovery/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/discovery/v1beta1/types.go @@ -32,7 +32,7 @@ import ( // For a given service there may be multiple EndpointSlice objects, selected by // labels, which must be joined to produce the full set of endpoints. type EndpointSlice struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional @@ -46,14 +46,14 @@ type EndpointSlice struct { // * IPv6: Represents an IPv6 Address. // * FQDN: Represents a Fully Qualified Domain Name. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable AddressType AddressType `json:"addressType" protobuf:"bytes,4,rep,name=addressType"` // endpoints is a list of unique endpoints in this slice. Each slice may // include a maximum of 1000 endpoints. // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Endpoints []Endpoint `json:"endpoints" protobuf:"bytes,2,rep,name=endpoints"` // ports specifies the list of network ports exposed by each endpoint in @@ -68,7 +68,7 @@ type EndpointSlice struct { // AddressType represents the type of address referred to by an endpoint. // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type AddressType string const ( @@ -92,8 +92,8 @@ type Endpoint struct { // use the first element. Refer to: https://issue.k8s.io/106267 // +listType=set // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxItems=100 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxItems=100 Addresses []string `json:"addresses" protobuf:"bytes,1,rep,name=addresses"` // conditions contains information about the current status of the endpoint. @@ -228,7 +228,7 @@ type EndpointPort struct { // EndpointSliceList represents a list of endpoint slices type EndpointSliceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional diff --git a/constraint/vendor/k8s.io/api/events/v1/generated.proto b/constraint/vendor/k8s.io/api/events/v1/generated.proto index 6c7e4cca1..f1e63a33a 100644 --- a/constraint/vendor/k8s.io/api/events/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/events/v1/generated.proto @@ -36,7 +36,7 @@ option go_package = "k8s.io/api/events/v1"; // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. message Event { - // Standard object's metadata. + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -105,7 +105,7 @@ message Event { // EventList is a list of Event objects. message EventList { - // Standard list metadata. + // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; diff --git a/constraint/vendor/k8s.io/api/events/v1/types.go b/constraint/vendor/k8s.io/api/events/v1/types.go index 86b12eee1..c54528410 100644 --- a/constraint/vendor/k8s.io/api/events/v1/types.go +++ b/constraint/vendor/k8s.io/api/events/v1/types.go @@ -32,9 +32,9 @@ import ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type Event struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // 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" protobuf:"bytes,1,opt,name=metadata"` @@ -114,8 +114,8 @@ type EventSeries struct { // EventList is a list of Event objects. type EventList struct { - metav1.TypeMeta `json:",inline"` - // Standard list metadata. + metav1.TypeMeta `json:""` + // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/events/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/events/v1/types_swagger_doc_generated.go index 44ac0c3bb..f5b83f049 100644 --- a/constraint/vendor/k8s.io/api/events/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/events/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Event = map[string]string{ "": "Event is a report of an event somewhere in the cluster. It generally denotes some state change in the system. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "eventTime": "eventTime is the time when this Event was first observed. It is required.", "series": "series is data about the Event series this event represents or nil if it's a singleton Event.", "reportingController": "reportingController is the name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. This field cannot be empty for new Events.", @@ -52,7 +52,7 @@ func (Event) SwaggerDoc() map[string]string { var map_EventList = map[string]string{ "": "EventList is a list of Event objects.", - "metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "items": "items is a list of schema objects.", } diff --git a/constraint/vendor/k8s.io/api/events/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/events/v1beta1/generated.proto index fbdb30970..6e39c03bc 100644 --- a/constraint/vendor/k8s.io/api/events/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/events/v1beta1/generated.proto @@ -36,7 +36,7 @@ option go_package = "k8s.io/api/events/v1beta1"; // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. message Event { - // Standard object's metadata. + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -109,7 +109,7 @@ message Event { // EventList is a list of Event objects. message EventList { - // Standard list metadata. + // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; diff --git a/constraint/vendor/k8s.io/api/events/v1beta1/types.go b/constraint/vendor/k8s.io/api/events/v1beta1/types.go index 5bb6f92b2..dfe1e4cc1 100644 --- a/constraint/vendor/k8s.io/api/events/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/events/v1beta1/types.go @@ -33,9 +33,9 @@ import ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type Event struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // 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" protobuf:"bytes,1,opt,name=metadata"` @@ -120,8 +120,8 @@ type EventSeries struct { // EventList is a list of Event objects. type EventList struct { - metav1.TypeMeta `json:",inline"` - // Standard list metadata. + metav1.TypeMeta `json:""` + // metadata is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/events/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/events/v1beta1/types_swagger_doc_generated.go index e6c28a4f8..4f188b2ab 100644 --- a/constraint/vendor/k8s.io/api/events/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/events/v1beta1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1beta1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Event = map[string]string{ "": "Event is a report of an event somewhere in the cluster. It generally denotes some state change in the system. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "eventTime": "eventTime is the time when this Event was first observed. It is required.", "series": "series is data about the Event series this event represents or nil if it's a singleton Event.", "reportingController": "reportingController is the name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. This field cannot be empty for new Events.", @@ -52,7 +52,7 @@ func (Event) SwaggerDoc() map[string]string { var map_EventList = map[string]string{ "": "EventList is a list of Event objects.", - "metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "items": "items is a list of schema objects.", } diff --git a/constraint/vendor/k8s.io/api/extensions/v1beta1/doc.go b/constraint/vendor/k8s.io/api/extensions/v1beta1/doc.go index bf39ca3e1..98ccb7685 100644 --- a/constraint/vendor/k8s.io/api/extensions/v1beta1/doc.go +++ b/constraint/vendor/k8s.io/api/extensions/v1beta1/doc.go @@ -19,7 +19,8 @@ limitations under the License. // +k8s:openapi-gen=true // +k8s:prerelease-lifecycle-gen=true // +k8s:openapi-model-package=io.k8s.api.extensions.v1beta1 -// +k8s:validation-gen=TypeMeta -// +k8s:validation-gen-input=k8s.io/api/extensions/v1beta1 +// extensions/v1beta1 is permanently unserved, so version-specific declarative +// validation here is unreachable. +// +k8s:validation-gen=false package v1beta1 diff --git a/constraint/vendor/k8s.io/api/extensions/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/extensions/v1beta1/generated.proto index f09030668..9d45061d5 100644 --- a/constraint/vendor/k8s.io/api/extensions/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/extensions/v1beta1/generated.proto @@ -33,6 +33,7 @@ option go_package = "k8s.io/api/extensions/v1beta1"; // DEPRECATED - This group version of DaemonSet is deprecated by apps/v1beta2/DaemonSet. See the release notes for // more information. // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" message DaemonSet { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -202,6 +203,7 @@ message DaemonSetUpdateStrategy { // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/status" message Deployment { // Standard object metadata. // +optional @@ -429,7 +431,7 @@ message IPBlock { // CIDR is a string representing the IP Block // Valid examples are "192.168.1.0/24" or "2001:db8::/64" // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string cidr = 1; // Except is a slice of CIDRs that should not be included within an IP Block @@ -445,6 +447,7 @@ message IPBlock { // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. // DEPRECATED - This group version of Ingress is deprecated by networking.k8s.io/v1beta1 Ingress. See the release notes for more information. +// +k8s:supportsSubresource="/status" message Ingress { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -688,7 +691,7 @@ message NetworkPolicyEgressRule { // allows traffic only if the traffic matches at least one item in the to list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyPeer to = 2; } @@ -711,7 +714,7 @@ message NetworkPolicyIngressRule { // traffic matches at least one item in the from list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyPeer from = 2; } @@ -750,7 +753,7 @@ message NetworkPolicyPeer { // IPBlock defines policy on a particular IPBlock. If this field is set then // neither of the other fields can be. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional IPBlock ipBlock = 3; } @@ -794,7 +797,7 @@ message NetworkPolicySpec { // (and serves solely to ensure that the pods it selects are isolated by default). // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyIngressRule ingress = 2; // List of egress rules to be applied to the selected pods. Outgoing traffic is @@ -806,7 +809,7 @@ message NetworkPolicySpec { // This field is beta-level in 1.8 // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyEgressRule egress = 3; // List of rule types that the NetworkPolicy relates to. @@ -827,6 +830,7 @@ message NetworkPolicySpec { // DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1beta2/ReplicaSet. See the release notes for // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/status" message ReplicaSet { // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -1046,9 +1050,9 @@ message Scale { message ScaleSpec { // desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 optional int32 replicas = 1; } diff --git a/constraint/vendor/k8s.io/api/extensions/v1beta1/types.go b/constraint/vendor/k8s.io/api/extensions/v1beta1/types.go index 09d143ea6..e0caf1982 100644 --- a/constraint/vendor/k8s.io/api/extensions/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/extensions/v1beta1/types.go @@ -27,9 +27,9 @@ import ( type ScaleSpec struct { // desired number of instances for the scaled object. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +default=0 - // +k8s:alpha(since: "1.36")=+k8s:minimum=0 + // +k8s:beta(since: "1.37")=+k8s:minimum=0 Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } @@ -61,7 +61,7 @@ type ScaleStatus struct { // represents a scaling request for a resource. type Scale struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -88,8 +88,9 @@ type Scale struct { // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for // more information. // Deployment enables declarative updates for Pods and ReplicaSets. +// +k8s:supportsSubresource="/status" type Deployment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -164,7 +165,7 @@ type DeploymentSpec struct { // DEPRECATED. // DeploymentRollback stores the information required to rollback a deployment. type DeploymentRollback struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Required: This must match the Name of a deployment. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // The annotations to be updated to a deployment @@ -333,7 +334,7 @@ type DeploymentCondition struct { // DeploymentList is a list of Deployments. type DeploymentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -539,8 +540,9 @@ type DaemonSetCondition struct { // DEPRECATED - This group version of DaemonSet is deprecated by apps/v1beta2/DaemonSet. See the release notes for // more information. // DaemonSet represents the configuration of a daemon set. +// +k8s:supportsSubresource="/status" type DaemonSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -581,7 +583,7 @@ const ( // DaemonSetList is a collection of daemon sets. type DaemonSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -603,8 +605,9 @@ type DaemonSetList struct { // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. // DEPRECATED - This group version of Ingress is deprecated by networking.k8s.io/v1beta1 Ingress. See the release notes for more information. +// +k8s:supportsSubresource="/status" type Ingress struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -629,7 +632,7 @@ type Ingress struct { // IngressList is a collection of Ingress. type IngressList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -786,7 +789,7 @@ type IngressRule struct { // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. // +optional - IngressRuleValue `json:",inline" protobuf:"bytes,2,opt,name=ingressRuleValue"` + IngressRuleValue `json:"" protobuf:"bytes,2,opt,name=ingressRuleValue"` } // IngressRuleValue represents a rule to apply against incoming requests. If the @@ -914,8 +917,9 @@ type IngressBackend struct { // DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1beta2/ReplicaSet. See the release notes for // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. +// +k8s:supportsSubresource="/status" type ReplicaSet struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. @@ -945,7 +949,7 @@ type ReplicaSet struct { // ReplicaSetList is a collection of ReplicaSets. type ReplicaSetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1060,7 +1064,7 @@ type ReplicaSetCondition struct { // DEPRECATED 1.9 - This group version of NetworkPolicy is deprecated by networking/v1/NetworkPolicy. // NetworkPolicy describes what network traffic is allowed for a set of Pods type NetworkPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -1106,7 +1110,7 @@ type NetworkPolicySpec struct { // (and serves solely to ensure that the pods it selects are isolated by default). // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"` // List of egress rules to be applied to the selected pods. Outgoing traffic is @@ -1118,7 +1122,7 @@ type NetworkPolicySpec struct { // This field is beta-level in 1.8 // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Egress []NetworkPolicyEgressRule `json:"egress,omitempty" protobuf:"bytes,3,rep,name=egress"` // List of rule types that the NetworkPolicy relates to. @@ -1155,7 +1159,7 @@ type NetworkPolicyIngressRule struct { // traffic matches at least one item in the from list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"` } @@ -1180,7 +1184,7 @@ type NetworkPolicyEgressRule struct { // allows traffic only if the traffic matches at least one item in the to list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional To []NetworkPolicyPeer `json:"to,omitempty" protobuf:"bytes,2,rep,name=to"` } @@ -1214,7 +1218,7 @@ type IPBlock struct { // CIDR is a string representing the IP Block // Valid examples are "192.168.1.0/24" or "2001:db8::/64" // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required CIDR string `json:"cidr" protobuf:"bytes,1,name=cidr"` // Except is a slice of CIDRs that should not be included within an IP Block // Valid examples are "192.168.1.0/24" or "2001:db8::/64" @@ -1247,7 +1251,7 @@ type NetworkPolicyPeer struct { // IPBlock defines policy on a particular IPBlock. If this field is set then // neither of the other fields can be. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional IPBlock *IPBlock `json:"ipBlock,omitempty" protobuf:"bytes,3,rep,name=ipBlock"` } @@ -1260,7 +1264,7 @@ type NetworkPolicyPeer struct { // DEPRECATED 1.9 - This group version of NetworkPolicyList is deprecated by networking/v1/NetworkPolicyList. // Network Policy List is a list of NetworkPolicy objects. type NetworkPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/extensions/v1beta1/zz_generated.validations.go b/constraint/vendor/k8s.io/api/extensions/v1beta1/zz_generated.validations.go deleted file mode 100644 index d504d5452..000000000 --- a/constraint/vendor/k8s.io/api/extensions/v1beta1/zz_generated.validations.go +++ /dev/null @@ -1,279 +0,0 @@ -//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 validation-gen. DO NOT EDIT. - -package v1beta1 - -import ( - context "context" - fmt "fmt" - - equality "k8s.io/apimachinery/pkg/api/equality" - operation "k8s.io/apimachinery/pkg/api/operation" - safe "k8s.io/apimachinery/pkg/api/safe" - validate "k8s.io/apimachinery/pkg/api/validate" - runtime "k8s.io/apimachinery/pkg/runtime" - field "k8s.io/apimachinery/pkg/util/validation/field" -) - -func init() { localSchemeBuilder.Register(RegisterValidations) } - -// RegisterValidations adds validation functions to the given scheme. -// Public to allow building arbitrary schemes. -func RegisterValidations(scheme *runtime.Scheme) error { - // type NetworkPolicy - scheme.AddValidationFunc((*NetworkPolicy)(nil), func(ctx context.Context, op operation.Operation, obj, oldObj interface{}) field.ErrorList { - switch op.Request.SubresourcePath() { - case "/": - return Validate_NetworkPolicy(ctx, op, nil /* fldPath */, obj.(*NetworkPolicy), safe.Cast[*NetworkPolicy](oldObj)) - } - return field.ErrorList{field.InternalError(nil, fmt.Errorf("no validation found for %T, subresource: %v", obj, op.Request.SubresourcePath()))} - }) - // type Scale - scheme.AddValidationFunc((*Scale)(nil), func(ctx context.Context, op operation.Operation, obj, oldObj interface{}) field.ErrorList { - switch op.Request.SubresourcePath() { - case "/scale": - return Validate_Scale(ctx, op, nil /* fldPath */, obj.(*Scale), safe.Cast[*Scale](oldObj)) - } - return field.ErrorList{field.InternalError(nil, fmt.Errorf("no validation found for %T, subresource: %v", obj, op.Request.SubresourcePath()))} - }) - return nil -} - -// Validate_IPBlock validates an instance of IPBlock according -// to declarative validation rules in the API schema. -func Validate_IPBlock(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *IPBlock) (errs field.ErrorList) { - // field IPBlock.CIDR - errs = append(errs, - func(fldPath *field.Path, obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && (obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj)) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - return - }(fldPath.Child("cidr"), &obj.CIDR, safe.Field(oldObj, func(oldObj *IPBlock) *string { return &oldObj.CIDR }), oldObj != nil)...) - - // field IPBlock.Except has no validation - return errs -} - -// Validate_NetworkPolicy validates an instance of NetworkPolicy according -// to declarative validation rules in the API schema. -func Validate_NetworkPolicy(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *NetworkPolicy) (errs field.ErrorList) { - // field NetworkPolicy.TypeMeta has no validation - // field NetworkPolicy.ObjectMeta has no validation - - // field NetworkPolicy.Spec - errs = append(errs, - func(fldPath *field.Path, obj, oldObj *NetworkPolicySpec, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call the type's validation function - errs = append(errs, Validate_NetworkPolicySpec(ctx, op, fldPath, obj, oldObj)...) - return - }(fldPath.Child("spec"), &obj.Spec, safe.Field(oldObj, func(oldObj *NetworkPolicy) *NetworkPolicySpec { return &oldObj.Spec }), oldObj != nil)...) - - return errs -} - -// Validate_NetworkPolicyEgressRule validates an instance of NetworkPolicyEgressRule according -// to declarative validation rules in the API schema. -func Validate_NetworkPolicyEgressRule(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *NetworkPolicyEgressRule) (errs field.ErrorList) { - // field NetworkPolicyEgressRule.Ports has no validation - - // field NetworkPolicyEgressRule.To - errs = append(errs, - func(fldPath *field.Path, obj, oldObj []NetworkPolicyPeer, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - // iterate the list and call the type's validation function - errs = append(errs, validate.EachSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_NetworkPolicyPeer)...) - return - }(fldPath.Child("to"), obj.To, safe.Field(oldObj, func(oldObj *NetworkPolicyEgressRule) []NetworkPolicyPeer { return oldObj.To }), oldObj != nil)...) - - return errs -} - -// Validate_NetworkPolicyIngressRule validates an instance of NetworkPolicyIngressRule according -// to declarative validation rules in the API schema. -func Validate_NetworkPolicyIngressRule(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *NetworkPolicyIngressRule) (errs field.ErrorList) { - // field NetworkPolicyIngressRule.Ports has no validation - - // field NetworkPolicyIngressRule.From - errs = append(errs, - func(fldPath *field.Path, obj, oldObj []NetworkPolicyPeer, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - // iterate the list and call the type's validation function - errs = append(errs, validate.EachSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_NetworkPolicyPeer)...) - return - }(fldPath.Child("from"), obj.From, safe.Field(oldObj, func(oldObj *NetworkPolicyIngressRule) []NetworkPolicyPeer { return oldObj.From }), oldObj != nil)...) - - return errs -} - -// Validate_NetworkPolicyPeer validates an instance of NetworkPolicyPeer according -// to declarative validation rules in the API schema. -func Validate_NetworkPolicyPeer(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *NetworkPolicyPeer) (errs field.ErrorList) { - // field NetworkPolicyPeer.PodSelector has no validation - // field NetworkPolicyPeer.NamespaceSelector has no validation - - // field NetworkPolicyPeer.IPBlock - errs = append(errs, - func(fldPath *field.Path, obj, oldObj *IPBlock, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - // call the type's validation function - errs = append(errs, Validate_IPBlock(ctx, op, fldPath, obj, oldObj)...) - return - }(fldPath.Child("ipBlock"), obj.IPBlock, safe.Field(oldObj, func(oldObj *NetworkPolicyPeer) *IPBlock { return oldObj.IPBlock }), oldObj != nil)...) - - return errs -} - -// Validate_NetworkPolicySpec validates an instance of NetworkPolicySpec according -// to declarative validation rules in the API schema. -func Validate_NetworkPolicySpec(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *NetworkPolicySpec) (errs field.ErrorList) { - // field NetworkPolicySpec.PodSelector has no validation - - // field NetworkPolicySpec.Ingress - errs = append(errs, - func(fldPath *field.Path, obj, oldObj []NetworkPolicyIngressRule, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - // iterate the list and call the type's validation function - errs = append(errs, validate.EachSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_NetworkPolicyIngressRule)...) - return - }(fldPath.Child("ingress"), obj.Ingress, safe.Field(oldObj, func(oldObj *NetworkPolicySpec) []NetworkPolicyIngressRule { return oldObj.Ingress }), oldObj != nil)...) - - // field NetworkPolicySpec.Egress - errs = append(errs, - func(fldPath *field.Path, obj, oldObj []NetworkPolicyEgressRule, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && equality.Semantic.DeepEqual(obj, oldObj) { - return nil - } - // call field-attached validations - earlyReturn := false - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - // iterate the list and call the type's validation function - errs = append(errs, validate.EachSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_NetworkPolicyEgressRule)...) - return - }(fldPath.Child("egress"), obj.Egress, safe.Field(oldObj, func(oldObj *NetworkPolicySpec) []NetworkPolicyEgressRule { return oldObj.Egress }), oldObj != nil)...) - - // field NetworkPolicySpec.PolicyTypes has no validation - return errs -} - -// Validate_Scale validates an instance of Scale according -// to declarative validation rules in the API schema. -func Validate_Scale(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *Scale) (errs field.ErrorList) { - // field Scale.TypeMeta has no validation - // field Scale.ObjectMeta has no validation - - // field Scale.Spec - errs = append(errs, - func(fldPath *field.Path, obj, oldObj *ScaleSpec, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && (obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj)) { - return nil - } - // call the type's validation function - errs = append(errs, Validate_ScaleSpec(ctx, op, fldPath, obj, oldObj)...) - return - }(fldPath.Child("spec"), &obj.Spec, safe.Field(oldObj, func(oldObj *Scale) *ScaleSpec { return &oldObj.Spec }), oldObj != nil)...) - - // field Scale.Status has no validation - return errs -} - -// Validate_ScaleSpec validates an instance of ScaleSpec according -// to declarative validation rules in the API schema. -func Validate_ScaleSpec(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *ScaleSpec) (errs field.ErrorList) { - // field ScaleSpec.Replicas - errs = append(errs, - func(fldPath *field.Path, obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update && (obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj)) { - return nil - } - // call field-attached validations - errs = append(errs, validate.Minimum(ctx, op, fldPath, obj, oldObj, 0).MarkAlpha()...) - return - }(fldPath.Child("replicas"), &obj.Replicas, safe.Field(oldObj, func(oldObj *ScaleSpec) *int32 { return &oldObj.Replicas }), oldObj != nil)...) - - return errs -} diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1/generated.proto b/constraint/vendor/k8s.io/api/flowcontrol/v1/generated.proto index eb9186d01..29e51ed05 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1/generated.proto @@ -67,11 +67,13 @@ message FlowDistinguisherMethod { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required optional string type = 1; } // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" message FlowSchema { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -80,7 +82,7 @@ message FlowSchema { // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional FlowSchemaSpec spec = 2; // `status` is the current status of a FlowSchema. @@ -93,20 +95,24 @@ message FlowSchema { message FlowSchemaCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -126,6 +132,7 @@ message FlowSchemaSpec { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required optional PriorityLevelConfigurationReference priorityLevelConfiguration = 1; // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen @@ -165,6 +172,7 @@ message GroupSubject { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required optional string name = 1; } @@ -178,17 +186,17 @@ message LimitResponse { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required optional QueuingConfiguration queuing = 2; } @@ -221,6 +229,7 @@ message LimitedPriorityLevelConfiguration { optional int32 nominalConcurrencyShares = 1; // `limitResponse` indicates what to do with requests that can not be executed right now + // +required optional LimitResponse limitResponse = 2; // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -261,6 +270,7 @@ message NonResourcePolicyRule { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. @@ -273,6 +283,7 @@ message NonResourcePolicyRule { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string nonResourceURLs = 6; } @@ -286,6 +297,7 @@ message PolicyRulesWithSubjects { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required repeated Subject subjects = 1; // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the @@ -303,6 +315,7 @@ message PolicyRulesWithSubjects { } // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" message PriorityLevelConfiguration { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -311,7 +324,7 @@ message PriorityLevelConfiguration { // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional PriorityLevelConfigurationSpec spec = 2; // `status` is the current status of a "request-priority". @@ -324,20 +337,24 @@ message PriorityLevelConfiguration { message PriorityLevelConfigurationCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -356,6 +373,7 @@ message PriorityLevelConfigurationList { message PriorityLevelConfigurationReference { // `name` is the name of the priority level configuration being referenced // Required. + // +required optional string name = 1; } @@ -371,17 +389,17 @@ message PriorityLevelConfigurationSpec { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required optional LimitedPriorityLevelConfiguration limited = 2; // `exempt` specifies how requests are handled for an exempt priority level. @@ -390,9 +408,8 @@ message PriorityLevelConfigurationSpec { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional optional ExemptPriorityLevelConfiguration exempt = 3; } @@ -454,12 +471,14 @@ message ResourcePolicyRule { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string apiGroups = 2; // `resources` is a list of matching resources (i.e., lowercase @@ -468,6 +487,7 @@ message ResourcePolicyRule { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required repeated string resources = 3; // `clusterScope` indicates whether to match requests that do not @@ -495,10 +515,12 @@ message ResourcePolicyRule { message ServiceAccountSubject { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required optional string namespace = 1; // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required optional string name = 2; } @@ -508,6 +530,7 @@ message ServiceAccountSubject { message Subject { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator optional string kind = 1; @@ -528,6 +551,7 @@ message Subject { message UserSubject { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required optional string name = 1; } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1/types.go b/constraint/vendor/k8s.io/api/flowcontrol/v1/types.go index 4a40bdca4..31e421f28 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1/types.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1/types.go @@ -110,15 +110,16 @@ const ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" type FlowSchema struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec FlowSchemaSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -131,7 +132,7 @@ type FlowSchema struct { // FlowSchemaList is a list of FlowSchema objects. type FlowSchemaList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -146,6 +147,7 @@ type FlowSchemaSpec struct { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required PriorityLevelConfiguration PriorityLevelConfigurationReference `json:"priorityLevelConfiguration" protobuf:"bytes,1,opt,name=priorityLevelConfiguration"` // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen // FlowSchema is among those with the numerically lowest (which we take to be logically highest) @@ -187,6 +189,7 @@ type FlowDistinguisherMethod struct { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required Type FlowDistinguisherMethodType `json:"type" protobuf:"bytes,1,opt,name=type"` } @@ -194,6 +197,7 @@ type FlowDistinguisherMethod struct { type PriorityLevelConfigurationReference struct { // `name` is the name of the priority level configuration being referenced // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -207,6 +211,7 @@ type PolicyRulesWithSubjects struct { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required Subjects []Subject `json:"subjects" protobuf:"bytes,1,rep,name=subjects"` // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the // target resource. @@ -227,6 +232,7 @@ type PolicyRulesWithSubjects struct { type Subject struct { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator Kind SubjectKind `json:"kind" protobuf:"bytes,1,opt,name=kind"` // `user` matches based on username. @@ -254,6 +260,7 @@ const ( type UserSubject struct { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -263,6 +270,7 @@ type GroupSubject struct { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -270,9 +278,11 @@ type GroupSubject struct { type ServiceAccountSubject struct { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required Namespace string `json:"namespace" protobuf:"bytes,1,opt,name=namespace"` // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` } @@ -290,12 +300,14 @@ type ResourcePolicyRule struct { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required APIGroups []string `json:"apiGroups" protobuf:"bytes,2,rep,name=apiGroups"` // `resources` is a list of matching resources (i.e., lowercase @@ -304,6 +316,7 @@ type ResourcePolicyRule struct { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required Resources []string `json:"resources" protobuf:"bytes,3,rep,name=resources"` // `clusterScope` indicates whether to match requests that do not @@ -335,6 +348,7 @@ type NonResourcePolicyRule struct { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. // For example: @@ -346,6 +360,7 @@ type NonResourcePolicyRule struct { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required NonResourceURLs []string `json:"nonResourceURLs" protobuf:"bytes,6,rep,name=nonResourceURLs"` } @@ -364,16 +379,20 @@ type FlowSchemaStatus struct { type FlowSchemaCondition struct { // `type` is the type of the condition. // Required. + // +required Type FlowSchemaConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -386,15 +405,16 @@ type FlowSchemaConditionType string // +k8s:prerelease-lifecycle-gen:introduced=1.29 // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" type PriorityLevelConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec PriorityLevelConfigurationSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -407,7 +427,7 @@ type PriorityLevelConfiguration struct { // PriorityLevelConfigurationList is a list of PriorityLevelConfiguration objects. type PriorityLevelConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -428,17 +448,17 @@ type PriorityLevelConfigurationSpec struct { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type PriorityLevelEnablement `json:"type" protobuf:"bytes,1,opt,name=type"` // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required Limited *LimitedPriorityLevelConfiguration `json:"limited,omitempty" protobuf:"bytes,2,opt,name=limited"` // `exempt` specifies how requests are handled for an exempt priority level. @@ -447,9 +467,8 @@ type PriorityLevelConfigurationSpec struct { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional Exempt *ExemptPriorityLevelConfiguration `json:"exempt,omitempty" protobuf:"bytes,3,opt,name=exempt"` } @@ -494,6 +513,7 @@ type LimitedPriorityLevelConfiguration struct { NominalConcurrencyShares *int32 `json:"nominalConcurrencyShares" protobuf:"varint,1,opt,name=nominalConcurrencyShares"` // `limitResponse` indicates what to do with requests that can not be executed right now + // +required LimitResponse LimitResponse `json:"limitResponse,omitempty" protobuf:"bytes,2,opt,name=limitResponse"` // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -573,17 +593,17 @@ type LimitResponse struct { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type LimitResponseType `json:"type" protobuf:"bytes,1,opt,name=type"` // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required Queuing *QueuingConfiguration `json:"queuing,omitempty" protobuf:"bytes,2,opt,name=queuing"` } @@ -650,16 +670,20 @@ type PriorityLevelConfigurationStatus struct { type PriorityLevelConfigurationCondition struct { // `type` is the type of the condition. // Required. + // +required Type PriorityLevelConfigurationConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/flowcontrol/v1/types_swagger_doc_generated.go index b8cb43636..96b7a78e7 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1/types_swagger_doc_generated.go @@ -60,7 +60,7 @@ func (FlowSchema) SwaggerDoc() map[string]string { var map_FlowSchemaCondition = map[string]string{ "": "FlowSchemaCondition describes conditions for a FlowSchema.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", @@ -167,7 +167,7 @@ func (PriorityLevelConfiguration) SwaggerDoc() map[string]string { var map_PriorityLevelConfigurationCondition = map[string]string{ "": "PriorityLevelConfigurationCondition defines the condition of priority level.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/generated.proto index 8a701a610..c06ec1a2a 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/generated.proto @@ -67,11 +67,13 @@ message FlowDistinguisherMethod { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required optional string type = 1; } // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" message FlowSchema { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -80,7 +82,7 @@ message FlowSchema { // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional FlowSchemaSpec spec = 2; // `status` is the current status of a FlowSchema. @@ -93,20 +95,24 @@ message FlowSchema { message FlowSchemaCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -126,6 +132,7 @@ message FlowSchemaSpec { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required optional PriorityLevelConfigurationReference priorityLevelConfiguration = 1; // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen @@ -163,6 +170,7 @@ message GroupSubject { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required optional string name = 1; } @@ -176,17 +184,17 @@ message LimitResponse { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required optional QueuingConfiguration queuing = 2; } @@ -214,6 +222,7 @@ message LimitedPriorityLevelConfiguration { optional int32 assuredConcurrencyShares = 1; // `limitResponse` indicates what to do with requests that can not be executed right now + // +required optional LimitResponse limitResponse = 2; // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -254,6 +263,7 @@ message NonResourcePolicyRule { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. @@ -266,6 +276,7 @@ message NonResourcePolicyRule { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string nonResourceURLs = 6; } @@ -279,6 +290,7 @@ message PolicyRulesWithSubjects { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required repeated Subject subjects = 1; // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the @@ -296,6 +308,7 @@ message PolicyRulesWithSubjects { } // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" message PriorityLevelConfiguration { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -304,7 +317,7 @@ message PriorityLevelConfiguration { // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional PriorityLevelConfigurationSpec spec = 2; // `status` is the current status of a "request-priority". @@ -317,20 +330,24 @@ message PriorityLevelConfiguration { message PriorityLevelConfigurationCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -349,6 +366,7 @@ message PriorityLevelConfigurationList { message PriorityLevelConfigurationReference { // `name` is the name of the priority level configuration being referenced // Required. + // +required optional string name = 1; } @@ -364,17 +382,17 @@ message PriorityLevelConfigurationSpec { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required optional LimitedPriorityLevelConfiguration limited = 2; // `exempt` specifies how requests are handled for an exempt priority level. @@ -383,9 +401,8 @@ message PriorityLevelConfigurationSpec { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional optional ExemptPriorityLevelConfiguration exempt = 3; } @@ -445,12 +462,14 @@ message ResourcePolicyRule { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string apiGroups = 2; // `resources` is a list of matching resources (i.e., lowercase @@ -459,6 +478,7 @@ message ResourcePolicyRule { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required repeated string resources = 3; // `clusterScope` indicates whether to match requests that do not @@ -486,10 +506,12 @@ message ResourcePolicyRule { message ServiceAccountSubject { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required optional string namespace = 1; // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required optional string name = 2; } @@ -499,6 +521,7 @@ message ServiceAccountSubject { message Subject { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator optional string kind = 1; @@ -519,6 +542,7 @@ message Subject { message UserSubject { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required optional string name = 1; } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types.go index 0de6ea940..39f869f6c 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types.go @@ -111,15 +111,16 @@ const ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" type FlowSchema struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec FlowSchemaSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -133,7 +134,7 @@ type FlowSchema struct { // FlowSchemaList is a list of FlowSchema objects. type FlowSchemaList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -148,6 +149,7 @@ type FlowSchemaSpec struct { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required PriorityLevelConfiguration PriorityLevelConfigurationReference `json:"priorityLevelConfiguration" protobuf:"bytes,1,opt,name=priorityLevelConfiguration"` // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen // FlowSchema is among those with the numerically lowest (which we take to be logically highest) @@ -189,6 +191,7 @@ type FlowDistinguisherMethod struct { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required Type FlowDistinguisherMethodType `json:"type" protobuf:"bytes,1,opt,name=type"` } @@ -196,6 +199,7 @@ type FlowDistinguisherMethod struct { type PriorityLevelConfigurationReference struct { // `name` is the name of the priority level configuration being referenced // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -209,6 +213,7 @@ type PolicyRulesWithSubjects struct { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required Subjects []Subject `json:"subjects" protobuf:"bytes,1,rep,name=subjects"` // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the // target resource. @@ -229,6 +234,7 @@ type PolicyRulesWithSubjects struct { type Subject struct { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator Kind SubjectKind `json:"kind" protobuf:"bytes,1,opt,name=kind"` // `user` matches based on username. @@ -256,6 +262,7 @@ const ( type UserSubject struct { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -265,6 +272,7 @@ type GroupSubject struct { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -272,9 +280,11 @@ type GroupSubject struct { type ServiceAccountSubject struct { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required Namespace string `json:"namespace" protobuf:"bytes,1,opt,name=namespace"` // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` } @@ -292,12 +302,14 @@ type ResourcePolicyRule struct { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required APIGroups []string `json:"apiGroups" protobuf:"bytes,2,rep,name=apiGroups"` // `resources` is a list of matching resources (i.e., lowercase @@ -306,6 +318,7 @@ type ResourcePolicyRule struct { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required Resources []string `json:"resources" protobuf:"bytes,3,rep,name=resources"` // `clusterScope` indicates whether to match requests that do not @@ -337,6 +350,7 @@ type NonResourcePolicyRule struct { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. // For example: @@ -348,6 +362,7 @@ type NonResourcePolicyRule struct { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required NonResourceURLs []string `json:"nonResourceURLs" protobuf:"bytes,6,rep,name=nonResourceURLs"` } @@ -364,16 +379,20 @@ type FlowSchemaStatus struct { type FlowSchemaCondition struct { // `type` is the type of the condition. // Required. + // +required Type FlowSchemaConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -387,15 +406,16 @@ type FlowSchemaConditionType string // +k8s:prerelease-lifecycle-gen:replacement=flowcontrol.apiserver.k8s.io,v1beta3,PriorityLevelConfiguration // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" type PriorityLevelConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec PriorityLevelConfigurationSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -409,7 +429,7 @@ type PriorityLevelConfiguration struct { // PriorityLevelConfigurationList is a list of PriorityLevelConfiguration objects. type PriorityLevelConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -430,17 +450,17 @@ type PriorityLevelConfigurationSpec struct { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type PriorityLevelEnablement `json:"type" protobuf:"bytes,1,opt,name=type"` // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required Limited *LimitedPriorityLevelConfiguration `json:"limited,omitempty" protobuf:"bytes,2,opt,name=limited"` // `exempt` specifies how requests are handled for an exempt priority level. @@ -449,9 +469,8 @@ type PriorityLevelConfigurationSpec struct { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional Exempt *ExemptPriorityLevelConfiguration `json:"exempt,omitempty" protobuf:"bytes,3,opt,name=exempt"` } @@ -491,6 +510,7 @@ type LimitedPriorityLevelConfiguration struct { AssuredConcurrencyShares int32 `json:"assuredConcurrencyShares" protobuf:"varint,1,opt,name=assuredConcurrencyShares"` // `limitResponse` indicates what to do with requests that can not be executed right now + // +required LimitResponse LimitResponse `json:"limitResponse,omitempty" protobuf:"bytes,2,opt,name=limitResponse"` // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -570,17 +590,17 @@ type LimitResponse struct { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type LimitResponseType `json:"type" protobuf:"bytes,1,opt,name=type"` // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required Queuing *QueuingConfiguration `json:"queuing,omitempty" protobuf:"bytes,2,opt,name=queuing"` } @@ -645,16 +665,20 @@ type PriorityLevelConfigurationStatus struct { type PriorityLevelConfigurationCondition struct { // `type` is the type of the condition. // Required. + // +required Type PriorityLevelConfigurationConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types_swagger_doc_generated.go index d69bdac62..fee54a89b 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta1/types_swagger_doc_generated.go @@ -60,7 +60,7 @@ func (FlowSchema) SwaggerDoc() map[string]string { var map_FlowSchemaCondition = map[string]string{ "": "FlowSchemaCondition describes conditions for a FlowSchema.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", @@ -167,7 +167,7 @@ func (PriorityLevelConfiguration) SwaggerDoc() map[string]string { var map_PriorityLevelConfigurationCondition = map[string]string{ "": "PriorityLevelConfigurationCondition defines the condition of priority level.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/generated.proto b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/generated.proto index 371b90a5c..a80455d67 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/generated.proto +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/generated.proto @@ -67,11 +67,13 @@ message FlowDistinguisherMethod { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required optional string type = 1; } // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" message FlowSchema { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -80,7 +82,7 @@ message FlowSchema { // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional FlowSchemaSpec spec = 2; // `status` is the current status of a FlowSchema. @@ -93,20 +95,24 @@ message FlowSchema { message FlowSchemaCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -126,6 +132,7 @@ message FlowSchemaSpec { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required optional PriorityLevelConfigurationReference priorityLevelConfiguration = 1; // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen @@ -163,6 +170,7 @@ message GroupSubject { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required optional string name = 1; } @@ -176,17 +184,17 @@ message LimitResponse { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required optional QueuingConfiguration queuing = 2; } @@ -214,6 +222,7 @@ message LimitedPriorityLevelConfiguration { optional int32 assuredConcurrencyShares = 1; // `limitResponse` indicates what to do with requests that can not be executed right now + // +required optional LimitResponse limitResponse = 2; // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -254,6 +263,7 @@ message NonResourcePolicyRule { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. @@ -266,6 +276,7 @@ message NonResourcePolicyRule { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string nonResourceURLs = 6; } @@ -279,6 +290,7 @@ message PolicyRulesWithSubjects { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required repeated Subject subjects = 1; // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the @@ -296,6 +308,7 @@ message PolicyRulesWithSubjects { } // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" message PriorityLevelConfiguration { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -304,7 +317,7 @@ message PriorityLevelConfiguration { // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional PriorityLevelConfigurationSpec spec = 2; // `status` is the current status of a "request-priority". @@ -317,20 +330,24 @@ message PriorityLevelConfiguration { message PriorityLevelConfigurationCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -349,6 +366,7 @@ message PriorityLevelConfigurationList { message PriorityLevelConfigurationReference { // `name` is the name of the priority level configuration being referenced // Required. + // +required optional string name = 1; } @@ -364,17 +382,17 @@ message PriorityLevelConfigurationSpec { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required optional LimitedPriorityLevelConfiguration limited = 2; // `exempt` specifies how requests are handled for an exempt priority level. @@ -383,9 +401,8 @@ message PriorityLevelConfigurationSpec { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional optional ExemptPriorityLevelConfiguration exempt = 3; } @@ -445,12 +462,14 @@ message ResourcePolicyRule { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string apiGroups = 2; // `resources` is a list of matching resources (i.e., lowercase @@ -459,6 +478,7 @@ message ResourcePolicyRule { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required repeated string resources = 3; // `clusterScope` indicates whether to match requests that do not @@ -486,10 +506,12 @@ message ResourcePolicyRule { message ServiceAccountSubject { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required optional string namespace = 1; // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required optional string name = 2; } @@ -499,6 +521,7 @@ message ServiceAccountSubject { message Subject { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator optional string kind = 1; @@ -519,6 +542,7 @@ message Subject { message UserSubject { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required optional string name = 1; } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types.go index 2f82a6823..38ab2a2a7 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types.go @@ -111,15 +111,16 @@ const ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" type FlowSchema struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec FlowSchemaSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -133,7 +134,7 @@ type FlowSchema struct { // FlowSchemaList is a list of FlowSchema objects. type FlowSchemaList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -148,6 +149,7 @@ type FlowSchemaSpec struct { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required PriorityLevelConfiguration PriorityLevelConfigurationReference `json:"priorityLevelConfiguration" protobuf:"bytes,1,opt,name=priorityLevelConfiguration"` // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen // FlowSchema is among those with the numerically lowest (which we take to be logically highest) @@ -189,6 +191,7 @@ type FlowDistinguisherMethod struct { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required Type FlowDistinguisherMethodType `json:"type" protobuf:"bytes,1,opt,name=type"` } @@ -196,6 +199,7 @@ type FlowDistinguisherMethod struct { type PriorityLevelConfigurationReference struct { // `name` is the name of the priority level configuration being referenced // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -209,6 +213,7 @@ type PolicyRulesWithSubjects struct { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required Subjects []Subject `json:"subjects" protobuf:"bytes,1,rep,name=subjects"` // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the // target resource. @@ -229,6 +234,7 @@ type PolicyRulesWithSubjects struct { type Subject struct { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator Kind SubjectKind `json:"kind" protobuf:"bytes,1,opt,name=kind"` // `user` matches based on username. @@ -256,6 +262,7 @@ const ( type UserSubject struct { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -265,6 +272,7 @@ type GroupSubject struct { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -272,9 +280,11 @@ type GroupSubject struct { type ServiceAccountSubject struct { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required Namespace string `json:"namespace" protobuf:"bytes,1,opt,name=namespace"` // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` } @@ -292,12 +302,14 @@ type ResourcePolicyRule struct { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required APIGroups []string `json:"apiGroups" protobuf:"bytes,2,rep,name=apiGroups"` // `resources` is a list of matching resources (i.e., lowercase @@ -306,6 +318,7 @@ type ResourcePolicyRule struct { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required Resources []string `json:"resources" protobuf:"bytes,3,rep,name=resources"` // `clusterScope` indicates whether to match requests that do not @@ -337,6 +350,7 @@ type NonResourcePolicyRule struct { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. // For example: @@ -348,6 +362,7 @@ type NonResourcePolicyRule struct { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required NonResourceURLs []string `json:"nonResourceURLs" protobuf:"bytes,6,rep,name=nonResourceURLs"` } @@ -364,16 +379,20 @@ type FlowSchemaStatus struct { type FlowSchemaCondition struct { // `type` is the type of the condition. // Required. + // +required Type FlowSchemaConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -387,15 +406,16 @@ type FlowSchemaConditionType string // +k8s:prerelease-lifecycle-gen:replacement=flowcontrol.apiserver.k8s.io,v1beta3,PriorityLevelConfiguration // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" type PriorityLevelConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec PriorityLevelConfigurationSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -409,7 +429,7 @@ type PriorityLevelConfiguration struct { // PriorityLevelConfigurationList is a list of PriorityLevelConfiguration objects. type PriorityLevelConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -430,17 +450,17 @@ type PriorityLevelConfigurationSpec struct { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type PriorityLevelEnablement `json:"type" protobuf:"bytes,1,opt,name=type"` // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required Limited *LimitedPriorityLevelConfiguration `json:"limited,omitempty" protobuf:"bytes,2,opt,name=limited"` // `exempt` specifies how requests are handled for an exempt priority level. @@ -449,9 +469,8 @@ type PriorityLevelConfigurationSpec struct { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional Exempt *ExemptPriorityLevelConfiguration `json:"exempt,omitempty" protobuf:"bytes,3,opt,name=exempt"` } @@ -491,6 +510,7 @@ type LimitedPriorityLevelConfiguration struct { AssuredConcurrencyShares int32 `json:"assuredConcurrencyShares" protobuf:"varint,1,opt,name=assuredConcurrencyShares"` // `limitResponse` indicates what to do with requests that can not be executed right now + // +required LimitResponse LimitResponse `json:"limitResponse,omitempty" protobuf:"bytes,2,opt,name=limitResponse"` // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -570,17 +590,17 @@ type LimitResponse struct { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type LimitResponseType `json:"type" protobuf:"bytes,1,opt,name=type"` // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required Queuing *QueuingConfiguration `json:"queuing,omitempty" protobuf:"bytes,2,opt,name=queuing"` } @@ -645,16 +665,20 @@ type PriorityLevelConfigurationStatus struct { type PriorityLevelConfigurationCondition struct { // `type` is the type of the condition. // Required. + // +required Type PriorityLevelConfigurationConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types_swagger_doc_generated.go index 921122731..bf12ce5e0 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta2/types_swagger_doc_generated.go @@ -60,7 +60,7 @@ func (FlowSchema) SwaggerDoc() map[string]string { var map_FlowSchemaCondition = map[string]string{ "": "FlowSchemaCondition describes conditions for a FlowSchema.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", @@ -167,7 +167,7 @@ func (PriorityLevelConfiguration) SwaggerDoc() map[string]string { var map_PriorityLevelConfigurationCondition = map[string]string{ "": "PriorityLevelConfigurationCondition defines the condition of priority level.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/generated.proto b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/generated.proto index 7e11de2a2..68344b79b 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/generated.proto +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/generated.proto @@ -67,11 +67,13 @@ message FlowDistinguisherMethod { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required optional string type = 1; } // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" message FlowSchema { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -80,7 +82,7 @@ message FlowSchema { // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional FlowSchemaSpec spec = 2; // `status` is the current status of a FlowSchema. @@ -93,20 +95,24 @@ message FlowSchema { message FlowSchemaCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -126,6 +132,7 @@ message FlowSchemaSpec { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required optional PriorityLevelConfigurationReference priorityLevelConfiguration = 1; // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen @@ -165,6 +172,7 @@ message GroupSubject { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required optional string name = 1; } @@ -178,17 +186,17 @@ message LimitResponse { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required optional QueuingConfiguration queuing = 2; } @@ -216,6 +224,7 @@ message LimitedPriorityLevelConfiguration { optional int32 nominalConcurrencyShares = 1; // `limitResponse` indicates what to do with requests that can not be executed right now + // +required optional LimitResponse limitResponse = 2; // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -256,6 +265,7 @@ message NonResourcePolicyRule { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. @@ -268,6 +278,7 @@ message NonResourcePolicyRule { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required repeated string nonResourceURLs = 6; } @@ -281,6 +292,7 @@ message PolicyRulesWithSubjects { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required repeated Subject subjects = 1; // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the @@ -298,6 +310,7 @@ message PolicyRulesWithSubjects { } // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" message PriorityLevelConfiguration { // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -306,7 +319,7 @@ message PriorityLevelConfiguration { // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required optional PriorityLevelConfigurationSpec spec = 2; // `status` is the current status of a "request-priority". @@ -319,20 +332,24 @@ message PriorityLevelConfiguration { message PriorityLevelConfigurationCondition { // `type` is the type of the condition. // Required. + // +required optional string type = 1; // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional optional string status = 2; // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional optional string reason = 4; // `message` is a human-readable message indicating details about last transition. + // +optional optional string message = 5; } @@ -351,6 +368,7 @@ message PriorityLevelConfigurationList { message PriorityLevelConfigurationReference { // `name` is the name of the priority level configuration being referenced // Required. + // +required optional string name = 1; } @@ -366,17 +384,17 @@ message PriorityLevelConfigurationSpec { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator optional string type = 1; // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required optional LimitedPriorityLevelConfiguration limited = 2; // `exempt` specifies how requests are handled for an exempt priority level. @@ -385,9 +403,8 @@ message PriorityLevelConfigurationSpec { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional optional ExemptPriorityLevelConfiguration exempt = 3; } @@ -449,12 +466,14 @@ message ResourcePolicyRule { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string verbs = 1; // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required repeated string apiGroups = 2; // `resources` is a list of matching resources (i.e., lowercase @@ -463,6 +482,7 @@ message ResourcePolicyRule { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required repeated string resources = 3; // `clusterScope` indicates whether to match requests that do not @@ -490,10 +510,12 @@ message ResourcePolicyRule { message ServiceAccountSubject { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required optional string namespace = 1; // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required optional string name = 2; } @@ -503,6 +525,7 @@ message ServiceAccountSubject { message Subject { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator optional string kind = 1; @@ -523,6 +546,7 @@ message Subject { message UserSubject { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required optional string name = 1; } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types.go index 26b67629c..cbebca357 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types.go @@ -125,15 +125,16 @@ const ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". +// +k8s:supportsSubresource="/status" type FlowSchema struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec FlowSchemaSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a FlowSchema. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -147,7 +148,7 @@ type FlowSchema struct { // FlowSchemaList is a list of FlowSchema objects. type FlowSchemaList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -162,6 +163,7 @@ type FlowSchemaSpec struct { // `priorityLevelConfiguration` should reference a PriorityLevelConfiguration in the cluster. If the reference cannot // be resolved, the FlowSchema will be ignored and marked as invalid in its status. // Required. + // +required PriorityLevelConfiguration PriorityLevelConfigurationReference `json:"priorityLevelConfiguration" protobuf:"bytes,1,opt,name=priorityLevelConfiguration"` // `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen // FlowSchema is among those with the numerically lowest (which we take to be logically highest) @@ -203,6 +205,7 @@ type FlowDistinguisherMethod struct { // `type` is the type of flow distinguisher method // The supported types are "ByUser" and "ByNamespace". // Required. + // +required Type FlowDistinguisherMethodType `json:"type" protobuf:"bytes,1,opt,name=type"` } @@ -210,6 +213,7 @@ type FlowDistinguisherMethod struct { type PriorityLevelConfigurationReference struct { // `name` is the name of the priority level configuration being referenced // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -223,6 +227,7 @@ type PolicyRulesWithSubjects struct { // A slice that includes both the system:authenticated and system:unauthenticated user groups matches every request. // +listType=atomic // Required. + // +required Subjects []Subject `json:"subjects" protobuf:"bytes,1,rep,name=subjects"` // `resourceRules` is a slice of ResourcePolicyRules that identify matching requests according to their verb and the // target resource. @@ -243,6 +248,7 @@ type PolicyRulesWithSubjects struct { type Subject struct { // `kind` indicates which one of the other fields is non-empty. // Required + // +required // +unionDiscriminator Kind SubjectKind `json:"kind" protobuf:"bytes,1,opt,name=kind"` // `user` matches based on username. @@ -270,6 +276,7 @@ const ( type UserSubject struct { // `name` is the username that matches, or "*" to match all usernames. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -279,6 +286,7 @@ type GroupSubject struct { // See https://github.com/kubernetes/apiserver/blob/master/pkg/authentication/user/user.go for some // well-known group names. // Required. + // +required Name string `json:"name" protobuf:"bytes,1,opt,name=name"` } @@ -286,9 +294,11 @@ type GroupSubject struct { type ServiceAccountSubject struct { // `namespace` is the namespace of matching ServiceAccount objects. // Required. + // +required Namespace string `json:"namespace" protobuf:"bytes,1,opt,name=namespace"` // `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. // Required. + // +required Name string `json:"name" protobuf:"bytes,2,opt,name=name"` } @@ -306,12 +316,14 @@ type ResourcePolicyRule struct { // "*" matches all verbs and, if present, must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `apiGroups` is a list of matching API groups and may not be empty. // "*" matches all API groups and, if present, must be the only entry. // +listType=set // Required. + // +required APIGroups []string `json:"apiGroups" protobuf:"bytes,2,rep,name=apiGroups"` // `resources` is a list of matching resources (i.e., lowercase @@ -320,6 +332,7 @@ type ResourcePolicyRule struct { // "*" matches all resources and, if present, must be the only entry. // Required. // +listType=set + // +required Resources []string `json:"resources" protobuf:"bytes,3,rep,name=resources"` // `clusterScope` indicates whether to match requests that do not @@ -351,6 +364,7 @@ type NonResourcePolicyRule struct { // "*" matches all verbs. If it is present, it must be the only entry. // +listType=set // Required. + // +required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` // `nonResourceURLs` is a set of url prefixes that a user should have access to and may not be empty. // For example: @@ -362,6 +376,7 @@ type NonResourcePolicyRule struct { // "*" matches all non-resource urls. if it is present, it must be the only entry. // +listType=set // Required. + // +required NonResourceURLs []string `json:"nonResourceURLs" protobuf:"bytes,6,rep,name=nonResourceURLs"` } @@ -380,16 +395,20 @@ type FlowSchemaStatus struct { type FlowSchemaCondition struct { // `type` is the type of the condition. // Required. + // +required Type FlowSchemaConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } @@ -403,15 +422,16 @@ type FlowSchemaConditionType string // +k8s:prerelease-lifecycle-gen:replacement=flowcontrol.apiserver.k8s.io,v1,PriorityLevelConfiguration // PriorityLevelConfiguration represents the configuration of a priority level. +// +k8s:supportsSubresource="/status" type PriorityLevelConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `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" protobuf:"bytes,1,opt,name=metadata"` // `spec` is the specification of the desired behavior of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status - // +optional + // +required Spec PriorityLevelConfigurationSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // `status` is the current status of a "request-priority". // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -425,7 +445,7 @@ type PriorityLevelConfiguration struct { // PriorityLevelConfigurationList is a list of PriorityLevelConfiguration objects. type PriorityLevelConfigurationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -446,17 +466,17 @@ type PriorityLevelConfigurationSpec struct { // _are_ subject to limits and (b) some of the server's limited // capacity is made available exclusively to this priority level. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type PriorityLevelEnablement `json:"type" protobuf:"bytes,1,opt,name=type"` // `limited` specifies how requests are handled for a Limited priority level. // This field must be non-empty if and only if `type` is `"Limited"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Limited")=+k8s:required Limited *LimitedPriorityLevelConfiguration `json:"limited,omitempty" protobuf:"bytes,2,opt,name=limited"` // `exempt` specifies how requests are handled for an exempt priority level. @@ -465,9 +485,8 @@ type PriorityLevelConfigurationSpec struct { // If empty and `type` is `"Exempt"` then the default values // for `ExemptPriorityLevelConfiguration` apply. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Exempt")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Limited")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Exempt")=+k8s:optional Exempt *ExemptPriorityLevelConfiguration `json:"exempt,omitempty" protobuf:"bytes,3,opt,name=exempt"` } @@ -507,6 +526,7 @@ type LimitedPriorityLevelConfiguration struct { NominalConcurrencyShares int32 `json:"nominalConcurrencyShares" protobuf:"varint,1,opt,name=nominalConcurrencyShares"` // `limitResponse` indicates what to do with requests that can not be executed right now + // +required LimitResponse LimitResponse `json:"limitResponse,omitempty" protobuf:"bytes,2,opt,name=limitResponse"` // `lendablePercent` prescribes the fraction of the level's NominalCL that @@ -586,17 +606,17 @@ type LimitResponse struct { // "Reject" means that requests that can not be executed upon arrival // are rejected. // Required. + // +required // +unionDiscriminator - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:discriminator + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:modeDiscriminator Type LimitResponseType `json:"type" protobuf:"bytes,1,opt,name=type"` // `queuing` holds the configuration parameters for queuing. // This field may be non-empty only if `type` is `"Queue"`. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:member("Queue")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:member("Reject")=+k8s:forbidden + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:ifMode("Queue")=+k8s:required Queuing *QueuingConfiguration `json:"queuing,omitempty" protobuf:"bytes,2,opt,name=queuing"` } @@ -663,16 +683,20 @@ type PriorityLevelConfigurationStatus struct { type PriorityLevelConfigurationCondition struct { // `type` is the type of the condition. // Required. + // +required Type PriorityLevelConfigurationConditionType `json:"type,omitempty" protobuf:"bytes,1,opt,name=type"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. + // +optional Status ConditionStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. + // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // `reason` is a unique, one-word, CamelCase reason for the condition's last transition. + // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // `message` is a human-readable message indicating details about last transition. + // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } diff --git a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types_swagger_doc_generated.go index fa76112a7..c799e5d8d 100644 --- a/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/flowcontrol/v1beta3/types_swagger_doc_generated.go @@ -60,7 +60,7 @@ func (FlowSchema) SwaggerDoc() map[string]string { var map_FlowSchemaCondition = map[string]string{ "": "FlowSchemaCondition describes conditions for a FlowSchema.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", @@ -167,7 +167,7 @@ func (PriorityLevelConfiguration) SwaggerDoc() map[string]string { var map_PriorityLevelConfigurationCondition = map[string]string{ "": "PriorityLevelConfigurationCondition defines the condition of priority level.", "type": "`type` is the type of the condition. Required.", - "status": "`status` is the status of the condition. Can be True, False, Unknown. Required.", + "status": "`status` is the status of the condition. Should be specified and set to one of True, False, Unknown.", "lastTransitionTime": "`lastTransitionTime` is the last time the condition transitioned from one status to another.", "reason": "`reason` is a unique, one-word, CamelCase reason for the condition's last transition.", "message": "`message` is a human-readable message indicating details about last transition.", diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/doc.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/doc.go similarity index 81% rename from constraint/vendor/k8s.io/api/scheduling/v1alpha2/doc.go rename to constraint/vendor/k8s.io/api/lifecycle/v1alpha1/doc.go index 24ba23e72..b8ccba674 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/doc.go +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/doc.go @@ -17,8 +17,9 @@ limitations under the License. // +k8s:deepcopy-gen=package // +k8s:protobuf-gen=package // +k8s:openapi-gen=true -// +k8s:openapi-model-package=io.k8s.api.scheduling.v1alpha2 +// +k8s:prerelease-lifecycle-gen=true +// +k8s:openapi-model-package=io.k8s.api.lifecycle.v1alpha1 -// +groupName=scheduling.k8s.io +// +groupName=lifecycle.k8s.io -package v1alpha2 +package v1alpha1 diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.pb.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.pb.go similarity index 61% rename from constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.pb.go rename to constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.pb.go index 12402df3d..f8835cc6a 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.pb.go +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.pb.go @@ -15,9 +15,9 @@ limitations under the License. */ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: k8s.io/api/scheduling/v1alpha2/generated.proto +// source: k8s.io/api/lifecycle/v1alpha1/generated.proto -package v1alpha2 +package v1alpha1 import ( fmt "fmt" @@ -29,45 +29,94 @@ import ( math_bits "math/bits" reflect "reflect" strings "strings" + + k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" ) -func (m *BasicSchedulingPolicy) Reset() { *m = BasicSchedulingPolicy{} } +func (m *Eviction) Reset() { *m = Eviction{} } -func (m *GangSchedulingPolicy) Reset() { *m = GangSchedulingPolicy{} } +func (m *EvictionList) Reset() { *m = EvictionList{} } -func (m *PodGroup) Reset() { *m = PodGroup{} } +func (m *EvictionPodReference) Reset() { *m = EvictionPodReference{} } -func (m *PodGroupList) Reset() { *m = PodGroupList{} } +func (m *EvictionRequest) Reset() { *m = EvictionRequest{} } -func (m *PodGroupResourceClaim) Reset() { *m = PodGroupResourceClaim{} } +func (m *EvictionRequestList) Reset() { *m = EvictionRequestList{} } -func (m *PodGroupResourceClaimStatus) Reset() { *m = PodGroupResourceClaimStatus{} } +func (m *EvictionRequestPodReference) Reset() { *m = EvictionRequestPodReference{} } -func (m *PodGroupSchedulingConstraints) Reset() { *m = PodGroupSchedulingConstraints{} } +func (m *EvictionRequestSpec) Reset() { *m = EvictionRequestSpec{} } -func (m *PodGroupSchedulingPolicy) Reset() { *m = PodGroupSchedulingPolicy{} } +func (m *EvictionRequestStatus) Reset() { *m = EvictionRequestStatus{} } -func (m *PodGroupSpec) Reset() { *m = PodGroupSpec{} } +func (m *EvictionRequestTarget) Reset() { *m = EvictionRequestTarget{} } -func (m *PodGroupStatus) Reset() { *m = PodGroupStatus{} } +func (m *EvictionSpec) Reset() { *m = EvictionSpec{} } -func (m *PodGroupTemplate) Reset() { *m = PodGroupTemplate{} } +func (m *EvictionStatus) Reset() { *m = EvictionStatus{} } -func (m *PodGroupTemplateReference) Reset() { *m = PodGroupTemplateReference{} } +func (m *EvictionTarget) Reset() { *m = EvictionTarget{} } -func (m *TopologyConstraint) Reset() { *m = TopologyConstraint{} } +func (m *Requester) Reset() { *m = Requester{} } -func (m *TypedLocalObjectReference) Reset() { *m = TypedLocalObjectReference{} } +func (m *ResponderStatus) Reset() { *m = ResponderStatus{} } -func (m *Workload) Reset() { *m = Workload{} } +func (m *TargetResponder) Reset() { *m = TargetResponder{} } -func (m *WorkloadList) Reset() { *m = WorkloadList{} } +func (m *Eviction) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} -func (m *WorkloadPodGroupTemplateReference) Reset() { *m = WorkloadPodGroupTemplateReference{} } +func (m *Eviction) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} -func (m *WorkloadSpec) Reset() { *m = WorkloadSpec{} } +func (m *Eviction) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} -func (m *BasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { +func (m *EvictionList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -77,20 +126,44 @@ func (m *BasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *BasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionList) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *BasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *GangSchedulingPolicy) Marshal() (dAtA []byte, err error) { +func (m *EvictionPodReference) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -100,23 +173,30 @@ func (m *GangSchedulingPolicy) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *GangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionPodReference) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *GangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionPodReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i = encodeVarintGenerated(dAtA, i, uint64(m.MinCount)) + i -= len(m.UID) + copy(dAtA[i:], m.UID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) i-- - dAtA[i] = 0x8 + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *PodGroup) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -126,12 +206,12 @@ func (m *PodGroup) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroup) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroup) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -169,7 +249,7 @@ func (m *PodGroup) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *PodGroupList) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequestList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -179,12 +259,12 @@ func (m *PodGroupList) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupList) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequestList) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupList) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequestList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -216,7 +296,7 @@ func (m *PodGroupList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *PodGroupResourceClaim) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequestPodReference) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -226,30 +306,21 @@ func (m *PodGroupResourceClaim) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupResourceClaim) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequestPodReference) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequestPodReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.ResourceClaimTemplateName != nil { - i -= len(*m.ResourceClaimTemplateName) - copy(dAtA[i:], *m.ResourceClaimTemplateName) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimTemplateName))) - i-- - dAtA[i] = 0x1a - } - if m.ResourceClaimName != nil { - i -= len(*m.ResourceClaimName) - copy(dAtA[i:], *m.ResourceClaimName) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) - i-- - dAtA[i] = 0x12 - } + i -= len(m.UID) + copy(dAtA[i:], m.UID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) + i-- + dAtA[i] = 0x12 i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) @@ -258,7 +329,7 @@ func (m *PodGroupResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *PodGroupResourceClaimStatus) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequestSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -268,32 +339,40 @@ func (m *PodGroupResourceClaimStatus) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupResourceClaimStatus) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequestSpec) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequestSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.ResourceClaimName != nil { - i -= len(*m.ResourceClaimName) - copy(dAtA[i:], *m.ResourceClaimName) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) - i-- - dAtA[i] = 0x12 + i -= len(m.Intent) + copy(dAtA[i:], m.Intent) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Intent))) + i-- + dAtA[i] = 0x1a + i -= len(m.Requester) + copy(dAtA[i:], m.Requester) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Requester))) + i-- + dAtA[i] = 0x12 + { + size, err := m.Target.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *PodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequestStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -303,20 +382,25 @@ func (m *PodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequestStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequestStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Topology) > 0 { - for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + if m.ObservedGeneration != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.ObservedGeneration)) + i-- + dAtA[i] = 0x10 + } + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -330,7 +414,7 @@ func (m *PodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, return len(dAtA) - i, nil } -func (m *PodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { +func (m *EvictionRequestTarget) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -340,31 +424,19 @@ func (m *PodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionRequestTarget) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionRequestTarget) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.Gang != nil { - { - size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.Basic != nil { + if m.Pod != nil { { - size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Pod.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -377,7 +449,7 @@ func (m *PodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error return len(dAtA) - i, nil } -func (m *PodGroupSpec) Marshal() (dAtA []byte, err error) { +func (m *EvictionSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -387,61 +459,18 @@ func (m *PodGroupSpec) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupSpec) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionSpec) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.Priority != nil { - i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) - i-- - dAtA[i] = 0x38 - } - i -= len(m.PriorityClassName) - copy(dAtA[i:], m.PriorityClassName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) - i-- - dAtA[i] = 0x32 - if m.DisruptionMode != nil { - i -= len(*m.DisruptionMode) - copy(dAtA[i:], *m.DisruptionMode) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.DisruptionMode))) - i-- - dAtA[i] = 0x2a - } - if len(m.ResourceClaims) > 0 { - for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if m.SchedulingConstraints != nil { - { - size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } { - size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Target.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -449,23 +478,11 @@ func (m *PodGroupSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x12 - if m.PodGroupTemplateRef != nil { - { - size, err := m.PodGroupTemplateRef.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } + dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *PodGroupStatus) Marshal() (dAtA []byte, err error) { +func (m *EvictionStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -475,20 +492,20 @@ func (m *PodGroupStatus) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupStatus) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.ResourceClaimStatuses) > 0 { - for iNdEx := len(m.ResourceClaimStatuses) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Responders) > 0 { + for iNdEx := len(m.Responders) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.ResourceClaimStatuses[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Responders[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -496,13 +513,13 @@ func (m *PodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x12 + dAtA[i] = 0x2a } } - if len(m.Conditions) > 0 { - for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + if len(m.TargetResponders) > 0 { + for iNdEx := len(m.TargetResponders) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.TargetResponders[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -510,53 +527,13 @@ func (m *PodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0xa + dAtA[i] = 0x22 } } - return len(dAtA) - i, nil -} - -func (m *PodGroupTemplate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PodGroupTemplate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Priority != nil { - i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) - i-- - dAtA[i] = 0x38 - } - i -= len(m.PriorityClassName) - copy(dAtA[i:], m.PriorityClassName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) - i-- - dAtA[i] = 0x32 - if m.DisruptionMode != nil { - i -= len(*m.DisruptionMode) - copy(dAtA[i:], *m.DisruptionMode) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.DisruptionMode))) - i-- - dAtA[i] = 0x2a - } - if len(m.ResourceClaims) > 0 { - for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Requesters) > 0 { + for iNdEx := len(m.Requesters) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Requesters[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -564,40 +541,32 @@ func (m *PodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x22 + dAtA[i] = 0x1a } } - if m.SchedulingConstraints != nil { - { - size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + if m.ObservedGeneration != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.ObservedGeneration)) i-- - dAtA[i] = 0x1a + dAtA[i] = 0x10 } - { - size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i-- - dAtA[i] = 0x12 - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *PodGroupTemplateReference) Marshal() (dAtA []byte, err error) { +func (m *EvictionTarget) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -607,19 +576,19 @@ func (m *PodGroupTemplateReference) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PodGroupTemplateReference) MarshalTo(dAtA []byte) (int, error) { +func (m *EvictionTarget) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PodGroupTemplateReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EvictionTarget) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.Workload != nil { + if m.Pod != nil { { - size, err := m.Workload.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Pod.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -632,7 +601,7 @@ func (m *PodGroupTemplateReference) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } -func (m *TopologyConstraint) Marshal() (dAtA []byte, err error) { +func (m *Requester) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -642,63 +611,30 @@ func (m *TopologyConstraint) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *TopologyConstraint) MarshalTo(dAtA []byte) (int, error) { +func (m *Requester) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *TopologyConstraint) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *Requester) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key))) + i -= len(m.Intent) + copy(dAtA[i:], m.Intent) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Intent))) i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TypedLocalObjectReference) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TypedLocalObjectReference) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TypedLocalObjectReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l + dAtA[i] = 0x12 i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i-- - dAtA[i] = 0x1a - i -= len(m.Kind) - copy(dAtA[i:], m.Kind) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind))) - i-- - dAtA[i] = 0x12 - i -= len(m.APIGroup) - copy(dAtA[i:], m.APIGroup) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) - i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *Workload) Marshal() (dAtA []byte, err error) { +func (m *ResponderStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -708,87 +644,80 @@ func (m *Workload) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *Workload) MarshalTo(dAtA []byte) (int, error) { +func (m *ResponderStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *Workload) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResponderStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + if m.Message != nil { + i -= len(*m.Message) + copy(dAtA[i:], *m.Message) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Message))) + i-- + dAtA[i] = 0x32 } - i-- - dAtA[i] = 0x12 - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.CompletionTime != nil { + { + size, err := m.CompletionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x2a } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *WorkloadList) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err + if m.ExpectedCompletionTime != nil { + { + size, err := m.ExpectedCompletionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 } - return dAtA[:n], nil -} - -func (m *WorkloadList) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *WorkloadList) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + if m.HeartbeatTime != nil { + { + size, err := m.HeartbeatTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } - i-- - dAtA[i] = 0x12 + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x1a } - { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.StartTime != nil { + { + size, err := m.StartTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x12 } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *WorkloadPodGroupTemplateReference) Marshal() (dAtA []byte, err error) { +func (m *TargetResponder) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -798,75 +727,31 @@ func (m *WorkloadPodGroupTemplateReference) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *WorkloadPodGroupTemplateReference) MarshalTo(dAtA []byte) (int, error) { +func (m *TargetResponder) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *WorkloadPodGroupTemplateReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *TargetResponder) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i -= len(m.PodGroupTemplateName) - copy(dAtA[i:], m.PodGroupTemplateName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.PodGroupTemplateName))) - i-- - dAtA[i] = 0x12 - i -= len(m.WorkloadName) - copy(dAtA[i:], m.WorkloadName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.WorkloadName))) + i -= len(m.State) + copy(dAtA[i:], m.State) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.State))) i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *WorkloadSpec) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *WorkloadSpec) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *WorkloadSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.PodGroupTemplates) > 0 { - for iNdEx := len(m.PodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.ControllerRef != nil { - { - size, err := m.ControllerRef.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + dAtA[i] = 0x1a + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) i-- - dAtA[i] = 0xa + dAtA[i] = 0x10 } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa return len(dAtA) - i, nil } @@ -881,26 +766,52 @@ func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *BasicSchedulingPolicy) Size() (n int) { +func (m *Eviction) Size() (n int) { if m == nil { return 0 } var l int _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *GangSchedulingPolicy) Size() (n int) { +func (m *EvictionList) Size() (n int) { if m == nil { return 0 } var l int _ = l - n += 1 + sovGenerated(uint64(m.MinCount)) + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *EvictionPodReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.UID) + n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *PodGroup) Size() (n int) { +func (m *EvictionRequest) Size() (n int) { if m == nil { return 0 } @@ -915,7 +826,7 @@ func (m *PodGroup) Size() (n int) { return n } -func (m *PodGroupList) Size() (n int) { +func (m *EvictionRequestList) Size() (n int) { if m == nil { return 0 } @@ -932,7 +843,7 @@ func (m *PodGroupList) Size() (n int) { return n } -func (m *PodGroupResourceClaim) Size() (n int) { +func (m *EvictionRequestPodReference) Size() (n int) { if m == nil { return 0 } @@ -940,99 +851,69 @@ func (m *PodGroupResourceClaim) Size() (n int) { _ = l l = len(m.Name) n += 1 + l + sovGenerated(uint64(l)) - if m.ResourceClaimName != nil { - l = len(*m.ResourceClaimName) - n += 1 + l + sovGenerated(uint64(l)) - } - if m.ResourceClaimTemplateName != nil { - l = len(*m.ResourceClaimTemplateName) - n += 1 + l + sovGenerated(uint64(l)) - } + l = len(m.UID) + n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *PodGroupResourceClaimStatus) Size() (n int) { +func (m *EvictionRequestSpec) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.Name) + l = m.Target.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Requester) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Intent) n += 1 + l + sovGenerated(uint64(l)) - if m.ResourceClaimName != nil { - l = len(*m.ResourceClaimName) - n += 1 + l + sovGenerated(uint64(l)) - } return n } -func (m *PodGroupSchedulingConstraints) Size() (n int) { +func (m *EvictionRequestStatus) Size() (n int) { if m == nil { return 0 } var l int _ = l - if len(m.Topology) > 0 { - for _, e := range m.Topology { + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } + if m.ObservedGeneration != nil { + n += 1 + sovGenerated(uint64(*m.ObservedGeneration)) + } return n } -func (m *PodGroupSchedulingPolicy) Size() (n int) { +func (m *EvictionRequestTarget) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.Basic != nil { - l = m.Basic.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Gang != nil { - l = m.Gang.Size() + if m.Pod != nil { + l = m.Pod.Size() n += 1 + l + sovGenerated(uint64(l)) } return n } -func (m *PodGroupSpec) Size() (n int) { +func (m *EvictionSpec) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.PodGroupTemplateRef != nil { - l = m.PodGroupTemplateRef.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - l = m.SchedulingPolicy.Size() + l = m.Target.Size() n += 1 + l + sovGenerated(uint64(l)) - if m.SchedulingConstraints != nil { - l = m.SchedulingConstraints.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.ResourceClaims) > 0 { - for _, e := range m.ResourceClaims { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - } - if m.DisruptionMode != nil { - l = len(*m.DisruptionMode) - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.PriorityClassName) - n += 1 + l + sovGenerated(uint64(l)) - if m.Priority != nil { - n += 1 + sovGenerated(uint64(*m.Priority)) - } return n } -func (m *PodGroupStatus) Size() (n int) { +func (m *EvictionStatus) Size() (n int) { if m == nil { return 0 } @@ -1044,145 +925,100 @@ func (m *PodGroupStatus) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } - if len(m.ResourceClaimStatuses) > 0 { - for _, e := range m.ResourceClaimStatuses { + if m.ObservedGeneration != nil { + n += 1 + sovGenerated(uint64(*m.ObservedGeneration)) + } + if len(m.Requesters) > 0 { + for _, e := range m.Requesters { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } - return n -} - -func (m *PodGroupTemplate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - n += 1 + l + sovGenerated(uint64(l)) - l = m.SchedulingPolicy.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.SchedulingConstraints != nil { - l = m.SchedulingConstraints.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.ResourceClaims) > 0 { - for _, e := range m.ResourceClaims { + if len(m.TargetResponders) > 0 { + for _, e := range m.TargetResponders { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } - if m.DisruptionMode != nil { - l = len(*m.DisruptionMode) - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.PriorityClassName) - n += 1 + l + sovGenerated(uint64(l)) - if m.Priority != nil { - n += 1 + sovGenerated(uint64(*m.Priority)) + if len(m.Responders) > 0 { + for _, e := range m.Responders { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } } return n } -func (m *PodGroupTemplateReference) Size() (n int) { +func (m *EvictionTarget) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.Workload != nil { - l = m.Workload.Size() + if m.Pod != nil { + l = m.Pod.Size() n += 1 + l + sovGenerated(uint64(l)) } return n } -func (m *TopologyConstraint) Size() (n int) { +func (m *Requester) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.Key) + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Intent) n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *TypedLocalObjectReference) Size() (n int) { +func (m *ResponderStatus) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.APIGroup) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Kind) - n += 1 + l + sovGenerated(uint64(l)) l = len(m.Name) n += 1 + l + sovGenerated(uint64(l)) - return n -} - -func (m *Workload) Size() (n int) { - if m == nil { - return 0 + if m.StartTime != nil { + l = m.StartTime.Size() + n += 1 + l + sovGenerated(uint64(l)) } - var l int - _ = l - l = m.ObjectMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Spec.Size() - n += 1 + l + sovGenerated(uint64(l)) - return n -} - -func (m *WorkloadList) Size() (n int) { - if m == nil { - return 0 + if m.HeartbeatTime != nil { + l = m.HeartbeatTime.Size() + n += 1 + l + sovGenerated(uint64(l)) } - var l int - _ = l - l = m.ListMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Items) > 0 { - for _, e := range m.Items { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } + if m.ExpectedCompletionTime != nil { + l = m.ExpectedCompletionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) } - return n -} - -func (m *WorkloadPodGroupTemplateReference) Size() (n int) { - if m == nil { - return 0 + if m.CompletionTime != nil { + l = m.CompletionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Message != nil { + l = len(*m.Message) + n += 1 + l + sovGenerated(uint64(l)) } - var l int - _ = l - l = len(m.WorkloadName) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.PodGroupTemplateName) - n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *WorkloadSpec) Size() (n int) { +func (m *TargetResponder) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.ControllerRef != nil { - l = m.ControllerRef.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.PodGroupTemplates) > 0 { - for _, e := range m.PodGroupTemplates { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) } + l = len(m.State) + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -1192,124 +1028,97 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (this *BasicSchedulingPolicy) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&BasicSchedulingPolicy{`, - `}`, - }, "") - return s -} -func (this *GangSchedulingPolicy) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&GangSchedulingPolicy{`, - `MinCount:` + fmt.Sprintf("%v", this.MinCount) + `,`, - `}`, - }, "") - return s -} -func (this *PodGroup) String() string { +func (this *Eviction) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&PodGroup{`, + s := strings.Join([]string{`&Eviction{`, `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodGroupSpec", "PodGroupSpec", 1), `&`, ``, 1) + `,`, - `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodGroupStatus", "PodGroupStatus", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "EvictionSpec", "EvictionSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "EvictionStatus", "EvictionStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } -func (this *PodGroupList) String() string { +func (this *EvictionList) String() string { if this == nil { return "nil" } - repeatedStringForItems := "[]PodGroup{" + repeatedStringForItems := "[]Eviction{" for _, f := range this.Items { - repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PodGroup", "PodGroup", 1), `&`, ``, 1) + "," + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Eviction", "Eviction", 1), `&`, ``, 1) + "," } repeatedStringForItems += "}" - s := strings.Join([]string{`&PodGroupList{`, + s := strings.Join([]string{`&EvictionList{`, `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + repeatedStringForItems + `,`, `}`, }, "") return s } -func (this *PodGroupResourceClaim) String() string { +func (this *EvictionPodReference) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&PodGroupResourceClaim{`, + s := strings.Join([]string{`&EvictionPodReference{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, - `ResourceClaimTemplateName:` + valueToStringGenerated(this.ResourceClaimTemplateName) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, `}`, }, "") return s } -func (this *PodGroupResourceClaimStatus) String() string { +func (this *EvictionRequest) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&PodGroupResourceClaimStatus{`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + s := strings.Join([]string{`&EvictionRequest{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "EvictionRequestSpec", "EvictionRequestSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "EvictionRequestStatus", "EvictionRequestStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } -func (this *PodGroupSchedulingConstraints) String() string { +func (this *EvictionRequestList) String() string { if this == nil { return "nil" } - repeatedStringForTopology := "[]TopologyConstraint{" - for _, f := range this.Topology { - repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + repeatedStringForItems := "[]EvictionRequest{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "EvictionRequest", "EvictionRequest", 1), `&`, ``, 1) + "," } - repeatedStringForTopology += "}" - s := strings.Join([]string{`&PodGroupSchedulingConstraints{`, - `Topology:` + repeatedStringForTopology + `,`, + repeatedStringForItems += "}" + s := strings.Join([]string{`&EvictionRequestList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, `}`, }, "") return s } -func (this *PodGroupSchedulingPolicy) String() string { +func (this *EvictionRequestPodReference) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&PodGroupSchedulingPolicy{`, - `Basic:` + strings.Replace(this.Basic.String(), "BasicSchedulingPolicy", "BasicSchedulingPolicy", 1) + `,`, - `Gang:` + strings.Replace(this.Gang.String(), "GangSchedulingPolicy", "GangSchedulingPolicy", 1) + `,`, + s := strings.Join([]string{`&EvictionRequestPodReference{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, `}`, }, "") return s } -func (this *PodGroupSpec) String() string { +func (this *EvictionRequestSpec) String() string { if this == nil { return "nil" } - repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" - for _, f := range this.ResourceClaims { - repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," - } - repeatedStringForResourceClaims += "}" - s := strings.Join([]string{`&PodGroupSpec{`, - `PodGroupTemplateRef:` + strings.Replace(this.PodGroupTemplateRef.String(), "PodGroupTemplateReference", "PodGroupTemplateReference", 1) + `,`, - `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, - `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, - `ResourceClaims:` + repeatedStringForResourceClaims + `,`, - `DisruptionMode:` + valueToStringGenerated(this.DisruptionMode) + `,`, - `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, - `Priority:` + valueToStringGenerated(this.Priority) + `,`, + s := strings.Join([]string{`&EvictionRequestSpec{`, + `Target:` + strings.Replace(strings.Replace(this.Target.String(), "EvictionRequestTarget", "EvictionRequestTarget", 1), `&`, ``, 1) + `,`, + `Requester:` + fmt.Sprintf("%v", this.Requester) + `,`, + `Intent:` + fmt.Sprintf("%v", this.Intent) + `,`, `}`, }, "") return s } -func (this *PodGroupStatus) String() string { +func (this *EvictionRequestStatus) String() string { if this == nil { return "nil" } @@ -1318,253 +1127,124 @@ func (this *PodGroupStatus) String() string { repeatedStringForConditions += fmt.Sprintf("%v", f) + "," } repeatedStringForConditions += "}" - repeatedStringForResourceClaimStatuses := "[]PodGroupResourceClaimStatus{" - for _, f := range this.ResourceClaimStatuses { - repeatedStringForResourceClaimStatuses += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaimStatus", "PodGroupResourceClaimStatus", 1), `&`, ``, 1) + "," - } - repeatedStringForResourceClaimStatuses += "}" - s := strings.Join([]string{`&PodGroupStatus{`, + s := strings.Join([]string{`&EvictionRequestStatus{`, `Conditions:` + repeatedStringForConditions + `,`, - `ResourceClaimStatuses:` + repeatedStringForResourceClaimStatuses + `,`, - `}`, - }, "") - return s -} -func (this *PodGroupTemplate) String() string { - if this == nil { - return "nil" - } - repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" - for _, f := range this.ResourceClaims { - repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," - } - repeatedStringForResourceClaims += "}" - s := strings.Join([]string{`&PodGroupTemplate{`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, - `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, - `ResourceClaims:` + repeatedStringForResourceClaims + `,`, - `DisruptionMode:` + valueToStringGenerated(this.DisruptionMode) + `,`, - `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, - `Priority:` + valueToStringGenerated(this.Priority) + `,`, - `}`, - }, "") - return s -} -func (this *PodGroupTemplateReference) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PodGroupTemplateReference{`, - `Workload:` + strings.Replace(this.Workload.String(), "WorkloadPodGroupTemplateReference", "WorkloadPodGroupTemplateReference", 1) + `,`, - `}`, - }, "") - return s -} -func (this *TopologyConstraint) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&TopologyConstraint{`, - `Key:` + fmt.Sprintf("%v", this.Key) + `,`, - `}`, - }, "") - return s -} -func (this *TypedLocalObjectReference) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&TypedLocalObjectReference{`, - `APIGroup:` + fmt.Sprintf("%v", this.APIGroup) + `,`, - `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `}`, - }, "") - return s -} -func (this *Workload) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&Workload{`, - `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "WorkloadSpec", "WorkloadSpec", 1), `&`, ``, 1) + `,`, - `}`, - }, "") - return s -} -func (this *WorkloadList) String() string { - if this == nil { - return "nil" - } - repeatedStringForItems := "[]Workload{" - for _, f := range this.Items { - repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Workload", "Workload", 1), `&`, ``, 1) + "," - } - repeatedStringForItems += "}" - s := strings.Join([]string{`&WorkloadList{`, - `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, - `Items:` + repeatedStringForItems + `,`, - `}`, - }, "") - return s -} -func (this *WorkloadPodGroupTemplateReference) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&WorkloadPodGroupTemplateReference{`, - `WorkloadName:` + fmt.Sprintf("%v", this.WorkloadName) + `,`, - `PodGroupTemplateName:` + fmt.Sprintf("%v", this.PodGroupTemplateName) + `,`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, `}`, }, "") return s } -func (this *WorkloadSpec) String() string { +func (this *EvictionRequestTarget) String() string { if this == nil { return "nil" } - repeatedStringForPodGroupTemplates := "[]PodGroupTemplate{" - for _, f := range this.PodGroupTemplates { - repeatedStringForPodGroupTemplates += strings.Replace(strings.Replace(f.String(), "PodGroupTemplate", "PodGroupTemplate", 1), `&`, ``, 1) + "," - } - repeatedStringForPodGroupTemplates += "}" - s := strings.Join([]string{`&WorkloadSpec{`, - `ControllerRef:` + strings.Replace(this.ControllerRef.String(), "TypedLocalObjectReference", "TypedLocalObjectReference", 1) + `,`, - `PodGroupTemplates:` + repeatedStringForPodGroupTemplates + `,`, + s := strings.Join([]string{`&EvictionRequestTarget{`, + `Pod:` + strings.Replace(this.Pod.String(), "EvictionRequestPodReference", "EvictionRequestPodReference", 1) + `,`, `}`, }, "") return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *BasicSchedulingPolicy) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BasicSchedulingPolicy: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GangSchedulingPolicy) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GangSchedulingPolicy: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MinCount", wireType) - } - m.MinCount = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MinCount |= int32(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } +} +func (this *EvictionSpec) String() string { + if this == nil { + return "nil" } - - if iNdEx > l { - return io.ErrUnexpectedEOF + s := strings.Join([]string{`&EvictionSpec{`, + `Target:` + strings.Replace(strings.Replace(this.Target.String(), "EvictionTarget", "EvictionTarget", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *EvictionStatus) String() string { + if this == nil { + return "nil" } - return nil + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + repeatedStringForRequesters := "[]Requester{" + for _, f := range this.Requesters { + repeatedStringForRequesters += strings.Replace(strings.Replace(f.String(), "Requester", "Requester", 1), `&`, ``, 1) + "," + } + repeatedStringForRequesters += "}" + repeatedStringForTargetResponders := "[]TargetResponder{" + for _, f := range this.TargetResponders { + repeatedStringForTargetResponders += strings.Replace(strings.Replace(f.String(), "TargetResponder", "TargetResponder", 1), `&`, ``, 1) + "," + } + repeatedStringForTargetResponders += "}" + repeatedStringForResponders := "[]ResponderStatus{" + for _, f := range this.Responders { + repeatedStringForResponders += strings.Replace(strings.Replace(f.String(), "ResponderStatus", "ResponderStatus", 1), `&`, ``, 1) + "," + } + repeatedStringForResponders += "}" + s := strings.Join([]string{`&EvictionStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, + `Requesters:` + repeatedStringForRequesters + `,`, + `TargetResponders:` + repeatedStringForTargetResponders + `,`, + `Responders:` + repeatedStringForResponders + `,`, + `}`, + }, "") + return s +} +func (this *EvictionTarget) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EvictionTarget{`, + `Pod:` + strings.Replace(this.Pod.String(), "EvictionPodReference", "EvictionPodReference", 1) + `,`, + `}`, + }, "") + return s +} +func (this *Requester) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Requester{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Intent:` + fmt.Sprintf("%v", this.Intent) + `,`, + `}`, + }, "") + return s +} +func (this *ResponderStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ResponderStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `StartTime:` + strings.Replace(fmt.Sprintf("%v", this.StartTime), "Time", "v1.Time", 1) + `,`, + `HeartbeatTime:` + strings.Replace(fmt.Sprintf("%v", this.HeartbeatTime), "Time", "v1.Time", 1) + `,`, + `ExpectedCompletionTime:` + strings.Replace(fmt.Sprintf("%v", this.ExpectedCompletionTime), "Time", "v1.Time", 1) + `,`, + `CompletionTime:` + strings.Replace(fmt.Sprintf("%v", this.CompletionTime), "Time", "v1.Time", 1) + `,`, + `Message:` + valueToStringGenerated(this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *TargetResponder) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TargetResponder{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `State:` + fmt.Sprintf("%v", this.State) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) } -func (m *PodGroup) Unmarshal(dAtA []byte) error { +func (m *Eviction) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1587,10 +1267,10 @@ func (m *PodGroup) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroup: wiretype end group for non-group") + return fmt.Errorf("proto: Eviction: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroup: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Eviction: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1713,7 +1393,7 @@ func (m *PodGroup) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupList) Unmarshal(dAtA []byte) error { +func (m *EvictionList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1736,10 +1416,10 @@ func (m *PodGroupList) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupList: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupList: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1804,7 +1484,7 @@ func (m *PodGroupList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, PodGroup{}) + m.Items = append(m.Items, Eviction{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } @@ -1830,7 +1510,7 @@ func (m *PodGroupList) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { +func (m *EvictionPodReference) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1853,10 +1533,10 @@ func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupResourceClaim: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionPodReference: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupResourceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionPodReference: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1893,40 +1573,7 @@ func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - s := string(dAtA[iNdEx:postIndex]) - m.ResourceClaimName = &s - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimTemplateName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1954,8 +1601,7 @@ func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.ResourceClaimTemplateName = &s + m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -1978,7 +1624,7 @@ func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { +func (m *EvictionRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2001,17 +1647,17 @@ func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupResourceClaimStatus: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupResourceClaimStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2021,29 +1667,30 @@ func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2053,78 +1700,28 @@ func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.ResourceClaimName = &s - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PodGroupSchedulingConstraints: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + iNdEx = postIndex + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2151,8 +1748,7 @@ func (m *PodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Topology = append(m.Topology, TopologyConstraint{}) - if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -2177,7 +1773,7 @@ func (m *PodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { +func (m *EvictionRequestList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2200,15 +1796,15 @@ func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupSchedulingPolicy: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionRequestList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionRequestList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2235,16 +1831,13 @@ func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Basic == nil { - m.Basic = &BasicSchedulingPolicy{} - } - if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2271,10 +1864,8 @@ func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Gang == nil { - m.Gang = &GangSchedulingPolicy{} - } - if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Items = append(m.Items, EvictionRequest{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -2299,7 +1890,7 @@ func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { +func (m *EvictionRequestPodReference) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2322,17 +1913,17 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupSpec: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionRequestPodReference: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupSpec: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionRequestPodReference: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplateRef", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2342,33 +1933,29 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.PodGroupTemplateRef == nil { - m.PodGroupTemplateRef = &PodGroupTemplateReference{} - } - if err := m.PodGroupTemplateRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2378,64 +1965,77 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - postIndex := iNdEx + msglen - if postIndex < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } - if postIndex > l { + if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } - if m.SchedulingConstraints == nil { - m.SchedulingConstraints = &PodGroupSchedulingConstraints{} + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EvictionRequestSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF } - if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break } - iNdEx = postIndex - case 4: + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvictionRequestSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvictionRequestSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Target", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2462,14 +2062,13 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) - if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Target.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 5: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2497,12 +2096,11 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := DisruptionMode(dAtA[iNdEx:postIndex]) - m.DisruptionMode = &s + m.Requester = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 6: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Intent", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2530,28 +2128,8 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + m.Intent = EvictionRequestIntent(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) - } - var v int32 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int32(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Priority = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -2573,7 +2151,7 @@ func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { +func (m *EvictionRequestStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2596,10 +2174,10 @@ func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupStatus: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionRequestStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionRequestStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2637,10 +2215,10 @@ func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimStatuses", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) } - var msglen int + var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2650,26 +2228,12 @@ func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + v |= int64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ResourceClaimStatuses = append(m.ResourceClaimStatuses, PodGroupResourceClaimStatus{}) - if err := m.ResourceClaimStatuses[len(m.ResourceClaimStatuses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex + m.ObservedGeneration = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -2691,7 +2255,7 @@ func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { } return nil } -func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { +func (m *EvictionRequestTarget) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2714,17 +2278,17 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PodGroupTemplate: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionRequestTarget: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionRequestTarget: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pod", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2734,60 +2298,81 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + if m.Pod == nil { + m.Pod = &EvictionRequestPodReference{} } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } + if err := m.Pod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - if msglen < 0 { - return ErrInvalidLengthGenerated + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - postIndex := iNdEx + msglen - if postIndex < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } - if postIndex > l { + if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } - if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EvictionSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - iNdEx = postIndex - case 3: + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvictionSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvictionSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Target", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2814,16 +2399,63 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.SchedulingConstraints == nil { - m.SchedulingConstraints = &PodGroupSchedulingConstraints{} - } - if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Target.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 4: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *EvictionStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: EvictionStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EvictionStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2850,16 +2482,16 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) - if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ObservedGeneration", wireType) } - var stringLen uint64 + var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2869,30 +2501,17 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + v |= int64(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - s := DisruptionMode(dAtA[iNdEx:postIndex]) - m.DisruptionMode = &s - iNdEx = postIndex - case 6: + m.ObservedGeneration = &v + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requesters", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2902,29 +2521,31 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + m.Requesters = append(m.Requesters, Requester{}) + if err := m.Requesters[len(m.Requesters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TargetResponders", wireType) } - var v int32 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2934,65 +2555,29 @@ func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int32(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - m.Priority = &v - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PodGroupTemplateReference) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated + if msglen < 0 { + return ErrInvalidLengthGenerated } - if iNdEx >= l { + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + m.TargetResponders = append(m.TargetResponders, TargetResponder{}) + if err := m.TargetResponders[len(m.TargetResponders)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PodGroupTemplateReference: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PodGroupTemplateReference: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + iNdEx = postIndex + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Workload", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Responders", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3019,10 +2604,8 @@ func (m *PodGroupTemplateReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Workload == nil { - m.Workload = &WorkloadPodGroupTemplateReference{} - } - if err := m.Workload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Responders = append(m.Responders, ResponderStatus{}) + if err := m.Responders[len(m.Responders)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -3047,7 +2630,7 @@ func (m *PodGroupTemplateReference) Unmarshal(dAtA []byte) error { } return nil } -func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { +func (m *EvictionTarget) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3070,17 +2653,17 @@ func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: TopologyConstraint: wiretype end group for non-group") + return fmt.Errorf("proto: EvictionTarget: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: TopologyConstraint: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EvictionTarget: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pod", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -3090,23 +2673,27 @@ func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Key = string(dAtA[iNdEx:postIndex]) + if m.Pod == nil { + m.Pod = &EvictionPodReference{} + } + if err := m.Pod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -3129,7 +2716,7 @@ func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { } return nil } -func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { +func (m *Requester) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3152,15 +2739,15 @@ func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: TypedLocalObjectReference: wiretype end group for non-group") + return fmt.Errorf("proto: Requester: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: TypedLocalObjectReference: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Requester: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field APIGroup", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3188,43 +2775,11 @@ func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.APIGroup = string(dAtA[iNdEx:postIndex]) + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Kind = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Intent", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3252,7 +2807,7 @@ func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.Intent = RequesterIntent(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -3275,7 +2830,7 @@ func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { } return nil } -func (m *Workload) Unmarshal(dAtA []byte) error { +func (m *ResponderStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3298,17 +2853,17 @@ func (m *Workload) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Workload: wiretype end group for non-group") + return fmt.Errorf("proto: ResponderStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Workload: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ResponderStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -3318,28 +2873,27 @@ func (m *Workload) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StartTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3366,63 +2920,16 @@ func (m *Workload) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + if m.StartTime == nil { + m.StartTime = &v1.Time{} } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { + if err := m.StartTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *WorkloadList) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: WorkloadList: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: WorkloadList: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + iNdEx = postIndex + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field HeartbeatTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3449,13 +2956,16 @@ func (m *WorkloadList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if m.HeartbeatTime == nil { + m.HeartbeatTime = &v1.Time{} + } + if err := m.HeartbeatTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 2: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ExpectedCompletionTime", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3482,66 +2992,18 @@ func (m *WorkloadList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, Workload{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + if m.ExpectedCompletionTime == nil { + m.ExpectedCompletionTime = &v1.Time{} } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { + if err := m.ExpectedCompletionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *WorkloadPodGroupTemplateReference) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: WorkloadPodGroupTemplateReference: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: WorkloadPodGroupTemplateReference: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + iNdEx = postIndex + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WorkloadName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CompletionTime", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -3551,27 +3013,31 @@ func (m *WorkloadPodGroupTemplateReference) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.WorkloadName = string(dAtA[iNdEx:postIndex]) + if m.CompletionTime == nil { + m.CompletionTime = &v1.Time{} + } + if err := m.CompletionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplateName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3599,7 +3065,8 @@ func (m *WorkloadPodGroupTemplateReference) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.PodGroupTemplateName = string(dAtA[iNdEx:postIndex]) + s := string(dAtA[iNdEx:postIndex]) + m.Message = &s iNdEx = postIndex default: iNdEx = preIndex @@ -3622,7 +3089,7 @@ func (m *WorkloadPodGroupTemplateReference) Unmarshal(dAtA []byte) error { } return nil } -func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { +func (m *TargetResponder) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3645,17 +3112,17 @@ func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: WorkloadSpec: wiretype end group for non-group") + return fmt.Errorf("proto: TargetResponder: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: WorkloadSpec: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: TargetResponder: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ControllerRef", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -3665,33 +3132,49 @@ func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.ControllerRef == nil { - m.ControllerRef = &TypedLocalObjectReference{} - } - if err := m.ControllerRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplates", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field State", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -3701,25 +3184,23 @@ func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.PodGroupTemplates = append(m.PodGroupTemplates, PodGroupTemplate{}) - if err := m.PodGroupTemplates[len(m.PodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.State = ResponderStateType(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.proto new file mode 100644 index 000000000..cef2c730d --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/generated.proto @@ -0,0 +1,529 @@ +/* +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. +*/ + + +// This file was autogenerated by go-to-protobuf. Do not edit it manually! + +syntax = "proto2"; + +package k8s.io.api.lifecycle.v1alpha1; + +import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; + +// Package-wide variables from generator "generated". +option go_package = "k8s.io/api/lifecycle/v1alpha1"; + +// Eviction initiates an eviction process, which should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. It manages the Eviction lifecycle. +// Requesters are preserved in .status.requesters even after they have withdrawn their request. +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Once all EvictionRequest corresponding to this Eviction .spec.target have been +// removed, this Eviction object will eventually be garbage collected. +// +// If the target is a pod, the .status.targetResponders is populated from Pod's +// .spec.evictionResponders. +// +// Responders should observe and communicate through the .status to help with the eviction +// of the target when they see their state == Active in .status.targetResponders. ResponderStatus +// struct should then be periodically updated to indicate the progress or completion of the eviction +// process by each responder in .status.responders. If .status.responders[].heartbeatTime is not +// updated within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the +// eviction is passed over to the next responder with a lower priority. +// +// If there are no other responders and the target is a pod, the last default +// imperative-eviction.k8s.io/evictor responder with a priority of 100 will evict the pod using the +// imperative Eviction API (pods//eviction subresource). +// +k8s:validation-gen-nolint // Note: remove this when the API got GA +message Eviction { + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // .metadata.name set by the evictionrequest-controller is purely informative and subject to change. + // .spec.target field should be used to identify the target precisesly. + // + // The requester and responder names will be used as label keys and added to the labels of the + // eviction in one of the following formats: + // 1. acme.io/foo: "requester" + // 2. acme.io/foo: "responder" + // 3. acme.io/foo: "requester-responder" + // + // Please see EvictionParticipantRole for available role label values. + // +optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the eviction specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +required + optional EvictionSpec spec = 2; + + // status represents the most recently observed status of the eviction. + // Populated by responders and evictionrequest-controller. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + optional EvictionStatus status = 3; +} + +// EvictionList contains a list of Eviction resources. +message EvictionList { + // metadata is the standard list metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // items is the list of Evictions. + repeated Eviction items = 2; +} + +// EvictionPodReference contains enough information to locate the referenced pod inside the same +// namespace. +message EvictionPodReference { + // name of the target. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-long-name + optional string name = 1; + + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-uuid + optional string uid = 2; +} + +// EvictionRequest defines a request that should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. +// - .spec.requester is set as a label on the Eviction for easier lookup. +// - Each target can have a set of responders assigned to it. Eviction objects are observed by +// these responders, who implement the eviction logic and update the Eviction's status with +// progress. +// +// There is many-to-many relationship between EvictionRequests and Evictions in general. +// And many-to-one if the target is a pod. +// +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Deleting an EvictionRequest also counts as a withdrawal. +// Once all EvictionRequest of a target are removed, the corresponding Evictions are eventually +// garbage collected. +// +// +k8s:validation-gen-nolint // Note: remove this when the API got GA +message EvictionRequest { + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // +optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the eviction request specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +required + optional EvictionRequestSpec spec = 2; + + // status represents the most recently observed status of the eviction request. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + optional EvictionRequestStatus status = 3; +} + +// EvictionRequestList contains a list of EvictionRequests resources. +message EvictionRequestList { + // metadata is the standard list metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // items is the list of EvictionRequests. + repeated EvictionRequest items = 2; +} + +// EvictionRequestPodReference contains enough information to locate the referenced pod inside the +// same namespace. +message EvictionRequestPodReference { + // name of the target. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-long-name + optional string name = 1; + + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-uuid + optional string uid = 2; +} + +// EvictionRequestSpec is a specification of an EvictionRequest. +message EvictionRequestSpec { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + // +required + // +k8s:immutable + optional EvictionRequestTarget target = 1; + + // requester allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field is required and immutable. + // +required + // +k8s:required + // +k8s:immutable + // +k8s:format=k8s-prefixed-label-key + // +k8s:customValidation + optional string requester = 2; + + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn for a common target, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + // +required + // +k8s:required + optional string intent = 3; +} + +// EvictionRequestStatus represents the last observed status of the eviction request. +message EvictionRequestStatus { + // conditions contain information about the eviction request. + // + // EvictionRequest specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // These conditions can be reset if the eviction was unsuccessful and a new Eviction intent has + // been submitted. + // + // The maximum length of the conditions list is 100. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:maxItems=100 + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // observedGeneration is EvictionRequest's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + // +optional + // +k8s:optional + // +k8s:minimum=1 + // +k8s:update=NoUnset + // +k8s:monotonic + optional int64 observedGeneration = 2; +} + +// EvictionRequestTarget contains a reference to an object that should be evicted. +// +union +message EvictionRequestTarget { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + // +optional + // +k8s:optional + // +k8s:unionMember + optional EvictionRequestPodReference pod = 1; +} + +// EvictionSpec is a specification of an Eviction. +message EvictionSpec { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + // +required + // +k8s:immutable + optional EvictionTarget target = 1; +} + +// EvictionStatus represents the last observed status of the eviction request. +message EvictionStatus { + // conditions contain information about the eviction request. + // + // Eviction specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // The maximum length of the conditions list is 100. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:maxItems=100 + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // observedGeneration is Eviction's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + // +optional + // +k8s:optional + // +k8s:minimum=1 + // +k8s:monotonic + // +k8s:update=NoUnset + optional int64 observedGeneration = 2; + + // requesters allow you to identify the entities, that requested the eviction of the target. + // If all the requesters withdraw their eviction intent, the eviction will be canceled. + // + // The maximum length of the requesters list is 100. + // If this limit is exceeded, requesters with Withdrawn intent should be dropped first. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=100 + repeated Requester requesters = 3; + + // targetResponders reference responders that should eventually respond to this eviction + // to help with the graceful eviction of a target. These responders are selected sequentially, + // according to their specified priority by setting the Active state to the TargetResponder + // .state field. The maximum number of active responders allowed is 1. + // Eventually each responder can end up in an Interrupted, Canceled or, Completed state. + // Responders should observe these states in order to navigate their lifecycle. + // + // If the target is a pod, the field is populated from Pod's .spec.evictionResponders. Default + // responders may be added to the list according to the target. + // + // Default responders: + // - imperative-eviction.k8s.io/evictor responder with a priority of 100 is added to the list if the + // target is a pod. It will call the imperative Eviction API (pods//eviction subresource). + // This call may not succeed due to PodDisruptionBudgets, which may block the pod termination. + // It will update the responder message and try again with a backoff. + // + // The maximum length of the responders list is 11. + // The length and keys of the list cannot change once set. + // This field is managed by evictionrequest-controller. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=11 + repeated TargetResponder targetResponders = 4; + + // responders represents the eviction process status of each declared responder. + // + // The responder list should be the same length and have the same .name fields as + // .status.targetResponders. Only responders with .name that have Active state in + // .targetResponders[].state should be updated and can be mutated. First initialization + // of the list is allowed. + // + // Each ResponderStatus is initialized by evictionrequest-controller and then managed by + // the designated responder. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=11 + repeated ResponderStatus responders = 5; +} + +// EvictionTarget contains a reference to an object that should be evicted. +// +union +message EvictionTarget { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + // +optional + // +k8s:optional + // +k8s:unionMember + optional EvictionPodReference pod = 1; +} + +// Requester allows you to identify the entity, that requested the eviction of the target. +// +structType=atomic +message Requester { + // name allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each requester. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + optional string name = 1; + + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + // +required + // +k8s:required + optional string intent = 2; +} + +// ResponderStatus represents the last observed status of the eviction process of the responder. +// It should be only updated by the designated responder whose name is .name field. +// +structType=granular +message ResponderStatus { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field is initialized by Kubernetes and must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + optional string name = 1; + + // startTime tracks the time at which this responder was designated as active and should start + // processing the eviction request. + // It should reflect the present time when set. + // This field is initialized by Kubernetes when this responder becomes active. + // This field becomes immutable once set. + // +optional + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time startTime = 2; + + // heartbeatTime is the last time at which the eviction process was reported to be in progress + // by the responder. + // It should reflect the present time when set. + // Responders should avoid heartbeats more frequent than 20 seconds to avoid overloading the + // control-plane. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time heartbeatTime = 3; + + // expectedCompletionTime is the time at which the eviction process step is expected to end for the + // responder. + // The time cannot be set to the past. + // May be omitted if no estimate can be made. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time expectedCompletionTime = 4; + + // completionTime tracks the time at which the Responder stopped processing the eviction request. + // Completion means that the responders has either fully or partially completed the + // eviction process, which may have resulted in target eviction (e.g. pod termination). + // It should reflect the present time when set. + // This field becomes immutable once set. + // +optional + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time completionTime = 5; + + // message provides human-readable details about the state of the responder and the eviction + // process. + // Maximum length is 4000 characters. + // +optional + // +k8s:optional + // +k8s:maxLength=4000 + optional string message = 6; +} + +// TargetResponder allows you to specify the responder reacting to the Eviction. +// Responders should observe and communicate through the Eviction API (see .state) to help +// with the graceful eviction of a target (e.g. termination of a pod). +// +structType=atomic +message TargetResponder { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + optional string name = 1; + + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required and immutable. + // +required + // +k8s:required + // +k8s:minimum=0 + // +k8s:maximum=100000 + // +k8s:update=NoModify + // +k8s:update=NoUnset + optional int32 priority = 2; + + // state specifies a state that is assigned by the evictionrequest-controller. Responders should observe + // this state in order to navigate their lifecycle. + // - Inactive means that the responder should not yet process this eviction request. + // - Active means that the responder is either running or expected to start soon. + // Also, startTime has been set in the ResponderStatus by the evictionrequest-controller. + // + // An active responder should currently interact with the eviction process by updating + // .status.responders, where .name is the active responder name. ResponderStatus fields + // should be periodically updated to indicate the progress or completion of the eviction process. + // If .status.responders[].heartbeatTime field is not updated within the heartbeat deadline defined + // by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder + // with a lower priority. Only one responder can be active at a time. + // - Interrupted means that the responder has failed to start or failed to update + // heartbeatTime in ResponderStatus in a timely manner. + // - Canceled means that the responder has been canceled. In other words, there is no + // EvictionRequest with the same target and Eviction intent in .spec.intent. + // - Completed means that the responder has successfully completed and set completionTime + // in ResponderStatus. + // + // Please refer to the ResponderStatus in .status.responders for more details on each responder. + // +required + // +k8s:required + optional string state = 3; +} + diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/register.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/register.go new file mode 100644 index 000000000..1efd34172 --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/register.go @@ -0,0 +1,55 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// GroupName is the group name use in this package +const GroupName = "lifecycle.k8s.io" + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. + // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + localSchemeBuilder = &SchemeBuilder + AddToScheme = localSchemeBuilder.AddToScheme +) + +// Adds the list of known types to api.Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &Eviction{}, + &EvictionList{}, + &EvictionRequest{}, + &EvictionRequestList{}, + ) + + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types.go new file mode 100644 index 000000000..42bbb44cf --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types.go @@ -0,0 +1,680 @@ +/* +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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apimachinerytypes "k8s.io/apimachinery/pkg/types" +) + +const ( + // EvictionResponderImperativeEviction is a default responder that will evict pods using the imperative + // Eviction API (pods//eviction subresource) with a backoff. + EvictionResponderImperativeEviction string = "imperative-eviction.k8s.io/evictor" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:supportsSubresource="/status" + +// EvictionRequest defines a request that should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. +// - .spec.requester is set as a label on the Eviction for easier lookup. +// - Each target can have a set of responders assigned to it. Eviction objects are observed by +// these responders, who implement the eviction logic and update the Eviction's status with +// progress. +// +// There is many-to-many relationship between EvictionRequests and Evictions in general. +// And many-to-one if the target is a pod. +// +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Deleting an EvictionRequest also counts as a withdrawal. +// Once all EvictionRequest of a target are removed, the corresponding Evictions are eventually +// garbage collected. +// +// +k8s:validation-gen-nolint // Note: remove this when the API got GA +type EvictionRequest struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // +optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the eviction request specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +required + Spec EvictionRequestSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status represents the most recently observed status of the eviction request. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status EvictionRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// EvictionRequestSpec is a specification of an EvictionRequest. +type EvictionRequestSpec struct { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + // +required + // +k8s:immutable + Target EvictionRequestTarget `json:"target" protobuf:"bytes,1,opt,name=target"` + + // requester allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field is required and immutable. + // +required + // +k8s:required + // +k8s:immutable + // +k8s:format=k8s-prefixed-label-key + // +k8s:customValidation + Requester string `json:"requester" protobuf:"bytes,2,opt,name=requester"` + + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn for a common target, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + // +required + // +k8s:required + Intent EvictionRequestIntent `json:"intent" protobuf:"bytes,3,opt,name=intent,casttype=EvictionRequestIntent"` +} + +// EvictionRequestTarget contains a reference to an object that should be evicted. +// +union +type EvictionRequestTarget struct { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + // +optional + // +k8s:optional + // +k8s:unionMember + Pod *EvictionRequestPodReference `json:"pod,omitempty" protobuf:"bytes,1,opt,name=pod"` +} + +// EvictionRequestPodReference contains enough information to locate the referenced pod inside the +// same namespace. +type EvictionRequestPodReference struct { + // name of the target. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-long-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-uuid + UID apimachinerytypes.UID `json:"uid" protobuf:"bytes,2,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"` +} + +// EvictionRequestIntent specifies a requester intent. +// +enum +// +k8s:enum +type EvictionRequestIntent string + +// These are intents that can be set by each requester. +const ( + // EvictionRequestIntentEviction means that the requester is interested in the eviction of the target. + EvictionRequestIntentEviction EvictionRequestIntent = "Eviction" + + // EvictionRequestIntentWithdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn for a common target, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + EvictionRequestIntentWithdrawn EvictionRequestIntent = "Withdrawn" +) + +// EvictionRequestStatus represents the last observed status of the eviction request. +type EvictionRequestStatus struct { + // conditions contain information about the eviction request. + // + // EvictionRequest specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // These conditions can be reset if the eviction was unsuccessful and a new Eviction intent has + // been submitted. + // + // The maximum length of the conditions list is 100. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:maxItems=100 + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + + // observedGeneration is EvictionRequest's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + // +optional + // +k8s:optional + // +k8s:minimum=1 + // +k8s:update=NoUnset + // +k8s:monotonic + ObservedGeneration *int64 `json:"observedGeneration,omitempty" protobuf:"varint,2,opt,name=observedGeneration"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// EvictionRequestList contains a list of EvictionRequests resources. +type EvictionRequestList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // items is the list of EvictionRequests. + Items []EvictionRequest `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:supportsSubresource="/status" + +// Eviction initiates an eviction process, which should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. It manages the Eviction lifecycle. +// Requesters are preserved in .status.requesters even after they have withdrawn their request. +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Once all EvictionRequest corresponding to this Eviction .spec.target have been +// removed, this Eviction object will eventually be garbage collected. +// +// If the target is a pod, the .status.targetResponders is populated from Pod's +// .spec.evictionResponders. +// +// Responders should observe and communicate through the .status to help with the eviction +// of the target when they see their state == Active in .status.targetResponders. ResponderStatus +// struct should then be periodically updated to indicate the progress or completion of the eviction +// process by each responder in .status.responders. If .status.responders[].heartbeatTime is not +// updated within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the +// eviction is passed over to the next responder with a lower priority. +// +// If there are no other responders and the target is a pod, the last default +// imperative-eviction.k8s.io/evictor responder with a priority of 100 will evict the pod using the +// imperative Eviction API (pods//eviction subresource). +// +k8s:validation-gen-nolint // Note: remove this when the API got GA +type Eviction struct { + metav1.TypeMeta `json:",inline"` + + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // .metadata.name set by the evictionrequest-controller is purely informative and subject to change. + // .spec.target field should be used to identify the target precisesly. + // + // The requester and responder names will be used as label keys and added to the labels of the + // eviction in one of the following formats: + // 1. acme.io/foo: "requester" + // 2. acme.io/foo: "responder" + // 3. acme.io/foo: "requester-responder" + // + // Please see EvictionParticipantRole for available role label values. + // +optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the eviction specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +required + Spec EvictionSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status represents the most recently observed status of the eviction. + // Populated by responders and evictionrequest-controller. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status EvictionStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// EvictionParticipantRole specifies a role of an eviction participant intent. +type EvictionParticipantRole string + +const ( + // EvictionParticipantRoleRequester identifies a requester which creates EvictionRequests. + EvictionParticipantRoleRequester EvictionParticipantRole = "requester" + + // EvictionParticipantRoleResponder identifies a responder which responds to an Eviction. + EvictionParticipantRoleResponder EvictionParticipantRole = "responder" + + // EvictionParticipantRoleRequesterResponder is both a "requester" and a "responder" at the same time. + EvictionParticipantRoleRequesterResponder EvictionParticipantRole = "requester-responder" +) + +// EvictionSpec is a specification of an Eviction. +type EvictionSpec struct { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + // +required + // +k8s:immutable + Target EvictionTarget `json:"target" protobuf:"bytes,1,opt,name=target"` +} + +// EvictionTarget contains a reference to an object that should be evicted. +// +union +type EvictionTarget struct { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + // +optional + // +k8s:optional + // +k8s:unionMember + Pod *EvictionPodReference `json:"pod,omitempty" protobuf:"bytes,1,opt,name=pod"` +} + +// EvictionPodReference contains enough information to locate the referenced pod inside the same +// namespace. +type EvictionPodReference struct { + // name of the target. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-long-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-uuid + UID apimachinerytypes.UID `json:"uid" protobuf:"bytes,2,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"` +} + +// EvictionStatus represents the last observed status of the eviction request. +type EvictionStatus struct { + // conditions contain information about the eviction request. + // + // Eviction specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // The maximum length of the conditions list is 100. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + // +k8s:maxItems=100 + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + + // observedGeneration is Eviction's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + // +optional + // +k8s:optional + // +k8s:minimum=1 + // +k8s:monotonic + // +k8s:update=NoUnset + ObservedGeneration *int64 `json:"observedGeneration,omitempty" protobuf:"varint,2,opt,name=observedGeneration"` + + // requesters allow you to identify the entities, that requested the eviction of the target. + // If all the requesters withdraw their eviction intent, the eviction will be canceled. + // + // The maximum length of the requesters list is 100. + // If this limit is exceeded, requesters with Withdrawn intent should be dropped first. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=100 + Requesters []Requester `json:"requesters,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,3,rep,name=requesters"` + + // targetResponders reference responders that should eventually respond to this eviction + // to help with the graceful eviction of a target. These responders are selected sequentially, + // according to their specified priority by setting the Active state to the TargetResponder + // .state field. The maximum number of active responders allowed is 1. + // Eventually each responder can end up in an Interrupted, Canceled or, Completed state. + // Responders should observe these states in order to navigate their lifecycle. + // + // If the target is a pod, the field is populated from Pod's .spec.evictionResponders. Default + // responders may be added to the list according to the target. + // + // Default responders: + // - imperative-eviction.k8s.io/evictor responder with a priority of 100 is added to the list if the + // target is a pod. It will call the imperative Eviction API (pods//eviction subresource). + // This call may not succeed due to PodDisruptionBudgets, which may block the pod termination. + // It will update the responder message and try again with a backoff. + // + // The maximum length of the responders list is 11. + // The length and keys of the list cannot change once set. + // This field is managed by evictionrequest-controller. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=11 + TargetResponders []TargetResponder `json:"targetResponders,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,4,rep,name=targetResponders"` + + // responders represents the eviction process status of each declared responder. + // + // The responder list should be the same length and have the same .name fields as + // .status.targetResponders. Only responders with .name that have Active state in + // .targetResponders[].state should be updated and can be mutated. First initialization + // of the list is allowed. + // + // Each ResponderStatus is initialized by evictionrequest-controller and then managed by + // the designated responder. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=11 + Responders []ResponderStatus `json:"responders,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,5,rep,name=responders"` +} + +type EvictionConditionType string + +// These are built-in conditions of an eviction request. +const ( + // EvictionConditionFailed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + EvictionConditionFailed EvictionConditionType = "Failed" + + // EvictionConditionTargetEvicted means that the target has been evicted (e.g. a pod has been + // terminated or deleted). + EvictionConditionTargetEvicted EvictionConditionType = "TargetEvicted" +) + +type EvictionConditionReason string + +// These are built-in condition reasons of an eviction request. +const ( + // EvictionConditionReasonAwaitingEviction means that this Eviction works as expected and the target + // is scheduled for an eviction. + // This reason is set for the Failed and TargetEvicted condition. + EvictionConditionReasonAwaitingEviction EvictionConditionReason = "AwaitingEviction" + // EvictionConditionReasonEvictionInvalid means that the Eviction is not accepted because the + // initial configuration is not valid. + // This reason is set for the Failed condition. + EvictionConditionReasonEvictionInvalid EvictionConditionReason = "EvictionInvalid" + // EvictionConditionReasonCanceledDueToNoRequesters means that the Eviction is canceled because there is no + // EvictionRequest with the same target and Eviction intent in .spec.intent. + // This reason is set for the Failed condition. + EvictionConditionReasonCanceledDueToNoRequesters EvictionConditionReason = "CanceledDueToNoRequesters" + // EvictionConditionReasonSucceeded means that the Eviction has successfully evicted the target. + // This reason is set for the Failed condition. + EvictionConditionReasonSucceeded EvictionConditionReason = "Succeeded" + // EvictionConditionReasonNoFurtherResponder means that the Eviction responders failed to evict + // the target and that no further responder is available. + // This reason is set for the Failed condition. + EvictionConditionReasonNoFurtherResponder EvictionConditionReason = "NoFurtherResponder" + // EvictionConditionReasonPodDeleted means that the target pod has been deleted. + // This reason is set for the TargetEvicted condition. + EvictionConditionReasonPodDeleted EvictionConditionReason = "PodDeleted" + // EvictionConditionReasonPodTerminal means that the target pod has reached a terminal state. + // This reason is set for the TargetEvicted condition. + EvictionConditionReasonPodTerminal EvictionConditionReason = "PodTerminal" + // EvictionConditionReasonEvictionFailed means that the eviction of the target was unsuccessful. + // This reason is set for the TargetEvicted condition. + EvictionConditionReasonEvictionFailed EvictionConditionReason = "EvictionFailed" +) + +// Requester allows you to identify the entity, that requested the eviction of the target. +// +structType=atomic +type Requester struct { + // name allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each requester. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + // +required + // +k8s:required + Intent RequesterIntent `json:"intent" protobuf:"bytes,2,opt,name=intent,casttype=RequesterIntent"` +} + +// RequesterIntent specifies a requester intent. +// +enum +// +k8s:enum +type RequesterIntent string + +// These are intents that can be set by each requester. +const ( + // RequesterIntentEviction means that the requester is interested in the eviction of the target. + RequesterIntentEviction RequesterIntent = "Eviction" + + // RequesterIntentWithdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + RequesterIntentWithdrawn RequesterIntent = "Withdrawn" +) + +// TargetResponder allows you to specify the responder reacting to the Eviction. +// Responders should observe and communicate through the Eviction API (see .state) to help +// with the graceful eviction of a target (e.g. termination of a pod). +// +structType=atomic +type TargetResponder struct { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required and immutable. + // +required + // +k8s:required + // +k8s:minimum=0 + // +k8s:maximum=100000 + // +k8s:update=NoModify + // +k8s:update=NoUnset + Priority *int32 `json:"priority" protobuf:"varint,2,opt,name=priority"` + + // state specifies a state that is assigned by the evictionrequest-controller. Responders should observe + // this state in order to navigate their lifecycle. + // - Inactive means that the responder should not yet process this eviction request. + // - Active means that the responder is either running or expected to start soon. + // Also, startTime has been set in the ResponderStatus by the evictionrequest-controller. + // + // An active responder should currently interact with the eviction process by updating + // .status.responders, where .name is the active responder name. ResponderStatus fields + // should be periodically updated to indicate the progress or completion of the eviction process. + // If .status.responders[].heartbeatTime field is not updated within the heartbeat deadline defined + // by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder + // with a lower priority. Only one responder can be active at a time. + // - Interrupted means that the responder has failed to start or failed to update + // heartbeatTime in ResponderStatus in a timely manner. + // - Canceled means that the responder has been canceled. In other words, there is no + // EvictionRequest with the same target and Eviction intent in .spec.intent. + // - Completed means that the responder has successfully completed and set completionTime + // in ResponderStatus. + // + // Please refer to the ResponderStatus in .status.responders for more details on each responder. + // +required + // +k8s:required + State ResponderStateType `json:"state" protobuf:"bytes,3,opt,name=state,casttype=ResponderStateType"` +} + +// ResponderStateType specifies a state that is assigned by the evictionrequest-controller. +// +enum +// +k8s:enum +type ResponderStateType string + +const ( + // ResponderStateInactive means that the responder should not yet process this eviction request. + ResponderStateInactive ResponderStateType = "Inactive" + + // ResponderStateActive means that the responder is either running or expected to start soon. + // Also, startTime has been set in the ResponderStatus by the evictionrequest-controller. + // + // An active responder should currently interact with the eviction process by updating + // .status.responders, where .name is the active responder name. ResponderStatus fields + // should be periodically updated to indicate the progress or completion of the eviction process. + // If .status.responders[].heartbeatTime field is not updated within the heartbeat deadline defined + // by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder + // with a lower priority. Only one responder can be active at a time. + ResponderStateActive ResponderStateType = "Active" + + // ResponderStateInterrupted means that the responder has failed to start or failed to update + // heartbeatTime in ResponderStatus in a timely manner. + ResponderStateInterrupted ResponderStateType = "Interrupted" + + // ResponderStateCanceled means that the responder has been canceled. In other words, there + // is no EvictionRequest with the same target and Eviction intent in .spec.intent. + ResponderStateCanceled ResponderStateType = "Canceled" + + // ResponderStateCompleted means that the responder has successfully completed and set completionTime + // in ResponderStatus. + ResponderStateCompleted ResponderStateType = "Completed" +) + +// ResponderStatus represents the last observed status of the eviction process of the responder. +// It should be only updated by the designated responder whose name is .name field. +// +structType=granular +type ResponderStatus struct { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field is initialized by Kubernetes and must be unique for each responder. + // This field is required. + // +required + // +k8s:required + // +k8s:format=k8s-prefixed-label-key + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // startTime tracks the time at which this responder was designated as active and should start + // processing the eviction request. + // It should reflect the present time when set. + // This field is initialized by Kubernetes when this responder becomes active. + // This field becomes immutable once set. + // +optional + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + StartTime *metav1.Time `json:"startTime,omitempty" protobuf:"bytes,2,opt,name=startTime"` + + // heartbeatTime is the last time at which the eviction process was reported to be in progress + // by the responder. + // It should reflect the present time when set. + // Responders should avoid heartbeats more frequent than 20 seconds to avoid overloading the + // control-plane. + // +optional + // +k8s:optional + HeartbeatTime *metav1.Time `json:"heartbeatTime,omitempty" protobuf:"bytes,3,opt,name=heartbeatTime"` + + // expectedCompletionTime is the time at which the eviction process step is expected to end for the + // responder. + // The time cannot be set to the past. + // May be omitted if no estimate can be made. + // +optional + // +k8s:optional + ExpectedCompletionTime *metav1.Time `json:"expectedCompletionTime,omitempty" protobuf:"bytes,4,opt,name=expectedCompletionTime"` + + // completionTime tracks the time at which the Responder stopped processing the eviction request. + // Completion means that the responders has either fully or partially completed the + // eviction process, which may have resulted in target eviction (e.g. pod termination). + // It should reflect the present time when set. + // This field becomes immutable once set. + // +optional + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + CompletionTime *metav1.Time `json:"completionTime,omitempty" protobuf:"bytes,5,opt,name=completionTime"` + + // message provides human-readable details about the state of the responder and the eviction + // process. + // Maximum length is 4000 characters. + // +optional + // +k8s:optional + // +k8s:maxLength=4000 + Message *string `json:"message,omitempty" protobuf:"bytes,6,opt,name=message"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// EvictionList contains a list of Eviction resources. +type EvictionList struct { + metav1.TypeMeta `json:",inline"` + // metadata is the standard list metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // items is the list of Evictions. + Items []Eviction `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types_swagger_doc_generated.go new file mode 100644 index 000000000..3646f8434 --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/types_swagger_doc_generated.go @@ -0,0 +1,188 @@ +/* +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 v1alpha1 + +// This file contains a collection of methods that can be used from go-restful to +// generate Swagger API documentation for its models. Please read this PR for more +// information on the implementation: https://github.com/emicklei/go-restful/pull/215 +// +// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if +// they are on one line! For multiple line or blocks that you want to ignore use ---. +// Any context after a --- is ignored. +// +// Those methods can be generated by using hack/update-codegen.sh + +// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. +var map_Eviction = map[string]string{ + "": "Eviction initiates an eviction process, which should ideally result in a graceful eviction of a .spec.target (e.g. termination of a pod).\n\nThe evictionrequest-controller observes intents of all EvictionRequests and transforms them into Evictions. It manages the Eviction lifecycle. Requesters are preserved in .status.requesters even after they have withdrawn their request. If all requesters withdraw their eviction intent for a common target, the eviction will be canceled. Once all EvictionRequest corresponding to this Eviction .spec.target have been removed, this Eviction object will eventually be garbage collected.\n\nIf the target is a pod, the .status.targetResponders is populated from Pod's .spec.evictionResponders.\n\nResponders should observe and communicate through the .status to help with the eviction of the target when they see their state == Active in .status.targetResponders. ResponderStatus struct should then be periodically updated to indicate the progress or completion of the eviction process by each responder in .status.responders. If .status.responders[].heartbeatTime is not updated within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder with a lower priority.\n\nIf there are no other responders and the target is a pod, the last default imperative-eviction.k8s.io/evictor responder with a priority of 100 will evict the pod using the imperative Eviction API (pods//eviction subresource).", + "metadata": "metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. .metadata.name set by the evictionrequest-controller is purely informative and subject to change. .spec.target field should be used to identify the target precisesly.\n\nThe requester and responder names will be used as label keys and added to the labels of the eviction in one of the following formats: 1. acme.io/foo: \"requester\" 2. acme.io/foo: \"responder\" 3. acme.io/foo: \"requester-responder\"\n\nPlease see EvictionParticipantRole for available role label values.", + "spec": "spec defines the eviction specification. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", + "status": "status represents the most recently observed status of the eviction. Populated by responders and evictionrequest-controller. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", +} + +func (Eviction) SwaggerDoc() map[string]string { + return map_Eviction +} + +var map_EvictionList = map[string]string{ + "": "EvictionList contains a list of Eviction resources.", + "metadata": "metadata is the standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "items": "items is the list of Evictions.", +} + +func (EvictionList) SwaggerDoc() map[string]string { + return map_EvictionList +} + +var map_EvictionPodReference = map[string]string{ + "": "EvictionPodReference contains enough information to locate the referenced pod inside the same namespace.", + "name": "name of the target. This field is required.", + "uid": "uid of the target. It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. This field is required.", +} + +func (EvictionPodReference) SwaggerDoc() map[string]string { + return map_EvictionPodReference +} + +var map_EvictionRequest = map[string]string{ + "": "EvictionRequest defines a request that should ideally result in a graceful eviction of a .spec.target (e.g. termination of a pod).\n\nThe evictionrequest-controller observes intents of all EvictionRequests and transforms them into Evictions.\n - .spec.requester is set as a label on the Eviction for easier lookup.\n - Each target can have a set of responders assigned to it. Eviction objects are observed by\n these responders, who implement the eviction logic and update the Eviction's status with\n progress.\n\nThere is many-to-many relationship between EvictionRequests and Evictions in general. And many-to-one if the target is a pod.\n\nIf all requesters withdraw their eviction intent for a common target, the eviction will be canceled. Deleting an EvictionRequest also counts as a withdrawal. Once all EvictionRequest of a target are removed, the corresponding Evictions are eventually garbage collected.", + "metadata": "metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.", + "spec": "spec defines the eviction request specification. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", + "status": "status represents the most recently observed status of the eviction request. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", +} + +func (EvictionRequest) SwaggerDoc() map[string]string { + return map_EvictionRequest +} + +var map_EvictionRequestList = map[string]string{ + "": "EvictionRequestList contains a list of EvictionRequests resources.", + "metadata": "metadata is the standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "items": "items is the list of EvictionRequests.", +} + +func (EvictionRequestList) SwaggerDoc() map[string]string { + return map_EvictionRequestList +} + +var map_EvictionRequestPodReference = map[string]string{ + "": "EvictionRequestPodReference contains enough information to locate the referenced pod inside the same namespace.", + "name": "name of the target. This field is required.", + "uid": "uid of the target. It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. This field is required.", +} + +func (EvictionRequestPodReference) SwaggerDoc() map[string]string { + return map_EvictionRequestPodReference +} + +var map_EvictionRequestSpec = map[string]string{ + "": "EvictionRequestSpec is a specification of an EvictionRequest.", + "target": "target contains a reference to an object (e.g. a pod) that should be evicted. This field is required and immutable.", + "requester": "requester allows you to identify the entity, that requested the eviction of the target.\n\nIt must be a valid domain-prefixed key (such as \"acme.io/foo\"). Domain names *.k8s.io and *.kubernetes.io are reserved. This field is required and immutable.", + "intent": "intent specifies the action that should be taken for the specified target.\n\n- Eviction means that the requester is interested in the eviction of the target. - Withdrawn means that the requester is no longer interested in the eviction of the target.\n If all requesters' intents are withdrawn for a common target, the eviction will be canceled.\n Cancellation consequences:\n - Inactive responders will never run.\n - Active responders are expected to cancel the eviction.\n - Completed or Interrupted responders should not take any action.", +} + +func (EvictionRequestSpec) SwaggerDoc() map[string]string { + return map_EvictionRequestSpec +} + +var map_EvictionRequestStatus = map[string]string{ + "": "EvictionRequestStatus represents the last observed status of the eviction request.", + "conditions": "conditions contain information about the eviction request.\n\nEvictionRequest specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). - Failed means that the eviction request is no longer being processed\n by any eviction responder. This can happen if the request is canceled or if no responder\n managed to evict the target (e.g. terminate or delete a pod).\n- TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted).\n\nThese conditions can be reset if the eviction was unsuccessful and a new Eviction intent has been submitted.\n\nThe maximum length of the conditions list is 100.", + "observedGeneration": "observedGeneration is EvictionRequest's .metadata.generation observed by the evictionrequest-controller. The observed generation value cannot be negative and can only be incremented. The minimum value is 1. This field is managed by evictionrequest-controller.", +} + +func (EvictionRequestStatus) SwaggerDoc() map[string]string { + return map_EvictionRequestStatus +} + +var map_EvictionRequestTarget = map[string]string{ + "": "EvictionRequestTarget contains a reference to an object that should be evicted.", + "pod": "pod references a pod that is subject to eviction/termination. Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported.", +} + +func (EvictionRequestTarget) SwaggerDoc() map[string]string { + return map_EvictionRequestTarget +} + +var map_EvictionSpec = map[string]string{ + "": "EvictionSpec is a specification of an Eviction.", + "target": "target contains a reference to an object (e.g. a pod) that should be evicted. This field is required and immutable.", +} + +func (EvictionSpec) SwaggerDoc() map[string]string { + return map_EvictionSpec +} + +var map_EvictionStatus = map[string]string{ + "": "EvictionStatus represents the last observed status of the eviction request.", + "conditions": "conditions contain information about the eviction request.\n\nEviction specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). - Failed means that the eviction request is no longer being processed\n by any eviction responder. This can happen if the request is canceled or if no responder\n managed to evict the target (e.g. terminate or delete a pod).\n- TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted).\n\n\tThe maximum length of the conditions list is 100.", + "observedGeneration": "observedGeneration is Eviction's .metadata.generation observed by the evictionrequest-controller. The observed generation value cannot be negative and can only be incremented. The minimum value is 1. This field is managed by evictionrequest-controller.", + "requesters": "requesters allow you to identify the entities, that requested the eviction of the target. If all the requesters withdraw their eviction intent, the eviction will be canceled.\n\nThe maximum length of the requesters list is 100. If this limit is exceeded, requesters with Withdrawn intent should be dropped first.", + "targetResponders": "targetResponders reference responders that should eventually respond to this eviction to help with the graceful eviction of a target. These responders are selected sequentially, according to their specified priority by setting the Active state to the TargetResponder .state field. The maximum number of active responders allowed is 1. Eventually each responder can end up in an Interrupted, Canceled or, Completed state. Responders should observe these states in order to navigate their lifecycle.\n\nIf the target is a pod, the field is populated from Pod's .spec.evictionResponders. Default responders may be added to the list according to the target.\n\nDefault responders: - imperative-eviction.k8s.io/evictor responder with a priority of 100 is added to the list if the\n target is a pod. It will call the imperative Eviction API (pods//eviction subresource).\n This call may not succeed due to PodDisruptionBudgets, which may block the pod termination.\n It will update the responder message and try again with a backoff.\n\nThe maximum length of the responders list is 11. The length and keys of the list cannot change once set. This field is managed by evictionrequest-controller.", + "responders": "responders represents the eviction process status of each declared responder.\n\nThe responder list should be the same length and have the same .name fields as .status.targetResponders. Only responders with .name that have Active state in .targetResponders[].state should be updated and can be mutated. First initialization of the list is allowed.\n\nEach ResponderStatus is initialized by evictionrequest-controller and then managed by the designated responder.", +} + +func (EvictionStatus) SwaggerDoc() map[string]string { + return map_EvictionStatus +} + +var map_EvictionTarget = map[string]string{ + "": "EvictionTarget contains a reference to an object that should be evicted.", + "pod": "pod references a pod that is subject to eviction/termination. Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported.", +} + +func (EvictionTarget) SwaggerDoc() map[string]string { + return map_EvictionTarget +} + +var map_Requester = map[string]string{ + "": "Requester allows you to identify the entity, that requested the eviction of the target.", + "name": "name allows you to identify the entity, that requested the eviction of the target.\n\nIt must be a valid domain-prefixed key (such as \"acme.io/foo\"). This field must be unique for each requester. This field is required.", + "intent": "intent specifies the action that should be taken for the specified target.\n\n- Eviction means that the requester is interested in the eviction of the target. - Withdrawn means that the requester is no longer interested in the eviction of the target.\n If all requesters' intents are withdrawn, the eviction will be canceled.\n Cancellation consequences:\n - Inactive responders will never run.\n - Active responders are expected to cancel the eviction.\n - Completed or Interrupted responders should not take any action.", +} + +func (Requester) SwaggerDoc() map[string]string { + return map_Requester +} + +var map_ResponderStatus = map[string]string{ + "": "ResponderStatus represents the last observed status of the eviction process of the responder. It should be only updated by the designated responder whose name is .name field.", + "name": "name allows you to identify the responder reacting to the Eviction.\n\nIt must be a valid domain-prefixed key (such as \"acme.io/foo\"). This field is initialized by Kubernetes and must be unique for each responder. This field is required.", + "startTime": "startTime tracks the time at which this responder was designated as active and should start processing the eviction request. It should reflect the present time when set. This field is initialized by Kubernetes when this responder becomes active. This field becomes immutable once set.", + "heartbeatTime": "heartbeatTime is the last time at which the eviction process was reported to be in progress by the responder. It should reflect the present time when set. Responders should avoid heartbeats more frequent than 20 seconds to avoid overloading the control-plane.", + "expectedCompletionTime": "expectedCompletionTime is the time at which the eviction process step is expected to end for the responder. The time cannot be set to the past. May be omitted if no estimate can be made.", + "completionTime": "completionTime tracks the time at which the Responder stopped processing the eviction request. Completion means that the responders has either fully or partially completed the eviction process, which may have resulted in target eviction (e.g. pod termination). It should reflect the present time when set. This field becomes immutable once set.", + "message": "message provides human-readable details about the state of the responder and the eviction process. Maximum length is 4000 characters.", +} + +func (ResponderStatus) SwaggerDoc() map[string]string { + return map_ResponderStatus +} + +var map_TargetResponder = map[string]string{ + "": "TargetResponder allows you to specify the responder reacting to the Eviction. Responders should observe and communicate through the Eviction API (see .state) to help with the graceful eviction of a target (e.g. termination of a pod).", + "name": "name allows you to identify the responder reacting to the Eviction.\n\nIt must be a valid domain-prefixed key (such as \"acme.io/foo\"). This field must be unique for each responder. This field is required.", + "priority": "priority for this responder. Higher priorities are selected first by the evictionrequest-controller. If there are responders with the same priority, the responder whose domain name comes first in the alphabetical higher domain order, will be picked. This means that the top domain labels are compared alphabetically first, followed by the lower domain labels. The key is compared last.\n\nThe responder that is the managing controller of the pod should set the value of this field to 10000 to allow both for preemption or fallback registration by other responders.\n\nThe minimum value is 0 and the maximum value is 100000. The interval 0-999 is reserved for responders with *.k8s.io suffix. This field is required and immutable.", + "state": "state specifies a state that is assigned by the evictionrequest-controller. Responders should observe this state in order to navigate their lifecycle. - Inactive means that the responder should not yet process this eviction request. - Active means that the responder is either running or expected to start soon.\n Also, startTime has been set in the ResponderStatus by the evictionrequest-controller.\n\n An active responder should currently interact with the eviction process by updating\n .status.responders, where .name is the active responder name. ResponderStatus fields\n should be periodically updated to indicate the progress or completion of the eviction process.\n If .status.responders[].heartbeatTime field is not updated within the heartbeat deadline defined\n by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder\n\t with a lower priority. Only one responder can be active at a time.\n- Interrupted means that the responder has failed to start or failed to update\n heartbeatTime in ResponderStatus in a timely manner.\n- Canceled means that the responder has been canceled. In other words, there\tis no\n EvictionRequest with the same target and Eviction intent in .spec.intent.\n- Completed means that the responder has successfully completed and set completionTime\n in ResponderStatus.\n\nPlease refer to the ResponderStatus in .status.responders for more details on each responder.", +} + +func (TargetResponder) SwaggerDoc() map[string]string { + return map_TargetResponder +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000..1b71bb99f --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,406 @@ +//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 deepcopy-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Eviction) DeepCopyInto(out *Eviction) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Eviction. +func (in *Eviction) DeepCopy() *Eviction { + if in == nil { + return nil + } + out := new(Eviction) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Eviction) 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 *EvictionList) DeepCopyInto(out *EvictionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Eviction, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionList. +func (in *EvictionList) DeepCopy() *EvictionList { + if in == nil { + return nil + } + out := new(EvictionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EvictionList) 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 *EvictionPodReference) DeepCopyInto(out *EvictionPodReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionPodReference. +func (in *EvictionPodReference) DeepCopy() *EvictionPodReference { + if in == nil { + return nil + } + out := new(EvictionPodReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionRequest) DeepCopyInto(out *EvictionRequest) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequest. +func (in *EvictionRequest) DeepCopy() *EvictionRequest { + if in == nil { + return nil + } + out := new(EvictionRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EvictionRequest) 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 *EvictionRequestList) DeepCopyInto(out *EvictionRequestList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]EvictionRequest, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequestList. +func (in *EvictionRequestList) DeepCopy() *EvictionRequestList { + if in == nil { + return nil + } + out := new(EvictionRequestList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EvictionRequestList) 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 *EvictionRequestPodReference) DeepCopyInto(out *EvictionRequestPodReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequestPodReference. +func (in *EvictionRequestPodReference) DeepCopy() *EvictionRequestPodReference { + if in == nil { + return nil + } + out := new(EvictionRequestPodReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionRequestSpec) DeepCopyInto(out *EvictionRequestSpec) { + *out = *in + in.Target.DeepCopyInto(&out.Target) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequestSpec. +func (in *EvictionRequestSpec) DeepCopy() *EvictionRequestSpec { + if in == nil { + return nil + } + out := new(EvictionRequestSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionRequestStatus) DeepCopyInto(out *EvictionRequestStatus) { + *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.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequestStatus. +func (in *EvictionRequestStatus) DeepCopy() *EvictionRequestStatus { + if in == nil { + return nil + } + out := new(EvictionRequestStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionRequestTarget) DeepCopyInto(out *EvictionRequestTarget) { + *out = *in + if in.Pod != nil { + in, out := &in.Pod, &out.Pod + *out = new(EvictionRequestPodReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionRequestTarget. +func (in *EvictionRequestTarget) DeepCopy() *EvictionRequestTarget { + if in == nil { + return nil + } + out := new(EvictionRequestTarget) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionSpec) DeepCopyInto(out *EvictionSpec) { + *out = *in + in.Target.DeepCopyInto(&out.Target) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionSpec. +func (in *EvictionSpec) DeepCopy() *EvictionSpec { + if in == nil { + return nil + } + out := new(EvictionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionStatus) DeepCopyInto(out *EvictionStatus) { + *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.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } + if in.Requesters != nil { + in, out := &in.Requesters, &out.Requesters + *out = make([]Requester, len(*in)) + copy(*out, *in) + } + if in.TargetResponders != nil { + in, out := &in.TargetResponders, &out.TargetResponders + *out = make([]TargetResponder, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Responders != nil { + in, out := &in.Responders, &out.Responders + *out = make([]ResponderStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionStatus. +func (in *EvictionStatus) DeepCopy() *EvictionStatus { + if in == nil { + return nil + } + out := new(EvictionStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EvictionTarget) DeepCopyInto(out *EvictionTarget) { + *out = *in + if in.Pod != nil { + in, out := &in.Pod, &out.Pod + *out = new(EvictionPodReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EvictionTarget. +func (in *EvictionTarget) DeepCopy() *EvictionTarget { + if in == nil { + return nil + } + out := new(EvictionTarget) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Requester) DeepCopyInto(out *Requester) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Requester. +func (in *Requester) DeepCopy() *Requester { + if in == nil { + return nil + } + out := new(Requester) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ResponderStatus) DeepCopyInto(out *ResponderStatus) { + *out = *in + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = (*in).DeepCopy() + } + if in.HeartbeatTime != nil { + in, out := &in.HeartbeatTime, &out.HeartbeatTime + *out = (*in).DeepCopy() + } + if in.ExpectedCompletionTime != nil { + in, out := &in.ExpectedCompletionTime, &out.ExpectedCompletionTime + *out = (*in).DeepCopy() + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = (*in).DeepCopy() + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResponderStatus. +func (in *ResponderStatus) DeepCopy() *ResponderStatus { + if in == nil { + return nil + } + out := new(ResponderStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TargetResponder) DeepCopyInto(out *TargetResponder) { + *out = *in + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TargetResponder. +func (in *TargetResponder) DeepCopy() *TargetResponder { + if in == nil { + return nil + } + out := new(TargetResponder) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.model_name.go new file mode 100644 index 000000000..69d36f25f --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.model_name.go @@ -0,0 +1,97 @@ +//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 v1alpha1 + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in Eviction) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.Eviction" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionList) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionPodReference) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionPodReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequest) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequest" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequestList) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequestList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequestPodReference) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequestPodReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequestSpec) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequestSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequestStatus) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequestStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionRequestTarget) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionRequestTarget" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionSpec) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionStatus) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in EvictionTarget) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.EvictionTarget" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in Requester) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.Requester" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ResponderStatus) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.ResponderStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in TargetResponder) OpenAPIModelName() string { + return "io.k8s.api.lifecycle.v1alpha1.TargetResponder" +} diff --git a/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.prerelease-lifecycle.go new file mode 100644 index 000000000..b4fbbf695 --- /dev/null +++ b/constraint/vendor/k8s.io/api/lifecycle/v1alpha1/zz_generated.prerelease-lifecycle.go @@ -0,0 +1,94 @@ +//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 prerelease-lifecycle-gen. DO NOT EDIT. + +package v1alpha1 + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *Eviction) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *Eviction) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *Eviction) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *EvictionList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *EvictionList) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *EvictionList) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *EvictionRequest) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *EvictionRequest) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *EvictionRequest) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *EvictionRequestList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *EvictionRequestList) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *EvictionRequestList) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} diff --git a/constraint/vendor/k8s.io/api/networking/v1/generated.proto b/constraint/vendor/k8s.io/api/networking/v1/generated.proto index 26dcfdfcc..8394f2dc0 100644 --- a/constraint/vendor/k8s.io/api/networking/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/networking/v1/generated.proto @@ -80,7 +80,7 @@ message HTTPIngressRuleValue { // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 message IPAddress { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -104,11 +104,11 @@ message IPAddressList { // IPAddressSpec describe the attributes in an IP Address. message IPAddressSpec { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional ParentReference parentRef = 1; } @@ -119,7 +119,7 @@ message IPBlock { // cidr is a string representing the IPBlock // Valid examples are "192.168.1.0/24" or "2001:db8::/64" // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string cidr = 1; // except is a slice of CIDRs that should not be included within an IPBlock @@ -134,8 +134,9 @@ message IPBlock { // endpoints defined by a backend. An Ingress can be configured to give services // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. +// +k8s:supportsSubresource="/status" message Ingress { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -172,7 +173,7 @@ message IngressBackend { // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. message IngressClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -204,12 +205,12 @@ message IngressClassParametersReference { // kind is the type of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string kind = 2; // name is the name of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; // scope represents if this refers to a cluster or namespace scoped resource. @@ -238,7 +239,7 @@ message IngressClassSpec { // configuration for the controller. This is optional if the controller does // not require extra parameters. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional IngressClassParametersReference parameters = 2; } @@ -344,6 +345,7 @@ message IngressRule { // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. message IngressRuleValue { + // http is a HTTP IngressRuleValue, which contains a list of http selectors // +optional optional HTTPIngressRuleValue http = 1; } @@ -425,7 +427,7 @@ message IngressTLS { // NetworkPolicy describes what network traffic is allowed for a set of Pods message NetworkPolicy { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -455,7 +457,7 @@ message NetworkPolicyEgressRule { // allows traffic only if the traffic matches at least one item in the to list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyPeer to = 2; } @@ -478,7 +480,7 @@ message NetworkPolicyIngressRule { // allows traffic only if the traffic matches at least one item in the from list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyPeer from = 2; } @@ -517,7 +519,7 @@ message NetworkPolicyPeer { // ipBlock defines policy on a particular IPBlock. If this field is set then // neither of the other fields can be. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional IPBlock ipBlock = 3; } @@ -563,7 +565,7 @@ message NetworkPolicySpec { // solely to ensure that the pods it selects are isolated by default) // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyIngressRule ingress = 2; // egress is a list of egress rules to be applied to the selected pods. Outgoing traffic @@ -575,7 +577,7 @@ message NetworkPolicySpec { // This field is beta-level in 1.8 // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated NetworkPolicyEgressRule egress = 3; // policyTypes is a list of rule types that the NetworkPolicy relates to. @@ -595,22 +597,22 @@ message NetworkPolicySpec { // ParentReference describes a reference to a parent object. message ParentReference { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. // +optional optional string group = 1; - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string resource = 2; - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. // +optional optional string namespace = 3; - // Name is the name of the object being referenced. + // name is the name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 4; } @@ -630,8 +632,9 @@ message ServiceBackendPort { // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. +// +k8s:supportsSubresource="/status" message ServiceCIDR { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -660,7 +663,7 @@ message ServiceCIDRList { // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. message ServiceCIDRSpec { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. // +optional @@ -677,6 +680,7 @@ message ServiceCIDRStatus { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; } diff --git a/constraint/vendor/k8s.io/api/networking/v1/types.go b/constraint/vendor/k8s.io/api/networking/v1/types.go index a0e737ee1..b455b46c3 100644 --- a/constraint/vendor/k8s.io/api/networking/v1/types.go +++ b/constraint/vendor/k8s.io/api/networking/v1/types.go @@ -28,9 +28,9 @@ import ( // NetworkPolicy describes what network traffic is allowed for a set of Pods type NetworkPolicy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -77,7 +77,7 @@ type NetworkPolicySpec struct { // solely to ensure that the pods it selects are isolated by default) // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"` // egress is a list of egress rules to be applied to the selected pods. Outgoing traffic @@ -89,7 +89,7 @@ type NetworkPolicySpec struct { // This field is beta-level in 1.8 // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Egress []NetworkPolicyEgressRule `json:"egress,omitempty" protobuf:"bytes,3,rep,name=egress"` // policyTypes is a list of rule types that the NetworkPolicy relates to. @@ -126,7 +126,7 @@ type NetworkPolicyIngressRule struct { // allows traffic only if the traffic matches at least one item in the from list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"` } @@ -150,7 +150,7 @@ type NetworkPolicyEgressRule struct { // allows traffic only if the traffic matches at least one item in the to list. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional To []NetworkPolicyPeer `json:"to,omitempty" protobuf:"bytes,2,rep,name=to"` } @@ -183,7 +183,7 @@ type IPBlock struct { // cidr is a string representing the IPBlock // Valid examples are "192.168.1.0/24" or "2001:db8::/64" // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required CIDR string `json:"cidr" protobuf:"bytes,1,name=cidr"` // except is a slice of CIDRs that should not be included within an IPBlock @@ -218,7 +218,7 @@ type NetworkPolicyPeer struct { // ipBlock defines policy on a particular IPBlock. If this field is set then // neither of the other fields can be. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional IPBlock *IPBlock `json:"ipBlock,omitempty" protobuf:"bytes,3,rep,name=ipBlock"` } @@ -227,7 +227,7 @@ type NetworkPolicyPeer struct { // NetworkPolicyList is a list of NetworkPolicy objects. type NetworkPolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -246,10 +246,11 @@ type NetworkPolicyList struct { // endpoints defined by a backend. An Ingress can be configured to give services // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. +// +k8s:supportsSubresource="/status" type Ingress struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -270,7 +271,7 @@ type Ingress struct { // IngressList is a collection of Ingress. type IngressList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -427,7 +428,7 @@ type IngressRule struct { // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. // +optional - IngressRuleValue `json:",inline" protobuf:"bytes,2,opt,name=ingressRuleValue"` + IngressRuleValue `json:"" protobuf:"bytes,2,opt,name=ingressRuleValue"` } // IngressRuleValue represents a rule to apply against incoming requests. If the @@ -435,6 +436,7 @@ type IngressRule struct { // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. type IngressRuleValue struct { + // http is a HTTP IngressRuleValue, which contains a list of http selectors // +optional HTTP *HTTPIngressRuleValue `json:"http,omitempty" protobuf:"bytes,1,opt,name=http"` } @@ -563,9 +565,9 @@ type ServiceBackendPort struct { // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. type IngressClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -590,7 +592,7 @@ type IngressClassSpec struct { // configuration for the controller. This is optional if the controller does // not require extra parameters. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Parameters *IngressClassParametersReference `json:"parameters,omitempty" protobuf:"bytes,2,opt,name=parameters"` } @@ -614,12 +616,12 @@ type IngressClassParametersReference struct { // kind is the type of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` // name is the name of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` // scope represents if this refers to a cluster or namespace scoped resource. @@ -639,7 +641,7 @@ type IngressClassParametersReference struct { // IngressClassList is a collection of IngressClasses. type IngressClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional @@ -662,8 +664,8 @@ type IngressClassList struct { // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 type IPAddress struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -675,29 +677,29 @@ type IPAddress struct { // IPAddressSpec describe the attributes in an IP Address. type IPAddressSpec struct { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable ParentRef *ParentReference `json:"parentRef,omitempty" protobuf:"bytes,1,opt,name=parentRef"` } // ParentReference describes a reference to a parent object. type ParentReference struct { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. // +optional Group string `json:"group,omitempty" protobuf:"bytes,1,opt,name=group"` - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Resource string `json:"resource,omitempty" protobuf:"bytes,2,opt,name=resource"` - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. // +optional Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"` - // Name is the name of the object being referenced. + // name is the name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name,omitempty" protobuf:"bytes,4,opt,name=name"` } @@ -706,7 +708,7 @@ type ParentReference struct { // IPAddressList contains a list of IPAddress. type IPAddressList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -722,9 +724,10 @@ type IPAddressList struct { // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. +// +k8s:supportsSubresource="/status" type ServiceCIDR struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -740,7 +743,7 @@ type ServiceCIDR struct { // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. type ServiceCIDRSpec struct { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. // +optional @@ -766,6 +769,7 @@ type ServiceCIDRStatus struct { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` } @@ -774,7 +778,7 @@ type ServiceCIDRStatus struct { // ServiceCIDRList contains a list of ServiceCIDR objects. type ServiceCIDRList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/networking/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/networking/v1/types_swagger_doc_generated.go index 6210bb7a5..cb5816b2f 100644 --- a/constraint/vendor/k8s.io/api/networking/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/networking/v1/types_swagger_doc_generated.go @@ -49,7 +49,7 @@ func (HTTPIngressRuleValue) SwaggerDoc() map[string]string { var map_IPAddress = map[string]string{ "": "IPAddress represents a single IP of a single IP Family. The object is designed to be used by APIs that operate on IP addresses. The object is used by the Service core API for allocation of IP addresses. An IP address can be represented in different formats, to guarantee the uniqueness of the IP, the name of the object is the IP address in canonical format, four decimal digits separated by dots suppressing leading zeros for IPv4 and the representation defined by RFC 5952 for IPv6. Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 Invalid: 10.01.2.3 or 2001:db8:0:0:0::1", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the IPAddress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -69,7 +69,7 @@ func (IPAddressList) SwaggerDoc() map[string]string { var map_IPAddressSpec = map[string]string{ "": "IPAddressSpec describe the attributes in an IP Address.", - "parentRef": "ParentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object.", + "parentRef": "parentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object.", } func (IPAddressSpec) SwaggerDoc() map[string]string { @@ -88,7 +88,7 @@ func (IPBlock) SwaggerDoc() map[string]string { var map_Ingress = map[string]string{ "": "Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "status": "status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -109,7 +109,7 @@ func (IngressBackend) SwaggerDoc() map[string]string { var map_IngressClass = map[string]string{ "": "IngressClass represents the class of the Ingress, referenced by the Ingress Spec. The `ingressclass.kubernetes.io/is-default-class` annotation can be used to indicate that an IngressClass should be considered default. When a single IngressClass resource has this annotation set to true, new Ingress resources without a class specified will be assigned this default class.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the IngressClass. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -201,7 +201,8 @@ func (IngressRule) SwaggerDoc() map[string]string { } var map_IngressRuleValue = map[string]string{ - "": "IngressRuleValue represents a rule to apply against incoming requests. If the rule is satisfied, the request is routed to the specified backend. Currently mixing different types of rules in a single Ingress is disallowed, so exactly one of the following must be set.", + "": "IngressRuleValue represents a rule to apply against incoming requests. If the rule is satisfied, the request is routed to the specified backend. Currently mixing different types of rules in a single Ingress is disallowed, so exactly one of the following must be set.", + "http": "http is a HTTP IngressRuleValue, which contains a list of http selectors", } func (IngressRuleValue) SwaggerDoc() map[string]string { @@ -251,7 +252,7 @@ func (IngressTLS) SwaggerDoc() map[string]string { var map_NetworkPolicy = map[string]string{ "": "NetworkPolicy describes what network traffic is allowed for a set of Pods", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents the specification of the desired behavior for this NetworkPolicy.", } @@ -325,10 +326,10 @@ func (NetworkPolicySpec) SwaggerDoc() map[string]string { var map_ParentReference = map[string]string{ "": "ParentReference describes a reference to a parent object.", - "group": "Group is the group of the object being referenced.", - "resource": "Resource is the resource of the object being referenced.", - "namespace": "Namespace is the namespace of the object being referenced.", - "name": "Name is the name of the object being referenced.", + "group": "group is the group of the object being referenced.", + "resource": "resource is the resource of the object being referenced.", + "namespace": "namespace is the namespace of the object being referenced.", + "name": "name is the name of the object being referenced.", } func (ParentReference) SwaggerDoc() map[string]string { @@ -347,7 +348,7 @@ func (ServiceBackendPort) SwaggerDoc() map[string]string { var map_ServiceCIDR = map[string]string{ "": "ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). This range is used to allocate ClusterIPs to Service objects.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "status": "status represents the current state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -368,7 +369,7 @@ func (ServiceCIDRList) SwaggerDoc() map[string]string { var map_ServiceCIDRSpec = map[string]string{ "": "ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services.", - "cidrs": "CIDRs defines the IP blocks in CIDR notation (e.g. \"192.168.0.0/24\" or \"2001:db8::/64\") from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. This field is immutable.", + "cidrs": "cidrs defines the IP blocks in CIDR notation (e.g. \"192.168.0.0/24\" or \"2001:db8::/64\") from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. This field is immutable.", } func (ServiceCIDRSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/networking/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/networking/v1beta1/generated.proto index a6944d603..11e2a0123 100644 --- a/constraint/vendor/k8s.io/api/networking/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/networking/v1beta1/generated.proto @@ -81,7 +81,7 @@ message HTTPIngressRuleValue { // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 message IPAddress { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -105,11 +105,11 @@ message IPAddressList { // IPAddressSpec describe the attributes in an IP Address. message IPAddressSpec { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional ParentReference parentRef = 1; } @@ -117,8 +117,9 @@ message IPAddressSpec { // endpoints defined by a backend. An Ingress can be configured to give services // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. +// +k8s:supportsSubresource="/status" message Ingress { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -157,7 +158,7 @@ message IngressBackend { // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. message IngressClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -189,12 +190,12 @@ message IngressClassParametersReference { // kind is the type of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string kind = 2; // name is the name of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; // scope represents if this refers to a cluster or namespace scoped resource. @@ -222,7 +223,7 @@ message IngressClassSpec { // configuration for the controller. This is optional if the controller does // not require extra parameters. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional IngressClassParametersReference parameters = 2; } @@ -328,6 +329,7 @@ message IngressRule { // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. message IngressRuleValue { + // http is a HTTP IngressRuleValue, which contains a list of http selectors // +optional optional HTTPIngressRuleValue http = 1; } @@ -398,29 +400,30 @@ message IngressTLS { // ParentReference describes a reference to a parent object. message ParentReference { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. // +optional optional string group = 1; - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string resource = 2; - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. // +optional optional string namespace = 3; - // Name is the name of the object being referenced. + // name is the name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 4; } // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. +// +k8s:supportsSubresource="/status" message ServiceCIDR { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -449,7 +452,7 @@ message ServiceCIDRList { // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. message ServiceCIDRSpec { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. // +optional @@ -466,6 +469,7 @@ message ServiceCIDRStatus { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; } diff --git a/constraint/vendor/k8s.io/api/networking/v1beta1/types.go b/constraint/vendor/k8s.io/api/networking/v1beta1/types.go index 7cd9b2b58..73cddf6a7 100644 --- a/constraint/vendor/k8s.io/api/networking/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/networking/v1beta1/types.go @@ -32,10 +32,11 @@ import ( // endpoints defined by a backend. An Ingress can be configured to give services // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. +// +k8s:supportsSubresource="/status" type Ingress struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -58,7 +59,7 @@ type Ingress struct { // IngressList is a collection of Ingress. type IngressList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -218,7 +219,7 @@ type IngressRule struct { // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. // +optional - IngressRuleValue `json:",inline" protobuf:"bytes,2,opt,name=ingressRuleValue"` + IngressRuleValue `json:"" protobuf:"bytes,2,opt,name=ingressRuleValue"` } // IngressRuleValue represents a rule to apply against incoming requests. If the @@ -232,6 +233,7 @@ type IngressRuleValue struct { // 2. Consider adding fields for ingress-type specific global options // usable by a loadbalancer, like http keep-alive. + // http is a HTTP IngressRuleValue, which contains a list of http selectors // +optional HTTP *HTTPIngressRuleValue `json:"http,omitempty" protobuf:"bytes,1,opt,name=http"` } @@ -341,9 +343,9 @@ type IngressBackend struct { // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. type IngressClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -368,7 +370,7 @@ type IngressClassSpec struct { // configuration for the controller. This is optional if the controller does // not require extra parameters. // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Parameters *IngressClassParametersReference `json:"parameters,omitempty" protobuf:"bytes,2,opt,name=parameters"` } @@ -392,12 +394,12 @@ type IngressClassParametersReference struct { // kind is the type of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` // name is the name of resource being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` // scope represents if this refers to a cluster or namespace scoped resource. @@ -418,7 +420,7 @@ type IngressClassParametersReference struct { // IngressClassList is a collection of IngressClasses. type IngressClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -440,8 +442,8 @@ type IngressClassList struct { // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 type IPAddress struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -453,29 +455,29 @@ type IPAddress struct { // IPAddressSpec describe the attributes in an IP Address. type IPAddressSpec struct { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable ParentRef *ParentReference `json:"parentRef,omitempty" protobuf:"bytes,1,opt,name=parentRef"` } // ParentReference describes a reference to a parent object. type ParentReference struct { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. // +optional Group string `json:"group,omitempty" protobuf:"bytes,1,opt,name=group"` - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Resource string `json:"resource,omitempty" protobuf:"bytes,2,opt,name=resource"` - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. // +optional Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"` - // Name is the name of the object being referenced. + // name is the name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name,omitempty" protobuf:"bytes,4,opt,name=name"` } @@ -484,7 +486,7 @@ type ParentReference struct { // IPAddressList contains a list of IPAddress. type IPAddressList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -500,9 +502,10 @@ type IPAddressList struct { // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. +// +k8s:supportsSubresource="/status" type ServiceCIDR struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -518,7 +521,7 @@ type ServiceCIDR struct { // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. type ServiceCIDRSpec struct { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. // +optional @@ -544,6 +547,7 @@ type ServiceCIDRStatus struct { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:opaqueType Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` } @@ -552,7 +556,7 @@ type ServiceCIDRStatus struct { // ServiceCIDRList contains a list of ServiceCIDR objects. type ServiceCIDRList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/networking/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/networking/v1beta1/types_swagger_doc_generated.go index 9d27517f3..03d33b5d4 100644 --- a/constraint/vendor/k8s.io/api/networking/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/networking/v1beta1/types_swagger_doc_generated.go @@ -49,7 +49,7 @@ func (HTTPIngressRuleValue) SwaggerDoc() map[string]string { var map_IPAddress = map[string]string{ "": "IPAddress represents a single IP of a single IP Family. The object is designed to be used by APIs that operate on IP addresses. The object is used by the Service core API for allocation of IP addresses. An IP address can be represented in different formats, to guarantee the uniqueness of the IP, the name of the object is the IP address in canonical format, four decimal digits separated by dots suppressing leading zeros for IPv4 and the representation defined by RFC 5952 for IPv6. Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 Invalid: 10.01.2.3 or 2001:db8:0:0:0::1", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the IPAddress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -69,7 +69,7 @@ func (IPAddressList) SwaggerDoc() map[string]string { var map_IPAddressSpec = map[string]string{ "": "IPAddressSpec describe the attributes in an IP Address.", - "parentRef": "ParentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object.", + "parentRef": "parentRef references the resource that an IPAddress is attached to. An IPAddress must reference a parent object.", } func (IPAddressSpec) SwaggerDoc() map[string]string { @@ -78,7 +78,7 @@ func (IPAddressSpec) SwaggerDoc() map[string]string { var map_Ingress = map[string]string{ "": "Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "status": "status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -100,7 +100,7 @@ func (IngressBackend) SwaggerDoc() map[string]string { var map_IngressClass = map[string]string{ "": "IngressClass represents the class of the Ingress, referenced by the Ingress Spec. The `ingressclass.kubernetes.io/is-default-class` annotation can be used to indicate that an IngressClass should be considered default. When a single IngressClass resource has this annotation set to true, new Ingress resources without a class specified will be assigned this default class.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the IngressClass. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -192,7 +192,8 @@ func (IngressRule) SwaggerDoc() map[string]string { } var map_IngressRuleValue = map[string]string{ - "": "IngressRuleValue represents a rule to apply against incoming requests. If the rule is satisfied, the request is routed to the specified backend. Currently mixing different types of rules in a single Ingress is disallowed, so exactly one of the following must be set.", + "": "IngressRuleValue represents a rule to apply against incoming requests. If the rule is satisfied, the request is routed to the specified backend. Currently mixing different types of rules in a single Ingress is disallowed, so exactly one of the following must be set.", + "http": "http is a HTTP IngressRuleValue, which contains a list of http selectors", } func (IngressRuleValue) SwaggerDoc() map[string]string { @@ -232,10 +233,10 @@ func (IngressTLS) SwaggerDoc() map[string]string { var map_ParentReference = map[string]string{ "": "ParentReference describes a reference to a parent object.", - "group": "Group is the group of the object being referenced.", - "resource": "Resource is the resource of the object being referenced.", - "namespace": "Namespace is the namespace of the object being referenced.", - "name": "Name is the name of the object being referenced.", + "group": "group is the group of the object being referenced.", + "resource": "resource is the resource of the object being referenced.", + "namespace": "namespace is the namespace of the object being referenced.", + "name": "name is the name of the object being referenced.", } func (ParentReference) SwaggerDoc() map[string]string { @@ -244,7 +245,7 @@ func (ParentReference) SwaggerDoc() map[string]string { var map_ServiceCIDR = map[string]string{ "": "ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). This range is used to allocate ClusterIPs to Service objects.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec is the desired state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", "status": "status represents the current state of the ServiceCIDR. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } @@ -265,7 +266,7 @@ func (ServiceCIDRList) SwaggerDoc() map[string]string { var map_ServiceCIDRSpec = map[string]string{ "": "ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services.", - "cidrs": "CIDRs defines the IP blocks in CIDR notation (e.g. \"192.168.0.0/24\" or \"2001:db8::/64\") from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. This field is immutable.", + "cidrs": "cidrs defines the IP blocks in CIDR notation (e.g. \"192.168.0.0/24\" or \"2001:db8::/64\") from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. This field is immutable.", } func (ServiceCIDRSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/node/v1/generated.proto b/constraint/vendor/k8s.io/api/node/v1/generated.proto index 4d77c9b78..f368bd85e 100644 --- a/constraint/vendor/k8s.io/api/node/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/node/v1/generated.proto @@ -45,6 +45,7 @@ message Overhead { // pod. For more details, see // https://kubernetes.io/docs/concepts/containers/runtime-class/ message RuntimeClass { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -60,9 +61,9 @@ message RuntimeClass { // The Handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, // and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required optional string handler = 2; // overhead represents the resource overhead associated with running a pod for a @@ -76,6 +77,7 @@ message RuntimeClass { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional optional Scheduling scheduling = 4; } @@ -107,6 +109,7 @@ message Scheduling { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional repeated .k8s.io.api.core.v1.Toleration tolerations = 2; } diff --git a/constraint/vendor/k8s.io/api/node/v1/types.go b/constraint/vendor/k8s.io/api/node/v1/types.go index c2ea739dc..4d781af2a 100644 --- a/constraint/vendor/k8s.io/api/node/v1/types.go +++ b/constraint/vendor/k8s.io/api/node/v1/types.go @@ -34,8 +34,9 @@ import ( // pod. For more details, see // https://kubernetes.io/docs/concepts/containers/runtime-class/ type RuntimeClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -51,9 +52,9 @@ type RuntimeClass struct { // The Handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, // and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required Handler string `json:"handler" protobuf:"bytes,2,opt,name=handler"` // overhead represents the resource overhead associated with running a pod for a @@ -67,6 +68,7 @@ type RuntimeClass struct { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional Scheduling *Scheduling `json:"scheduling,omitempty" protobuf:"bytes,4,opt,name=scheduling"` } @@ -94,6 +96,7 @@ type Scheduling struct { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,2,rep,name=tolerations"` } @@ -102,7 +105,7 @@ type Scheduling struct { // RuntimeClassList is a list of RuntimeClass objects. type RuntimeClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/node/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/node/v1/types_swagger_doc_generated.go index f5e6b3277..168f48a58 100644 --- a/constraint/vendor/k8s.io/api/node/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/node/v1/types_swagger_doc_generated.go @@ -38,7 +38,7 @@ func (Overhead) SwaggerDoc() map[string]string { var map_RuntimeClass = map[string]string{ "": "RuntimeClass defines a class of container runtime supported in the cluster. The RuntimeClass is used to determine which container runtime is used to run all containers in a pod. RuntimeClasses are manually defined by a user or cluster provisioner, and referenced in the PodSpec. The Kubelet is responsible for resolving the RuntimeClassName reference before running the pod. For more details, see https://kubernetes.io/docs/concepts/containers/runtime-class/", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "handler": "handler specifies the underlying runtime and configuration that the CRI implementation will use to handle pods of this class. The possible values are specific to the node & CRI configuration. It is assumed that all handlers are available on every node, and handlers of the same name are equivalent on every node. For example, a handler called \"runc\" might specify that the runc OCI runtime (using native Linux containers) will be used to run the containers in a pod. The Handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, and is immutable.", "overhead": "overhead represents the resource overhead associated with running a pod for a given RuntimeClass. For more details, see\n https://kubernetes.io/docs/concepts/scheduling-eviction/pod-overhead/", "scheduling": "scheduling holds the scheduling constraints to ensure that pods running with this RuntimeClass are scheduled to nodes that support it. If scheduling is nil, this RuntimeClass is assumed to be supported by all nodes.", diff --git a/constraint/vendor/k8s.io/api/node/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/node/v1alpha1/generated.proto index c50b63906..faf8b8c89 100644 --- a/constraint/vendor/k8s.io/api/node/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/node/v1alpha1/generated.proto @@ -45,6 +45,7 @@ message Overhead { // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class message RuntimeClass { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -82,9 +83,9 @@ message RuntimeClassSpec { // The runtimeHandler must be lowercase, conform to the DNS Label (RFC 1123) // requirements, and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required optional string runtimeHandler = 1; // overhead represents the resource overhead associated with running a pod for a @@ -98,6 +99,7 @@ message RuntimeClassSpec { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional optional Scheduling scheduling = 3; } @@ -118,6 +120,7 @@ message Scheduling { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional repeated .k8s.io.api.core.v1.Toleration tolerations = 2; } diff --git a/constraint/vendor/k8s.io/api/node/v1alpha1/types.go b/constraint/vendor/k8s.io/api/node/v1alpha1/types.go index 3521335b0..16d2794d4 100644 --- a/constraint/vendor/k8s.io/api/node/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/node/v1alpha1/types.go @@ -33,8 +33,9 @@ import ( // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class type RuntimeClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -61,9 +62,9 @@ type RuntimeClassSpec struct { // The runtimeHandler must be lowercase, conform to the DNS Label (RFC 1123) // requirements, and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required RuntimeHandler string `json:"runtimeHandler" protobuf:"bytes,1,opt,name=runtimeHandler"` // overhead represents the resource overhead associated with running a pod for a @@ -77,6 +78,7 @@ type RuntimeClassSpec struct { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional Scheduling *Scheduling `json:"scheduling,omitempty" protobuf:"bytes,3,opt,name=scheduling"` } @@ -104,6 +106,7 @@ type Scheduling struct { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,2,rep,name=tolerations"` } @@ -111,7 +114,7 @@ type Scheduling struct { // RuntimeClassList is a list of RuntimeClass objects. type RuntimeClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/node/v1alpha1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/node/v1alpha1/types_swagger_doc_generated.go index ccc1b7085..5c5438478 100644 --- a/constraint/vendor/k8s.io/api/node/v1alpha1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/node/v1alpha1/types_swagger_doc_generated.go @@ -38,7 +38,7 @@ func (Overhead) SwaggerDoc() map[string]string { var map_RuntimeClass = map[string]string{ "": "RuntimeClass defines a class of container runtime supported in the cluster. The RuntimeClass is used to determine which container runtime is used to run all containers in a pod. RuntimeClasses are (currently) manually defined by a user or cluster provisioner, and referenced in the PodSpec. The Kubelet is responsible for resolving the RuntimeClassName reference before running the pod. For more details, see https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents specification of the RuntimeClass More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", } diff --git a/constraint/vendor/k8s.io/api/node/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/node/v1beta1/generated.proto index 073a185e2..51fbfd5e8 100644 --- a/constraint/vendor/k8s.io/api/node/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/node/v1beta1/generated.proto @@ -45,6 +45,7 @@ message Overhead { // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class message RuntimeClass { + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -60,9 +61,9 @@ message RuntimeClass { // The handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, // and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required optional string handler = 2; // overhead represents the resource overhead associated with running a pod for a @@ -76,6 +77,7 @@ message RuntimeClass { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional optional Scheduling scheduling = 4; } @@ -107,6 +109,7 @@ message Scheduling { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional repeated .k8s.io.api.core.v1.Toleration tolerations = 2; } diff --git a/constraint/vendor/k8s.io/api/node/v1beta1/types.go b/constraint/vendor/k8s.io/api/node/v1beta1/types.go index 145e13866..3af85a9ee 100644 --- a/constraint/vendor/k8s.io/api/node/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/node/v1beta1/types.go @@ -35,8 +35,9 @@ import ( // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class type RuntimeClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -52,9 +53,9 @@ type RuntimeClass struct { // The handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, // and is immutable. // +required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-short-name" - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-short-name" + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required Handler string `json:"handler" protobuf:"bytes,2,opt,name=handler"` // overhead represents the resource overhead associated with running a pod for a @@ -68,6 +69,7 @@ type RuntimeClass struct { // If scheduling is nil, this RuntimeClass is assumed to be supported by all // nodes. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional Scheduling *Scheduling `json:"scheduling,omitempty" protobuf:"bytes,4,opt,name=scheduling"` } @@ -95,6 +97,7 @@ type Scheduling struct { // tolerated by the pod and the RuntimeClass. // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,2,rep,name=tolerations"` } @@ -104,7 +107,7 @@ type Scheduling struct { // RuntimeClassList is a list of RuntimeClass objects. type RuntimeClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/node/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/node/v1beta1/types_swagger_doc_generated.go index 086105ecc..74991a89f 100644 --- a/constraint/vendor/k8s.io/api/node/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/node/v1beta1/types_swagger_doc_generated.go @@ -38,7 +38,7 @@ func (Overhead) SwaggerDoc() map[string]string { var map_RuntimeClass = map[string]string{ "": "RuntimeClass defines a class of container runtime supported in the cluster. The RuntimeClass is used to determine which container runtime is used to run all containers in a pod. RuntimeClasses are (currently) manually defined by a user or cluster provisioner, and referenced in the PodSpec. The Kubelet is responsible for resolving the RuntimeClassName reference before running the pod. For more details, see https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", - "metadata": "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "handler": "handler specifies the underlying runtime and configuration that the CRI implementation will use to handle pods of this class. The possible values are specific to the node & CRI configuration. It is assumed that all handlers are available on every node, and handlers of the same name are equivalent on every node. For example, a handler called \"runc\" might specify that the runc OCI runtime (using native Linux containers) will be used to run the containers in a pod. The handler must be lowercase, conform to the DNS Label (RFC 1123) requirements, and is immutable.", "overhead": "overhead represents the resource overhead associated with running a pod for a given RuntimeClass. For more details, see https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md", "scheduling": "scheduling holds the scheduling constraints to ensure that pods running with this RuntimeClass are scheduled to nodes that support it. If scheduling is nil, this RuntimeClass is assumed to be supported by all nodes.", diff --git a/constraint/vendor/k8s.io/api/policy/v1/generated.proto b/constraint/vendor/k8s.io/api/policy/v1/generated.proto index 704cc10b7..ceec53a11 100644 --- a/constraint/vendor/k8s.io/api/policy/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/policy/v1/generated.proto @@ -33,27 +33,29 @@ option go_package = "k8s.io/api/policy/v1"; // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. message Eviction { - // ObjectMeta describes the pod that is being evicted. + // metadata describes the pod that is being evicted. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // DeleteOptions may be provided + // deleteOptions may be provided // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.DeleteOptions deleteOptions = 2; } // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods +// +k8s:supportsSubresource="/status" message PodDisruptionBudget { - // Standard object's metadata. + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. // +optional optional PodDisruptionBudgetSpec spec = 2; - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. // +optional optional PodDisruptionBudgetStatus status = 3; } @@ -71,14 +73,14 @@ message PodDisruptionBudgetList { // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. message PodDisruptionBudgetSpec { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". // +optional optional .k8s.io.apimachinery.pkg.util.intstr.IntOrString minAvailable = 1; - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector will match no pods, while an empty ({}) selector will select // all pods within the namespace. @@ -86,14 +88,14 @@ message PodDisruptionBudgetSpec { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". // +optional optional .k8s.io.apimachinery.pkg.util.intstr.IntOrString maxUnavailable = 3; - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // @@ -175,6 +177,9 @@ message PodDisruptionBudgetStatus { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 7; } diff --git a/constraint/vendor/k8s.io/api/policy/v1/types.go b/constraint/vendor/k8s.io/api/policy/v1/types.go index ebf349e31..1d49f92d1 100644 --- a/constraint/vendor/k8s.io/api/policy/v1/types.go +++ b/constraint/vendor/k8s.io/api/policy/v1/types.go @@ -26,14 +26,14 @@ const DisruptionBudgetCause metav1.CauseType = "DisruptionBudget" // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. type PodDisruptionBudgetSpec struct { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". // +optional MinAvailable *intstr.IntOrString `json:"minAvailable,omitempty" protobuf:"bytes,1,opt,name=minAvailable"` - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector will match no pods, while an empty ({}) selector will select // all pods within the namespace. @@ -41,14 +41,14 @@ type PodDisruptionBudgetSpec struct { // +optional Selector *metav1.LabelSelector `json:"selector,omitempty" patchStrategy:"replace" protobuf:"bytes,2,opt,name=selector"` - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". // +optional MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"bytes,3,opt,name=maxUnavailable"` - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // @@ -150,6 +150,9 @@ type PodDisruptionBudgetStatus struct { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,7,rep,name=conditions"` } @@ -174,17 +177,18 @@ const ( // +k8s:prerelease-lifecycle-gen:introduced=1.21 // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods +// +k8s:supportsSubresource="/status" type PodDisruptionBudget struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // 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" protobuf:"bytes,1,opt,name=metadata"` - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. // +optional Spec PodDisruptionBudgetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. // +optional Status PodDisruptionBudgetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -194,7 +198,7 @@ type PodDisruptionBudget struct { // PodDisruptionBudgetList is a collection of PodDisruptionBudgets. type PodDisruptionBudgetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -212,13 +216,14 @@ type PodDisruptionBudgetList struct { // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. type Eviction struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // ObjectMeta describes the pod that is being evicted. + // metadata describes the pod that is being evicted. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // DeleteOptions may be provided + // deleteOptions may be provided // +optional DeleteOptions *metav1.DeleteOptions `json:"deleteOptions,omitempty" protobuf:"bytes,2,opt,name=deleteOptions"` } diff --git a/constraint/vendor/k8s.io/api/policy/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/policy/v1/types_swagger_doc_generated.go index 9b2f5b945..cf67a76df 100644 --- a/constraint/vendor/k8s.io/api/policy/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/policy/v1/types_swagger_doc_generated.go @@ -29,8 +29,8 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Eviction = map[string]string{ "": "Eviction evicts a pod from its node subject to certain policies and safety constraints. This is a subresource of Pod. A request to cause such an eviction is created by POSTing to .../pods//evictions.", - "metadata": "ObjectMeta describes the pod that is being evicted.", - "deleteOptions": "DeleteOptions may be provided", + "metadata": "metadata describes the pod that is being evicted.", + "deleteOptions": "deleteOptions may be provided", } func (Eviction) SwaggerDoc() map[string]string { @@ -39,9 +39,9 @@ func (Eviction) SwaggerDoc() map[string]string { var map_PodDisruptionBudget = map[string]string{ "": "PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "spec": "Specification of the desired behavior of the PodDisruptionBudget.", - "status": "Most recently observed status of the PodDisruptionBudget.", + "metadata": "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec is the specification of the desired behavior of the PodDisruptionBudget.", + "status": "status is the most recently observed status of the PodDisruptionBudget.", } func (PodDisruptionBudget) SwaggerDoc() map[string]string { @@ -60,10 +60,10 @@ func (PodDisruptionBudgetList) SwaggerDoc() map[string]string { var map_PodDisruptionBudgetSpec = map[string]string{ "": "PodDisruptionBudgetSpec is a description of a PodDisruptionBudget.", - "minAvailable": "An eviction is allowed if at least \"minAvailable\" pods selected by \"selector\" will still be available after the eviction, i.e. even in the absence of the evicted pod. So for example you can prevent all voluntary evictions by specifying \"100%\".", - "selector": "Label query over pods whose evictions are managed by the disruption budget. A null selector will match no pods, while an empty ({}) selector will select all pods within the namespace.", - "maxUnavailable": "An eviction is allowed if at most \"maxUnavailable\" pods selected by \"selector\" are unavailable after the eviction, i.e. even in absence of the evicted pod. For example, one can prevent all voluntary evictions by specifying 0. This is a mutually exclusive setting with \"minAvailable\".", - "unhealthyPodEvictionPolicy": "UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.", + "minAvailable": "minAvailable indicates that an eviction is allowed if at least \"minAvailable\" pods selected by \"selector\" will still be available after the eviction, i.e. even in the absence of the evicted pod. So for example you can prevent all voluntary evictions by specifying \"100%\".", + "selector": "selector is a label query over pods whose evictions are managed by the disruption budget. A null selector will match no pods, while an empty ({}) selector will select all pods within the namespace.", + "maxUnavailable": "maxUnavailable indicates that an eviction is allowed if at most \"maxUnavailable\" pods selected by \"selector\" are unavailable after the eviction, i.e. even in absence of the evicted pod. For example, one can prevent all voluntary evictions by specifying 0. This is a mutually exclusive setting with \"minAvailable\".", + "unhealthyPodEvictionPolicy": "unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.", } func (PodDisruptionBudgetSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/policy/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/policy/v1beta1/generated.proto index a8200a2d7..be469ba61 100644 --- a/constraint/vendor/k8s.io/api/policy/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/policy/v1beta1/generated.proto @@ -33,27 +33,29 @@ option go_package = "k8s.io/api/policy/v1beta1"; // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. message Eviction { - // ObjectMeta describes the pod that is being evicted. + // metadata describes the pod that is being evicted. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // DeleteOptions may be provided + // deleteOptions may be provided // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.DeleteOptions deleteOptions = 2; } // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods +// +k8s:supportsSubresource="/status" message PodDisruptionBudget { - // Standard object's metadata. + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. // +optional optional PodDisruptionBudgetSpec spec = 2; - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. // +optional optional PodDisruptionBudgetStatus status = 3; } @@ -71,14 +73,14 @@ message PodDisruptionBudgetList { // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. message PodDisruptionBudgetSpec { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". // +optional optional .k8s.io.apimachinery.pkg.util.intstr.IntOrString minAvailable = 1; - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector selects no pods. // An empty selector ({}) also selects no pods, which differs from standard behavior of selecting all pods. @@ -86,14 +88,14 @@ message PodDisruptionBudgetSpec { // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 2; - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". // +optional optional .k8s.io.apimachinery.pkg.util.intstr.IntOrString maxUnavailable = 3; - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // @@ -175,6 +177,9 @@ message PodDisruptionBudgetStatus { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 7; } diff --git a/constraint/vendor/k8s.io/api/policy/v1beta1/types.go b/constraint/vendor/k8s.io/api/policy/v1beta1/types.go index 354c22a3d..6017d4179 100644 --- a/constraint/vendor/k8s.io/api/policy/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/policy/v1beta1/types.go @@ -23,14 +23,14 @@ import ( // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. type PodDisruptionBudgetSpec struct { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". // +optional MinAvailable *intstr.IntOrString `json:"minAvailable,omitempty" protobuf:"bytes,1,opt,name=minAvailable"` - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector selects no pods. // An empty selector ({}) also selects no pods, which differs from standard behavior of selecting all pods. @@ -38,14 +38,14 @@ type PodDisruptionBudgetSpec struct { // +optional Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". // +optional MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"bytes,3,opt,name=maxUnavailable"` - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // @@ -147,6 +147,9 @@ type PodDisruptionBudgetStatus struct { // +patchStrategy=merge // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,7,rep,name=conditions"` } @@ -174,18 +177,19 @@ const ( // +k8s:prerelease-lifecycle-gen:replacement=policy,v1,PodDisruptionBudget // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods +// +k8s:supportsSubresource="/status" type PodDisruptionBudget struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // 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" protobuf:"bytes,1,opt,name=metadata"` - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. // +optional Spec PodDisruptionBudgetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. // +optional Status PodDisruptionBudgetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -198,7 +202,7 @@ type PodDisruptionBudget struct { // PodDisruptionBudgetList is a collection of PodDisruptionBudgets. type PodDisruptionBudgetList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -218,13 +222,14 @@ type PodDisruptionBudgetList struct { // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. type Eviction struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // ObjectMeta describes the pod that is being evicted. + // metadata describes the pod that is being evicted. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // DeleteOptions may be provided + // deleteOptions may be provided // +optional DeleteOptions *metav1.DeleteOptions `json:"deleteOptions,omitempty" protobuf:"bytes,2,opt,name=deleteOptions"` } diff --git a/constraint/vendor/k8s.io/api/policy/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/policy/v1beta1/types_swagger_doc_generated.go index cffc9a548..cffdcdd42 100644 --- a/constraint/vendor/k8s.io/api/policy/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/policy/v1beta1/types_swagger_doc_generated.go @@ -29,8 +29,8 @@ package v1beta1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_Eviction = map[string]string{ "": "Eviction evicts a pod from its node subject to certain policies and safety constraints. This is a subresource of Pod. A request to cause such an eviction is created by POSTing to .../pods//evictions.", - "metadata": "ObjectMeta describes the pod that is being evicted.", - "deleteOptions": "DeleteOptions may be provided", + "metadata": "metadata describes the pod that is being evicted.", + "deleteOptions": "deleteOptions may be provided", } func (Eviction) SwaggerDoc() map[string]string { @@ -39,9 +39,9 @@ func (Eviction) SwaggerDoc() map[string]string { var map_PodDisruptionBudget = map[string]string{ "": "PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "spec": "Specification of the desired behavior of the PodDisruptionBudget.", - "status": "Most recently observed status of the PodDisruptionBudget.", + "metadata": "metadata is the standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec is the specification of the desired behavior of the PodDisruptionBudget.", + "status": "status is the most recently observed status of the PodDisruptionBudget.", } func (PodDisruptionBudget) SwaggerDoc() map[string]string { @@ -60,10 +60,10 @@ func (PodDisruptionBudgetList) SwaggerDoc() map[string]string { var map_PodDisruptionBudgetSpec = map[string]string{ "": "PodDisruptionBudgetSpec is a description of a PodDisruptionBudget.", - "minAvailable": "An eviction is allowed if at least \"minAvailable\" pods selected by \"selector\" will still be available after the eviction, i.e. even in the absence of the evicted pod. So for example you can prevent all voluntary evictions by specifying \"100%\".", - "selector": "Label query over pods whose evictions are managed by the disruption budget. A null selector selects no pods. An empty selector ({}) also selects no pods, which differs from standard behavior of selecting all pods. In policy/v1, an empty selector will select all pods in the namespace.", - "maxUnavailable": "An eviction is allowed if at most \"maxUnavailable\" pods selected by \"selector\" are unavailable after the eviction, i.e. even in absence of the evicted pod. For example, one can prevent all voluntary evictions by specifying 0. This is a mutually exclusive setting with \"minAvailable\".", - "unhealthyPodEvictionPolicy": "UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.", + "minAvailable": "minAvailable indicates that an eviction is allowed if at least \"minAvailable\" pods selected by \"selector\" will still be available after the eviction, i.e. even in the absence of the evicted pod. So for example you can prevent all voluntary evictions by specifying \"100%\".", + "selector": "selector is a label query over pods whose evictions are managed by the disruption budget. A null selector selects no pods. An empty selector ({}) also selects no pods, which differs from standard behavior of selecting all pods. In policy/v1, an empty selector will select all pods in the namespace.", + "maxUnavailable": "maxUnavailable indicates that an eviction is allowed if at most \"maxUnavailable\" pods selected by \"selector\" are unavailable after the eviction, i.e. even in absence of the evicted pod. For example, one can prevent all voluntary evictions by specifying 0. This is a mutually exclusive setting with \"minAvailable\".", + "unhealthyPodEvictionPolicy": "unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods should be considered for eviction. Current implementation considers healthy pods, as pods that have status.conditions item with type=\"Ready\",status=\"True\".\n\nValid policies are IfHealthyBudget and AlwaysAllow. If no policy is specified, the default behavior will be used, which corresponds to the IfHealthyBudget policy.\n\nIfHealthyBudget policy means that running pods (status.phase=\"Running\"), but not yet healthy can be evicted only if the guarded application is not disrupted (status.currentHealthy is at least equal to status.desiredHealthy). Healthy pods will be subject to the PDB for eviction.\n\nAlwaysAllow policy means that all running pods (status.phase=\"Running\"), but not yet healthy are considered disrupted and can be evicted regardless of whether the criteria in a PDB is met. This means perspective running pods of a disrupted application might not get a chance to become healthy. Healthy pods will be subject to the PDB for eviction.\n\nAdditional policies may be added in the future. Clients making eviction decisions should disallow eviction of unhealthy pods if they encounter an unrecognized policy in this field.", } func (PodDisruptionBudgetSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/rbac/v1/generated.proto b/constraint/vendor/k8s.io/api/rbac/v1/generated.proto index 7b4ec2afc..9a2489b7a 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/rbac/v1/generated.proto @@ -30,7 +30,7 @@ option go_package = "k8s.io/api/rbac/v1"; // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole message AggregationRule { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -39,17 +39,17 @@ message AggregationRule { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. message ClusterRole { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -59,20 +59,21 @@ message ClusterRole { // ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, // and adds who information via Subject. message ClusterRoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -99,29 +100,29 @@ message ClusterRoleList { // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. message PolicyRule { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string verbs = 1; - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic repeated string apiGroups = 2; - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. // +optional // +listType=atomic repeated string resources = 3; - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic repeated string resourceNames = 4; - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -131,14 +132,14 @@ message PolicyRule { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. message Role { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; } @@ -146,20 +147,21 @@ message Role { // It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given // namespace only have effect in that namespace. message RoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -186,17 +188,17 @@ message RoleList { // RoleRef contains information that points to the role being used // +structType=atomic message RoleRef { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional optional string apiGroup = 1; - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required optional string kind = 2; - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; } @@ -204,23 +206,23 @@ message RoleRef { // or a value for non-objects such as user and group names. // +structType=atomic message Subject { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required optional string kind = 1; - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. // +optional optional string apiGroup = 2; - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional optional string namespace = 4; diff --git a/constraint/vendor/k8s.io/api/rbac/v1/types.go b/constraint/vendor/k8s.io/api/rbac/v1/types.go index d3bb6d1a9..a1e96067e 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1/types.go +++ b/constraint/vendor/k8s.io/api/rbac/v1/types.go @@ -47,27 +47,27 @@ const ( // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRule struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,2,rep,name=apiGroups"` - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. // +optional // +listType=atomic Resources []string `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,4,rep,name=resourceNames"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -79,20 +79,20 @@ type PolicyRule struct { // or a value for non-objects such as user and group names. // +structType=atomic type Subject struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. // +optional APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,2,opt,name=apiGroup"` - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional Namespace string `json:"namespace,omitempty" protobuf:"bytes,4,opt,name=namespace"` @@ -101,15 +101,15 @@ type Subject struct { // RoleRef contains information that points to the role being used // +structType=atomic type RoleRef struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional APIGroup string `json:"apiGroup" protobuf:"bytes,1,opt,name=apiGroup"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` } @@ -119,15 +119,15 @@ type RoleRef struct { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. type Role struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` } @@ -139,21 +139,22 @@ type Role struct { // It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given // namespace only have effect in that namespace. type RoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -162,7 +163,7 @@ type RoleBinding struct { // RoleBindingList is a collection of RoleBindings type RoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -176,7 +177,7 @@ type RoleBindingList struct { // RoleList is a collection of Roles type RoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -192,18 +193,18 @@ type RoleList struct { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. type ClusterRole struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -212,7 +213,7 @@ type ClusterRole struct { // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRule struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -227,21 +228,22 @@ type AggregationRule struct { // ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, // and adds who information via Subject. type ClusterRoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -250,7 +252,7 @@ type ClusterRoleBinding struct { // ClusterRoleBindingList is a collection of ClusterRoleBindings type ClusterRoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -264,7 +266,7 @@ type ClusterRoleBindingList struct { // ClusterRoleList is a collection of ClusterRoles type ClusterRoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/rbac/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/rbac/v1/types_swagger_doc_generated.go index 0471a5594..7cc6a0e3f 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/rbac/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_AggregationRule = map[string]string{ "": "AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole", - "clusterRoleSelectors": "ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", + "clusterRoleSelectors": "clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", } func (AggregationRule) SwaggerDoc() map[string]string { @@ -38,9 +38,9 @@ func (AggregationRule) SwaggerDoc() map[string]string { var map_ClusterRole = map[string]string{ "": "ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this ClusterRole", - "aggregationRule": "AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this ClusterRole", + "aggregationRule": "aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", } func (ClusterRole) SwaggerDoc() map[string]string { @@ -49,9 +49,9 @@ func (ClusterRole) SwaggerDoc() map[string]string { var map_ClusterRoleBinding = map[string]string{ "": "ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, and adds who information via Subject.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", } func (ClusterRoleBinding) SwaggerDoc() map[string]string { @@ -80,11 +80,11 @@ func (ClusterRoleList) SwaggerDoc() map[string]string { var map_PolicyRule = map[string]string{ "": "PolicyRule holds information that describes a policy rule, but does not contain information about who the rule applies to or which namespace the rule applies to.", - "verbs": "Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", - "apiGroups": "APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", - "resources": "Resources is a list of resources this rule applies to. '*' represents all resources.", - "resourceNames": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - "nonResourceURLs": "NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", + "verbs": "verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", + "apiGroups": "apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", + "resources": "resources is a list of resources this rule applies to. '*' represents all resources.", + "resourceNames": "resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", + "nonResourceURLs": "nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", } func (PolicyRule) SwaggerDoc() map[string]string { @@ -93,8 +93,8 @@ func (PolicyRule) SwaggerDoc() map[string]string { var map_Role = map[string]string{ "": "Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this Role", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this Role", } func (Role) SwaggerDoc() map[string]string { @@ -103,9 +103,9 @@ func (Role) SwaggerDoc() map[string]string { var map_RoleBinding = map[string]string{ "": "RoleBinding references a role, but does not contain it. It can reference a Role in the same namespace or a ClusterRole in the global namespace. It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given namespace only have effect in that namespace.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", } func (RoleBinding) SwaggerDoc() map[string]string { @@ -134,9 +134,9 @@ func (RoleList) SwaggerDoc() map[string]string { var map_RoleRef = map[string]string{ "": "RoleRef contains information that points to the role being used", - "apiGroup": "APIGroup is the group for the resource being referenced", - "kind": "Kind is the type of resource being referenced", - "name": "Name is the name of resource being referenced", + "apiGroup": "apiGroup is the group for the resource being referenced", + "kind": "kind is the type of resource being referenced", + "name": "name is the name of resource being referenced", } func (RoleRef) SwaggerDoc() map[string]string { @@ -145,10 +145,10 @@ func (RoleRef) SwaggerDoc() map[string]string { var map_Subject = map[string]string{ "": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.", - "kind": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", - "apiGroup": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.", - "name": "Name of the object being referenced.", - "namespace": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", + "kind": "kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", + "apiGroup": "apiGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.", + "name": "name of the object being referenced.", + "namespace": "namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", } func (Subject) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/rbac/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/rbac/v1alpha1/generated.proto index 9551d1192..2046778ae 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/rbac/v1alpha1/generated.proto @@ -30,7 +30,7 @@ option go_package = "k8s.io/api/rbac/v1alpha1"; // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole message AggregationRule { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -40,17 +40,17 @@ message AggregationRule { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. message ClusterRole { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -61,19 +61,20 @@ message ClusterRole { // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. message ClusterRoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -102,29 +103,29 @@ message ClusterRoleList { // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. message PolicyRule { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string verbs = 1; - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic repeated string apiGroups = 3; - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. // +optional // +listType=atomic repeated string resources = 4; - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic repeated string resourceNames = 5; - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -135,14 +136,14 @@ message PolicyRule { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. message Role { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; } @@ -151,19 +152,20 @@ message Role { // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. message RoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -191,41 +193,41 @@ message RoleList { // RoleRef contains information that points to the role being used message RoleRef { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional optional string apiGroup = 1; - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required optional string kind = 2; - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; } // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. message Subject { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required optional string kind = 1; - // APIVersion holds the API group and version of the referenced subject. + // apiVersion holds the API group and version of the referenced subject. // Defaults to "v1" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io/v1alpha1" for User and Group subjects. // +k8s:conversion-gen=false // +optional optional string apiVersion = 2; - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional optional string namespace = 4; diff --git a/constraint/vendor/k8s.io/api/rbac/v1alpha1/types.go b/constraint/vendor/k8s.io/api/rbac/v1alpha1/types.go index 4ff4c0601..2f560efb4 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/rbac/v1alpha1/types.go @@ -47,27 +47,27 @@ const ( // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRule struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,3,rep,name=apiGroups"` - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. // +optional // +listType=atomic Resources []string `json:"resources,omitempty" protobuf:"bytes,4,rep,name=resources"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,5,rep,name=resourceNames"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -78,21 +78,21 @@ type PolicyRule struct { // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. type Subject struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` - // APIVersion holds the API group and version of the referenced subject. + // apiVersion holds the API group and version of the referenced subject. // Defaults to "v1" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io/v1alpha1" for User and Group subjects. // +k8s:conversion-gen=false // +optional APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"` - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional Namespace string `json:"namespace,omitempty" protobuf:"bytes,4,opt,name=namespace"` @@ -100,15 +100,15 @@ type Subject struct { // RoleRef contains information that points to the role being used type RoleRef struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional APIGroup string `json:"apiGroup" protobuf:"bytes,1,opt,name=apiGroup"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` } @@ -118,15 +118,15 @@ type RoleRef struct { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. type Role struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` } @@ -138,20 +138,21 @@ type Role struct { // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. type RoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -160,7 +161,7 @@ type RoleBinding struct { // RoleBindingList is a collection of RoleBindings // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBindingList, and will no longer be served in v1.22. type RoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -174,7 +175,7 @@ type RoleBindingList struct { // RoleList is a collection of Roles. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleList, and will no longer be served in v1.22. type RoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -190,18 +191,18 @@ type RoleList struct { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. type ClusterRole struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -210,7 +211,7 @@ type ClusterRole struct { // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRule struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -225,20 +226,21 @@ type AggregationRule struct { // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. type ClusterRoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -247,7 +249,7 @@ type ClusterRoleBinding struct { // ClusterRoleBindingList is a collection of ClusterRoleBindings. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBindings, and will no longer be served in v1.22. type ClusterRoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -261,7 +263,7 @@ type ClusterRoleBindingList struct { // ClusterRoleList is a collection of ClusterRoles. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoles, and will no longer be served in v1.22. type ClusterRoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/rbac/v1alpha1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/rbac/v1alpha1/types_swagger_doc_generated.go index 6708f3e58..03d69326d 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1alpha1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/rbac/v1alpha1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1alpha1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_AggregationRule = map[string]string{ "": "AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole", - "clusterRoleSelectors": "ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", + "clusterRoleSelectors": "clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", } func (AggregationRule) SwaggerDoc() map[string]string { @@ -38,9 +38,9 @@ func (AggregationRule) SwaggerDoc() map[string]string { var map_ClusterRole = map[string]string{ "": "ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this ClusterRole", - "aggregationRule": "AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this ClusterRole", + "aggregationRule": "aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", } func (ClusterRole) SwaggerDoc() map[string]string { @@ -49,9 +49,9 @@ func (ClusterRole) SwaggerDoc() map[string]string { var map_ClusterRoleBinding = map[string]string{ "": "ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, and adds who information via Subject. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", } func (ClusterRoleBinding) SwaggerDoc() map[string]string { @@ -80,11 +80,11 @@ func (ClusterRoleList) SwaggerDoc() map[string]string { var map_PolicyRule = map[string]string{ "": "PolicyRule holds information that describes a policy rule, but does not contain information about who the rule applies to or which namespace the rule applies to.", - "verbs": "Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", - "apiGroups": "APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", - "resources": "Resources is a list of resources this rule applies to. '*' represents all resources.", - "resourceNames": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - "nonResourceURLs": "NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", + "verbs": "verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", + "apiGroups": "apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", + "resources": "resources is a list of resources this rule applies to. '*' represents all resources.", + "resourceNames": "resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", + "nonResourceURLs": "nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", } func (PolicyRule) SwaggerDoc() map[string]string { @@ -93,8 +93,8 @@ func (PolicyRule) SwaggerDoc() map[string]string { var map_Role = map[string]string{ "": "Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this Role", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this Role", } func (Role) SwaggerDoc() map[string]string { @@ -103,9 +103,9 @@ func (Role) SwaggerDoc() map[string]string { var map_RoleBinding = map[string]string{ "": "RoleBinding references a role, but does not contain it. It can reference a Role in the same namespace or a ClusterRole in the global namespace. It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given namespace only have effect in that namespace. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", } func (RoleBinding) SwaggerDoc() map[string]string { @@ -134,9 +134,9 @@ func (RoleList) SwaggerDoc() map[string]string { var map_RoleRef = map[string]string{ "": "RoleRef contains information that points to the role being used", - "apiGroup": "APIGroup is the group for the resource being referenced", - "kind": "Kind is the type of resource being referenced", - "name": "Name is the name of resource being referenced", + "apiGroup": "apiGroup is the group for the resource being referenced", + "kind": "kind is the type of resource being referenced", + "name": "name is the name of resource being referenced", } func (RoleRef) SwaggerDoc() map[string]string { @@ -145,10 +145,10 @@ func (RoleRef) SwaggerDoc() map[string]string { var map_Subject = map[string]string{ "": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.", - "kind": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", - "apiVersion": "APIVersion holds the API group and version of the referenced subject. Defaults to \"v1\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io/v1alpha1\" for User and Group subjects.", - "name": "Name of the object being referenced.", - "namespace": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", + "kind": "kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", + "apiVersion": "apiVersion holds the API group and version of the referenced subject. Defaults to \"v1\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io/v1alpha1\" for User and Group subjects.", + "name": "name of the object being referenced.", + "namespace": "namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", } func (Subject) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/rbac/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/rbac/v1beta1/generated.proto index 326f312ec..d459646be 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/rbac/v1beta1/generated.proto @@ -30,7 +30,7 @@ option go_package = "k8s.io/api/rbac/v1beta1"; // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole message AggregationRule { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -40,17 +40,17 @@ message AggregationRule { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. message ClusterRole { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -61,19 +61,20 @@ message ClusterRole { // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. message ClusterRoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -102,30 +103,30 @@ message ClusterRoleList { // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. message PolicyRule { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required repeated string verbs = 1; - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic repeated string apiGroups = 2; - // Resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. + // resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. // '*/foo' represents the subresource 'foo' for all resources in the specified apiGroups. // +optional // +listType=atomic repeated string resources = 3; - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic repeated string resourceNames = 4; - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -136,14 +137,14 @@ message PolicyRule { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. message Role { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated PolicyRule rules = 2; } @@ -152,19 +153,20 @@ message Role { // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. message RoleBinding { - // Standard object's metadata. + // metadata is the standard object's metadata. // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated Subject subjects = 2; - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable optional RoleRef roleRef = 3; } @@ -192,40 +194,40 @@ message RoleList { // RoleRef contains information that points to the role being used message RoleRef { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional optional string apiGroup = 1; - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required optional string kind = 2; - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; } // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. message Subject { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required optional string kind = 1; - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. // +optional optional string apiGroup = 2; - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string name = 3; - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional optional string namespace = 4; diff --git a/constraint/vendor/k8s.io/api/rbac/v1beta1/types.go b/constraint/vendor/k8s.io/api/rbac/v1beta1/types.go index c653d071f..a635661a8 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/rbac/v1beta1/types.go @@ -47,28 +47,28 @@ const ( // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRule struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. // +listType=atomic // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. // +optional // +listType=atomic APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,2,rep,name=apiGroups"` - // Resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. + // resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. // '*/foo' represents the subresource 'foo' for all resources in the specified apiGroups. // +optional // +listType=atomic Resources []string `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. // +optional // +listType=atomic ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,4,rep,name=resourceNames"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. // +optional @@ -79,20 +79,20 @@ type PolicyRule struct { // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. type Subject struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. // +required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. // +optional APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,2,opt,name=apiGroup"` - // Name of the object being referenced. + // name of the object being referenced. // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. // +optional Namespace string `json:"namespace,omitempty" protobuf:"bytes,4,opt,name=namespace"` @@ -100,15 +100,15 @@ type Subject struct { // RoleRef contains information that points to the role being used type RoleRef struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced // +optional APIGroup string `json:"apiGroup" protobuf:"bytes,1,opt,name=apiGroup"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced // +required Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Name is the name of resource being referenced + // name is the name of resource being referenced // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` } @@ -122,15 +122,15 @@ type RoleRef struct { // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. type Role struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` } @@ -146,20 +146,21 @@ type Role struct { // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. type RoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -172,7 +173,7 @@ type RoleBinding struct { // RoleBindingList is a collection of RoleBindings // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBindingList, and will no longer be served in v1.22. type RoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -190,7 +191,7 @@ type RoleBindingList struct { // RoleList is a collection of Roles // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleList, and will no longer be served in v1.22. type RoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -210,17 +211,17 @@ type RoleList struct { // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. type ClusterRole struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. // +optional @@ -229,7 +230,7 @@ type ClusterRole struct { // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRule struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added // +optional // +listType=atomic @@ -248,20 +249,21 @@ type AggregationRule struct { // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. type ClusterRoleBinding struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object's metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Subjects []Subject `json:"subjects,omitempty" protobuf:"bytes,2,rep,name=subjects"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // +required + // +k8s:alpha(since:"1.37")=+k8s:immutable RoleRef RoleRef `json:"roleRef" protobuf:"bytes,3,opt,name=roleRef"` } @@ -274,7 +276,7 @@ type ClusterRoleBinding struct { // ClusterRoleBindingList is a collection of ClusterRoleBindings. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBindingList, and will no longer be served in v1.22. type ClusterRoleBindingList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -292,7 +294,7 @@ type ClusterRoleBindingList struct { // ClusterRoleList is a collection of ClusterRoles. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoles, and will no longer be served in v1.22. type ClusterRoleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/rbac/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/rbac/v1beta1/types_swagger_doc_generated.go index fff1fe40f..0b03d85e6 100644 --- a/constraint/vendor/k8s.io/api/rbac/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/rbac/v1beta1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1beta1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_AggregationRule = map[string]string{ "": "AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole", - "clusterRoleSelectors": "ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", + "clusterRoleSelectors": "clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", } func (AggregationRule) SwaggerDoc() map[string]string { @@ -38,9 +38,9 @@ func (AggregationRule) SwaggerDoc() map[string]string { var map_ClusterRole = map[string]string{ "": "ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this ClusterRole", - "aggregationRule": "AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this ClusterRole", + "aggregationRule": "aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", } func (ClusterRole) SwaggerDoc() map[string]string { @@ -49,9 +49,9 @@ func (ClusterRole) SwaggerDoc() map[string]string { var map_ClusterRoleBinding = map[string]string{ "": "ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, and adds who information via Subject. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", } func (ClusterRoleBinding) SwaggerDoc() map[string]string { @@ -80,11 +80,11 @@ func (ClusterRoleList) SwaggerDoc() map[string]string { var map_PolicyRule = map[string]string{ "": "PolicyRule holds information that describes a policy rule, but does not contain information about who the rule applies to or which namespace the rule applies to.", - "verbs": "Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", - "apiGroups": "APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", - "resources": "Resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. '*/foo' represents the subresource 'foo' for all resources in the specified apiGroups.", - "resourceNames": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - "nonResourceURLs": "NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", + "verbs": "verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", + "apiGroups": "apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", + "resources": "resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. '*/foo' represents the subresource 'foo' for all resources in the specified apiGroups.", + "resourceNames": "resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", + "nonResourceURLs": "nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", } func (PolicyRule) SwaggerDoc() map[string]string { @@ -93,8 +93,8 @@ func (PolicyRule) SwaggerDoc() map[string]string { var map_Role = map[string]string{ "": "Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "rules": "Rules holds all the PolicyRules for this Role", + "metadata": "metadata is the standard object's metadata.", + "rules": "rules holds all the PolicyRules for this Role", } func (Role) SwaggerDoc() map[string]string { @@ -103,9 +103,9 @@ func (Role) SwaggerDoc() map[string]string { var map_RoleBinding = map[string]string{ "": "RoleBinding references a role, but does not contain it. It can reference a Role in the same namespace or a ClusterRole in the global namespace. It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given namespace only have effect in that namespace. Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22.", - "metadata": "Standard object's metadata.", - "subjects": "Subjects holds references to the objects the role applies to.", - "roleRef": "RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", + "metadata": "metadata is the standard object's metadata.", + "subjects": "subjects holds references to the objects the role applies to.", + "roleRef": "roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error.", } func (RoleBinding) SwaggerDoc() map[string]string { @@ -134,9 +134,9 @@ func (RoleList) SwaggerDoc() map[string]string { var map_RoleRef = map[string]string{ "": "RoleRef contains information that points to the role being used", - "apiGroup": "APIGroup is the group for the resource being referenced", - "kind": "Kind is the type of resource being referenced", - "name": "Name is the name of resource being referenced", + "apiGroup": "apiGroup is the group for the resource being referenced", + "kind": "kind is the type of resource being referenced", + "name": "name is the name of resource being referenced", } func (RoleRef) SwaggerDoc() map[string]string { @@ -145,10 +145,10 @@ func (RoleRef) SwaggerDoc() map[string]string { var map_Subject = map[string]string{ "": "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.", - "kind": "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", - "apiGroup": "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.", - "name": "Name of the object being referenced.", - "namespace": "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", + "kind": "kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", + "apiGroup": "apiGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.", + "name": "name of the object being referenced.", + "namespace": "namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", } func (Subject) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/resource/v1/doc.go b/constraint/vendor/k8s.io/api/resource/v1/doc.go index 645c1cb53..b3a5d93d1 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/doc.go +++ b/constraint/vendor/k8s.io/api/resource/v1/doc.go @@ -20,6 +20,10 @@ limitations under the License. // +k8s:prerelease-lifecycle-gen=true // +k8s:openapi-model-package=io.k8s.api.resource.v1 // +groupName=resource.k8s.io +// +k8s:validation-gen=TypesWithSuffix=DeviceAttribute +// +k8s:validation-gen=TypesWithSuffix=NetworkDeviceData +// +k8s:validation-gen-input=k8s.io/api/resource/v1 +// +k8s:validation-gen-scheme-registry=nil // Package v1 is the v1 version of the resource API. package v1 diff --git a/constraint/vendor/k8s.io/api/resource/v1/generated.pb.go b/constraint/vendor/k8s.io/api/resource/v1/generated.pb.go index f59e82905..c0099e888 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/resource/v1/generated.pb.go @@ -82,6 +82,8 @@ func (m *DeviceConstraint) Reset() { *m = DeviceConstraint{} } func (m *DeviceCounterConsumption) Reset() { *m = DeviceCounterConsumption{} } +func (m *DeviceDerivedAttribute) Reset() { *m = DeviceDerivedAttribute{} } + func (m *DeviceRequest) Reset() { *m = DeviceRequest{} } func (m *DeviceRequestAllocationResult) Reset() { *m = DeviceRequestAllocationResult{} } @@ -92,13 +94,27 @@ func (m *DeviceSubRequest) Reset() { *m = DeviceSubRequest{} } func (m *DeviceTaint) Reset() { *m = DeviceTaint{} } +func (m *DeviceTaintRule) Reset() { *m = DeviceTaintRule{} } + +func (m *DeviceTaintRuleList) Reset() { *m = DeviceTaintRuleList{} } + +func (m *DeviceTaintRuleSpec) Reset() { *m = DeviceTaintRuleSpec{} } + +func (m *DeviceTaintRuleStatus) Reset() { *m = DeviceTaintRuleStatus{} } + +func (m *DeviceTaintSelector) Reset() { *m = DeviceTaintSelector{} } + func (m *DeviceToleration) Reset() { *m = DeviceToleration{} } func (m *ExactDeviceRequest) Reset() { *m = ExactDeviceRequest{} } func (m *NetworkDeviceData) Reset() { *m = NetworkDeviceData{} } -func (m *NodeAllocatableResourceMapping) Reset() { *m = NodeAllocatableResourceMapping{} } +func (m *NodeAllocatableMapping) Reset() { *m = NodeAllocatableMapping{} } + +func (m *NodeAllocatableOverhead) Reset() { *m = NodeAllocatableOverhead{} } + +func (m *NodeAllocatableResource) Reset() { *m = NodeAllocatableResource{} } func (m *OpaqueDeviceConfiguration) Reset() { *m = OpaqueDeviceConfiguration{} } @@ -576,14 +592,14 @@ func (m *Device) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.NodeAllocatableResourceMappings) > 0 { - keysForNodeAllocatableResourceMappings := make([]string, 0, len(m.NodeAllocatableResourceMappings)) - for k := range m.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) - } - sort.Strings(keysForNodeAllocatableResourceMappings) - for iNdEx := len(keysForNodeAllocatableResourceMappings) - 1; iNdEx >= 0; iNdEx-- { - v := m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResourceMappings[iNdEx])] + if len(m.NodeAllocatableResources) > 0 { + keysForNodeAllocatableResources := make([]string, 0, len(m.NodeAllocatableResources)) + for k := range m.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) + } + sort.Strings(keysForNodeAllocatableResources) + for iNdEx := len(keysForNodeAllocatableResources) - 1; iNdEx >= 0; iNdEx-- { + v := m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResources[iNdEx])] baseI := i { size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) @@ -595,14 +611,14 @@ func (m *Device) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x12 - i -= len(keysForNodeAllocatableResourceMappings[iNdEx]) - copy(dAtA[i:], keysForNodeAllocatableResourceMappings[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResourceMappings[iNdEx]))) + i -= len(keysForNodeAllocatableResources[iNdEx]) + copy(dAtA[i:], keysForNodeAllocatableResources[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResources[iNdEx]))) i-- dAtA[i] = 0xa i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) i-- - dAtA[i] = 0x6a + dAtA[i] = 0x72 } } if m.AllowMultipleAllocations != nil { @@ -1387,6 +1403,15 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error _ = i var l int _ = l + if len(m.CompatibilityGroups) > 0 { + for iNdEx := len(m.CompatibilityGroups) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.CompatibilityGroups[iNdEx]) + copy(dAtA[i:], m.CompatibilityGroups[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.CompatibilityGroups[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } if len(m.Counters) > 0 { keysForCounters := make([]string, 0, len(m.Counters)) for k := range m.Counters { @@ -1424,6 +1449,39 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error return len(dAtA) - i, nil } +func (m *DeviceDerivedAttribute) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DeviceDerivedAttribute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DeviceDerivedAttribute) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Expression) + copy(dAtA[i:], m.Expression) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Expression))) + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *DeviceRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1498,6 +1556,15 @@ func (m *DeviceRequestAllocationResult) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x5a + } + } if len(m.ConsumedCapacity) > 0 { keysForConsumedCapacity := make([]string, 0, len(m.ConsumedCapacity)) for k := range m.ConsumedCapacity { @@ -1654,6 +1721,20 @@ func (m *DeviceSubRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } if m.Capacity != nil { { size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) @@ -1765,7 +1846,7 @@ func (m *DeviceTaint) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *DeviceToleration) Marshal() (dAtA []byte, err error) { +func (m *DeviceTaintRule) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1775,45 +1856,50 @@ func (m *DeviceToleration) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *DeviceToleration) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceTaintRule) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *DeviceToleration) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceTaintRule) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.TolerationSeconds != nil { - i = encodeVarintGenerated(dAtA, i, uint64(*m.TolerationSeconds)) - i-- - dAtA[i] = 0x28 + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= len(m.Effect) - copy(dAtA[i:], m.Effect) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Effect))) - i-- - dAtA[i] = 0x22 - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Value))) i-- dAtA[i] = 0x1a - i -= len(m.Operator) - copy(dAtA[i:], m.Operator) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Operator))) + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } i-- dAtA[i] = 0x12 - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key))) + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ExactDeviceRequest) Marshal() (dAtA []byte, err error) { +func (m *DeviceTaintRuleList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1823,32 +1909,20 @@ func (m *ExactDeviceRequest) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ExactDeviceRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleList) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ExactDeviceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.Capacity != nil { - { - size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - if len(m.Tolerations) > 0 { - for iNdEx := len(m.Tolerations) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Tolerations[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -1856,50 +1930,23 @@ func (m *ExactDeviceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x32 - } - } - if m.AdminAccess != nil { - i-- - if *m.AdminAccess { - dAtA[i] = 1 - } else { - dAtA[i] = 0 + dAtA[i] = 0x12 } - i-- - dAtA[i] = 0x28 } - i = encodeVarintGenerated(dAtA, i, uint64(m.Count)) - i-- - dAtA[i] = 0x20 - i -= len(m.AllocationMode) - copy(dAtA[i:], m.AllocationMode) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.AllocationMode))) - i-- - dAtA[i] = 0x1a - if len(m.Selectors) > 0 { - for iNdEx := len(m.Selectors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Selectors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= len(m.DeviceClassName) - copy(dAtA[i:], m.DeviceClassName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.DeviceClassName))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *NetworkDeviceData) Marshal() (dAtA []byte, err error) { +func (m *DeviceTaintRuleSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1909,39 +1956,42 @@ func (m *NetworkDeviceData) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *NetworkDeviceData) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleSpec) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *NetworkDeviceData) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i -= len(m.HardwareAddress) - copy(dAtA[i:], m.HardwareAddress) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.HardwareAddress))) - i-- - dAtA[i] = 0x1a - if len(m.IPs) > 0 { - for iNdEx := len(m.IPs) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.IPs[iNdEx]) - copy(dAtA[i:], m.IPs[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.IPs[iNdEx]))) - i-- - dAtA[i] = 0x12 + { + size, err := m.Taint.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= len(m.InterfaceName) - copy(dAtA[i:], m.InterfaceName) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.InterfaceName))) i-- - dAtA[i] = 0xa + dAtA[i] = 0x12 + if m.DeviceSelector != nil { + { + size, err := m.DeviceSelector.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } return len(dAtA) - i, nil } -func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { +func (m *DeviceTaintRuleStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1951,39 +2001,34 @@ func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *NodeAllocatableResourceMapping) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *NodeAllocatableResourceMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceTaintRuleStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.AllocationMultiplier != nil { - { - size, err := m.AllocationMultiplier.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0xa } - i-- - dAtA[i] = 0x12 - } - if m.CapacityKey != nil { - i -= len(*m.CapacityKey) - copy(dAtA[i:], *m.CapacityKey) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.CapacityKey))) - i-- - dAtA[i] = 0xa } return len(dAtA) - i, nil } -func (m *OpaqueDeviceConfiguration) Marshal() (dAtA []byte, err error) { +func (m *DeviceTaintSelector) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1993,35 +2038,41 @@ func (m *OpaqueDeviceConfiguration) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *OpaqueDeviceConfiguration) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceTaintSelector) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *OpaqueDeviceConfiguration) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceTaintSelector) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Parameters.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + if m.Device != nil { + i -= len(*m.Device) + copy(dAtA[i:], *m.Device) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Device))) + i-- + dAtA[i] = 0x22 + } + if m.Pool != nil { + i -= len(*m.Pool) + copy(dAtA[i:], *m.Pool) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Pool))) + i-- + dAtA[i] = 0x1a + } + if m.Driver != nil { + i -= len(*m.Driver) + copy(dAtA[i:], *m.Driver) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.Driver))) + i-- + dAtA[i] = 0x12 } - i-- - dAtA[i] = 0x12 - i -= len(m.Driver) - copy(dAtA[i:], m.Driver) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Driver))) - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaim) Marshal() (dAtA []byte, err error) { +func (m *DeviceToleration) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2031,50 +2082,45 @@ func (m *ResourceClaim) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaim) MarshalTo(dAtA []byte) (int, error) { +func (m *DeviceToleration) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *DeviceToleration) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + if m.TolerationSeconds != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.TolerationSeconds)) + i-- + dAtA[i] = 0x28 } + i -= len(m.Effect) + copy(dAtA[i:], m.Effect) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Effect))) + i-- + dAtA[i] = 0x22 + i -= len(m.Value) + copy(dAtA[i:], m.Value) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Value))) i-- dAtA[i] = 0x1a - { - size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + i -= len(m.Operator) + copy(dAtA[i:], m.Operator) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Operator))) i-- dAtA[i] = 0x12 - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimConsumerReference) Marshal() (dAtA []byte, err error) { +func (m *ExactDeviceRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2084,40 +2130,97 @@ func (m *ResourceClaimConsumerReference) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimConsumerReference) MarshalTo(dAtA []byte) (int, error) { +func (m *ExactDeviceRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimConsumerReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ExactDeviceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i -= len(m.UID) - copy(dAtA[i:], m.UID) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) - i-- - dAtA[i] = 0x2a - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } + if m.Capacity != nil { + { + size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + if len(m.Tolerations) > 0 { + for iNdEx := len(m.Tolerations) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Tolerations[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + } + if m.AdminAccess != nil { + i-- + if *m.AdminAccess { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + i = encodeVarintGenerated(dAtA, i, uint64(m.Count)) i-- - dAtA[i] = 0x22 - i -= len(m.Resource) - copy(dAtA[i:], m.Resource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Resource))) + dAtA[i] = 0x20 + i -= len(m.AllocationMode) + copy(dAtA[i:], m.AllocationMode) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.AllocationMode))) i-- dAtA[i] = 0x1a - i -= len(m.APIGroup) - copy(dAtA[i:], m.APIGroup) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) + if len(m.Selectors) > 0 { + for iNdEx := len(m.Selectors) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Selectors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + i -= len(m.DeviceClassName) + copy(dAtA[i:], m.DeviceClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.DeviceClassName))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimList) Marshal() (dAtA []byte, err error) { +func (m *NetworkDeviceData) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2127,44 +2230,39 @@ func (m *ResourceClaimList) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimList) MarshalTo(dAtA []byte) (int, error) { +func (m *NetworkDeviceData) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimList) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NetworkDeviceData) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + i -= len(m.HardwareAddress) + copy(dAtA[i:], m.HardwareAddress) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.HardwareAddress))) + i-- + dAtA[i] = 0x1a + if len(m.IPs) > 0 { + for iNdEx := len(m.IPs) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.IPs[iNdEx]) + copy(dAtA[i:], m.IPs[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.IPs[iNdEx]))) i-- dAtA[i] = 0x12 } } - { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } + i -= len(m.InterfaceName) + copy(dAtA[i:], m.InterfaceName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.InterfaceName))) i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimSpec) Marshal() (dAtA []byte, err error) { +func (m *NodeAllocatableMapping) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2174,30 +2272,51 @@ func (m *ResourceClaimSpec) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimSpec) MarshalTo(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Devices.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.DeviceMultiplier != nil { + { + size, err := m.DeviceMultiplier.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x1a + } + if m.CapacityMultiplier != nil { + { + size, err := m.CapacityMultiplier.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.CapacityKey != nil { + i -= len(*m.CapacityKey) + copy(dAtA[i:], *m.CapacityKey) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.CapacityKey))) + i-- + dAtA[i] = 0xa } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimStatus) Marshal() (dAtA []byte, err error) { +func (m *NodeAllocatableOverhead) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2207,47 +2326,31 @@ func (m *ResourceClaimStatus) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimStatus) MarshalTo(dAtA []byte) (int, error) { +func (m *NodeAllocatableOverhead) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NodeAllocatableOverhead) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Devices) > 0 { - for iNdEx := len(m.Devices) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Devices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.ReservedFor) > 0 { - for iNdEx := len(m.ReservedFor) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ReservedFor[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + if m.PerContainer != nil { + { + size, err := m.PerContainer.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } - i-- - dAtA[i] = 0x12 + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x12 } - if m.Allocation != nil { + if m.PerPod != nil { { - size, err := m.Allocation.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.PerPod.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2260,7 +2363,7 @@ func (m *ResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *ResourceClaimTemplate) Marshal() (dAtA []byte, err error) { +func (m *NodeAllocatableResource) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2270,40 +2373,44 @@ func (m *ResourceClaimTemplate) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimTemplate) MarshalTo(dAtA []byte) (int, error) { +func (m *NodeAllocatableResource) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NodeAllocatableResource) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.Overhead != nil { + { + size, err := m.Overhead.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x22 } - i-- - dAtA[i] = 0x12 - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.Mapping != nil { + { + size, err := m.Mapping.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x1a } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimTemplateList) Marshal() (dAtA []byte, err error) { +func (m *OpaqueDeviceConfiguration) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2313,32 +2420,18 @@ func (m *ResourceClaimTemplateList) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimTemplateList) MarshalTo(dAtA []byte) (int, error) { +func (m *OpaqueDeviceConfiguration) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimTemplateList) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *OpaqueDeviceConfiguration) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Parameters.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2346,11 +2439,16 @@ func (m *ResourceClaimTemplateList) MarshalToSizedBuffer(dAtA []byte) (int, erro i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- + dAtA[i] = 0x12 + i -= len(m.Driver) + copy(dAtA[i:], m.Driver) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Driver))) + i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceClaimTemplateSpec) Marshal() (dAtA []byte, err error) { +func (m *ResourceClaim) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2360,16 +2458,26 @@ func (m *ResourceClaimTemplateSpec) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceClaimTemplateSpec) MarshalTo(dAtA []byte) (int, error) { +func (m *ResourceClaim) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceClaimTemplateSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a { size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -2393,7 +2501,7 @@ func (m *ResourceClaimTemplateSpec) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } -func (m *ResourcePool) Marshal() (dAtA []byte, err error) { +func (m *ResourceClaimConsumerReference) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2403,31 +2511,40 @@ func (m *ResourcePool) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourcePool) MarshalTo(dAtA []byte) (int, error) { +func (m *ResourceClaimConsumerReference) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourcePool) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResourceClaimConsumerReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - i = encodeVarintGenerated(dAtA, i, uint64(m.ResourceSliceCount)) - i-- - dAtA[i] = 0x18 - i = encodeVarintGenerated(dAtA, i, uint64(m.Generation)) + i -= len(m.UID) + copy(dAtA[i:], m.UID) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) i-- - dAtA[i] = 0x10 + dAtA[i] = 0x2a i -= len(m.Name) copy(dAtA[i:], m.Name) i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i-- + dAtA[i] = 0x22 + i -= len(m.Resource) + copy(dAtA[i:], m.Resource) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Resource))) + i-- + dAtA[i] = 0x1a + i -= len(m.APIGroup) + copy(dAtA[i:], m.APIGroup) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) + i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func (m *ResourceSlice) Marshal() (dAtA []byte, err error) { +func (m *ResourceClaimList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2437,28 +2554,32 @@ func (m *ResourceSlice) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceSlice) MarshalTo(dAtA []byte) (int, error) { +func (m *ResourceClaimList) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceSlice) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResourceClaimList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i-- - dAtA[i] = 0x12 { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2470,7 +2591,7 @@ func (m *ResourceSlice) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *ResourceSliceList) Marshal() (dAtA []byte, err error) { +func (m *ResourceClaimSpec) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2480,32 +2601,18 @@ func (m *ResourceSliceList) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceSliceList) MarshalTo(dAtA []byte) (int, error) { +func (m *ResourceClaimSpec) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceSliceList) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResourceClaimSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Devices.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2517,7 +2624,7 @@ func (m *ResourceSliceList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *ResourceSliceSpec) Marshal() (dAtA []byte, err error) { +func (m *ResourceClaimStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2527,20 +2634,20 @@ func (m *ResourceSliceSpec) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *ResourceSliceSpec) MarshalTo(dAtA []byte) (int, error) { +func (m *ResourceClaimStatus) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *ResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.SharedCounters) > 0 { - for iNdEx := len(m.SharedCounters) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Devices) > 0 { + for iNdEx := len(m.Devices) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.SharedCounters[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Devices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2548,23 +2655,13 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x42 - } - } - if m.PerDeviceNodeSelection != nil { - i-- - if *m.PerDeviceNodeSelection { - dAtA[i] = 1 - } else { - dAtA[i] = 0 + dAtA[i] = 0x22 } - i-- - dAtA[i] = 0x38 } - if len(m.Devices) > 0 { - for iNdEx := len(m.Devices) - 1; iNdEx >= 0; iNdEx-- { + if len(m.ReservedFor) > 0 { + for iNdEx := len(m.ReservedFor) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Devices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.ReservedFor[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2572,22 +2669,12 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x32 - } - } - if m.AllNodes != nil { - i-- - if *m.AllNodes { - dAtA[i] = 1 - } else { - dAtA[i] = 0 + dAtA[i] = 0x12 } - i-- - dAtA[i] = 0x28 } - if m.NodeSelector != nil { + if m.Allocation != nil { { - size, err := m.NodeSelector.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Allocation.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2595,17 +2682,33 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x22 + dAtA[i] = 0xa } - if m.NodeName != nil { - i -= len(*m.NodeName) - copy(dAtA[i:], *m.NodeName) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.NodeName))) - i-- - dAtA[i] = 0x1a + return len(dAtA) - i, nil +} + +func (m *ResourceClaimTemplate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *ResourceClaimTemplate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceClaimTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l { - size, err := m.Pool.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2614,311 +2717,651 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x12 - i -= len(m.Driver) - copy(dAtA[i:], m.Driver) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Driver))) + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } i-- dAtA[i] = 0xa return len(dAtA) - i, nil } -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ +func (m *ResourceClaimTemplateList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *AllocatedDeviceStatus) Size() (n int) { - if m == nil { - return 0 - } + +func (m *ResourceClaimTemplateList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceClaimTemplateList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.Driver) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Pool) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Device) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Conditions) > 0 { - for _, e := range m.Conditions { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 } } - if m.Data != nil { - l = m.Data.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.NetworkData != nil { - l = m.NetworkData.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.ShareID != nil { - l = len(*m.ShareID) - n += 1 + l + sovGenerated(uint64(l)) + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - return n + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *AllocationResult) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Devices.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.NodeSelector != nil { - l = m.NodeSelector.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.AllocationTimestamp != nil { - l = m.AllocationTimestamp.Size() - n += 1 + l + sovGenerated(uint64(l)) +func (m *ResourceClaimTemplateSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - return n + return dAtA[:n], nil } -func (m *CELDeviceSelector) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Expression) - n += 1 + l + sovGenerated(uint64(l)) - return n +func (m *ResourceClaimTemplateSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *CapacityRequestPolicy) Size() (n int) { - if m == nil { - return 0 - } +func (m *ResourceClaimTemplateSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if m.Default != nil { - l = m.Default.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.ValidValues) > 0 { - for _, e := range m.ValidValues { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - if m.ValidRange != nil { - l = m.ValidRange.Size() - n += 1 + l + sovGenerated(uint64(l)) + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - return n + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *CapacityRequestPolicyRange) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Min != nil { - l = m.Min.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Max != nil { - l = m.Max.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Step != nil { - l = m.Step.Size() - n += 1 + l + sovGenerated(uint64(l)) +func (m *ResourcePool) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - return n + return dAtA[:n], nil } -func (m *CapacityRequirements) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Requests) > 0 { - for k, v := range m.Requests { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) - } - } - return n +func (m *ResourcePool) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *Counter) Size() (n int) { - if m == nil { - return 0 - } +func (m *ResourcePool) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.Value.Size() - n += 1 + l + sovGenerated(uint64(l)) - return n + i = encodeVarintGenerated(dAtA, i, uint64(m.ResourceSliceCount)) + i-- + dAtA[i] = 0x18 + i = encodeVarintGenerated(dAtA, i, uint64(m.Generation)) + i-- + dAtA[i] = 0x10 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *CounterSet) Size() (n int) { - if m == nil { - return 0 +func (m *ResourceSlice) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *ResourceSlice) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceSlice) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.Name) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Counters) > 0 { - for k, v := range m.Counters { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - return n + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil } -func (m *Device) Size() (n int) { - if m == nil { - return 0 +func (m *ResourceSliceList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *ResourceSliceList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceSliceList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.Name) - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Attributes) > 0 { - for k, v := range m.Attributes { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 } } - if len(m.Capacity) > 0 { - for k, v := range m.Capacity { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - if len(m.ConsumesCounters) > 0 { - for _, e := range m.ConsumesCounters { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ResourceSliceSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ResourceSliceSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x52 } } - if m.NodeName != nil { - l = len(*m.NodeName) - n += 1 + l + sovGenerated(uint64(l)) + if m.PartitionTypeAttribute != nil { + i -= len(*m.PartitionTypeAttribute) + copy(dAtA[i:], *m.PartitionTypeAttribute) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PartitionTypeAttribute))) + i-- + dAtA[i] = 0x4a } - if m.NodeSelector != nil { - l = m.NodeSelector.Size() - n += 1 + l + sovGenerated(uint64(l)) + if len(m.SharedCounters) > 0 { + for iNdEx := len(m.SharedCounters) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SharedCounters[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } + if m.PerDeviceNodeSelection != nil { + i-- + if *m.PerDeviceNodeSelection { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x38 + } + if len(m.Devices) > 0 { + for iNdEx := len(m.Devices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Devices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } } if m.AllNodes != nil { - n += 2 + i-- + if *m.AllNodes { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 } - if len(m.Taints) > 0 { - for _, e := range m.Taints { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + if m.NodeSelector != nil { + { + size, err := m.NodeSelector.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x22 } - if m.BindsToNode != nil { - n += 2 + if m.NodeName != nil { + i -= len(*m.NodeName) + copy(dAtA[i:], *m.NodeName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.NodeName))) + i-- + dAtA[i] = 0x1a } - if len(m.BindingConditions) > 0 { - for _, s := range m.BindingConditions { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) + { + size, err := m.Pool.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - if len(m.BindingFailureConditions) > 0 { - for _, s := range m.BindingFailureConditions { - l = len(s) + i-- + dAtA[i] = 0x12 + i -= len(m.Driver) + copy(dAtA[i:], m.Driver) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Driver))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AllocatedDeviceStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Driver) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Pool) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Device) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } - if m.AllowMultipleAllocations != nil { - n += 2 + if m.Data != nil { + l = m.Data.Size() + n += 1 + l + sovGenerated(uint64(l)) } - if len(m.NodeAllocatableResourceMappings) > 0 { - for k, v := range m.NodeAllocatableResourceMappings { - _ = k - _ = v - l = v.Size() - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) - } + if m.NetworkData != nil { + l = m.NetworkData.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.ShareID != nil { + l = len(*m.ShareID) + n += 1 + l + sovGenerated(uint64(l)) } return n } -func (m *DeviceAllocationConfiguration) Size() (n int) { +func (m *AllocationResult) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.Source) + l = m.Devices.Size() n += 1 + l + sovGenerated(uint64(l)) - if len(m.Requests) > 0 { - for _, s := range m.Requests { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } + if m.NodeSelector != nil { + l = m.NodeSelector.Size() + n += 1 + l + sovGenerated(uint64(l)) } - l = m.DeviceConfiguration.Size() + if m.AllocationTimestamp != nil { + l = m.AllocationTimestamp.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CELDeviceSelector) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Expression) n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *DeviceAllocationResult) Size() (n int) { +func (m *CapacityRequestPolicy) Size() (n int) { if m == nil { return 0 } var l int _ = l - if len(m.Results) > 0 { - for _, e := range m.Results { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } + if m.Default != nil { + l = m.Default.Size() + n += 1 + l + sovGenerated(uint64(l)) } - if len(m.Config) > 0 { - for _, e := range m.Config { + if len(m.ValidValues) > 0 { + for _, e := range m.ValidValues { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } + if m.ValidRange != nil { + l = m.ValidRange.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } -func (m *DeviceAttribute) Size() (n int) { +func (m *CapacityRequestPolicyRange) Size() (n int) { if m == nil { return 0 } var l int _ = l - if m.IntValue != nil { - n += 1 + sovGenerated(uint64(*m.IntValue)) - } - if m.BoolValue != nil { - n += 2 + if m.Min != nil { + l = m.Min.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Max != nil { + l = m.Max.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Step != nil { + l = m.Step.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CapacityRequirements) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Requests) > 0 { + for k, v := range m.Requests { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + +func (m *Counter) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Value.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *CounterSet) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Counters) > 0 { + for k, v := range m.Counters { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + +func (m *Device) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Attributes) > 0 { + for k, v := range m.Attributes { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + if len(m.Capacity) > 0 { + for k, v := range m.Capacity { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + if len(m.ConsumesCounters) > 0 { + for _, e := range m.ConsumesCounters { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.NodeName != nil { + l = len(*m.NodeName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.NodeSelector != nil { + l = m.NodeSelector.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.AllNodes != nil { + n += 2 + } + if len(m.Taints) > 0 { + for _, e := range m.Taints { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.BindsToNode != nil { + n += 2 + } + if len(m.BindingConditions) > 0 { + for _, s := range m.BindingConditions { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.BindingFailureConditions) > 0 { + for _, s := range m.BindingFailureConditions { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.AllowMultipleAllocations != nil { + n += 2 + } + if len(m.NodeAllocatableResources) > 0 { + for k, v := range m.NodeAllocatableResources { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + l + sovGenerated(uint64(l)) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + +func (m *DeviceAllocationConfiguration) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Source) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Requests) > 0 { + for _, s := range m.Requests { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = m.DeviceConfiguration.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *DeviceAllocationResult) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Results) > 0 { + for _, e := range m.Results { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.Config) > 0 { + for _, e := range m.Config { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DeviceAttribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.IntValue != nil { + n += 1 + sovGenerated(uint64(*m.IntValue)) + } + if m.BoolValue != nil { + n += 2 } if m.StringValue != nil { l = len(*m.StringValue) @@ -3129,6 +3572,25 @@ func (m *DeviceCounterConsumption) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.CompatibilityGroups) > 0 { + for _, s := range m.CompatibilityGroups { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DeviceDerivedAttribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Expression) + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -3201,6 +3663,12 @@ func (m *DeviceRequestAllocationResult) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3246,6 +3714,12 @@ func (m *DeviceSubRequest) Size() (n int) { l = m.Capacity.Size() n += 1 + l + sovGenerated(uint64(l)) } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3268,67 +3742,156 @@ func (m *DeviceTaint) Size() (n int) { return n } -func (m *DeviceToleration) Size() (n int) { +func (m *DeviceTaintRule) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.Key) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Operator) + l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Value) + l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Effect) + l = m.Status.Size() n += 1 + l + sovGenerated(uint64(l)) - if m.TolerationSeconds != nil { - n += 1 + sovGenerated(uint64(*m.TolerationSeconds)) - } return n } -func (m *ExactDeviceRequest) Size() (n int) { +func (m *DeviceTaintRuleList) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.DeviceClassName) + l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) - if len(m.Selectors) > 0 { - for _, e := range m.Selectors { + if len(m.Items) > 0 { + for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } - l = len(m.AllocationMode) - n += 1 + l + sovGenerated(uint64(l)) - n += 1 + sovGenerated(uint64(m.Count)) - if m.AdminAccess != nil { - n += 2 - } - if len(m.Tolerations) > 0 { - for _, e := range m.Tolerations { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) - } + return n +} + +func (m *DeviceTaintRuleSpec) Size() (n int) { + if m == nil { + return 0 } - if m.Capacity != nil { - l = m.Capacity.Size() + var l int + _ = l + if m.DeviceSelector != nil { + l = m.DeviceSelector.Size() n += 1 + l + sovGenerated(uint64(l)) } + l = m.Taint.Size() + n += 1 + l + sovGenerated(uint64(l)) return n } -func (m *NetworkDeviceData) Size() (n int) { +func (m *DeviceTaintRuleStatus) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = len(m.InterfaceName) - n += 1 + l + sovGenerated(uint64(l)) + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DeviceTaintSelector) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Driver != nil { + l = len(*m.Driver) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Pool != nil { + l = len(*m.Pool) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Device != nil { + l = len(*m.Device) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *DeviceToleration) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Operator) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Value) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Effect) + n += 1 + l + sovGenerated(uint64(l)) + if m.TolerationSeconds != nil { + n += 1 + sovGenerated(uint64(*m.TolerationSeconds)) + } + return n +} + +func (m *ExactDeviceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.DeviceClassName) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Selectors) > 0 { + for _, e := range m.Selectors { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = len(m.AllocationMode) + n += 1 + l + sovGenerated(uint64(l)) + n += 1 + sovGenerated(uint64(m.Count)) + if m.AdminAccess != nil { + n += 2 + } + if len(m.Tolerations) > 0 { + for _, e := range m.Tolerations { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.Capacity != nil { + l = m.Capacity.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *NetworkDeviceData) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.InterfaceName) + n += 1 + l + sovGenerated(uint64(l)) if len(m.IPs) > 0 { for _, s := range m.IPs { l = len(s) @@ -3340,7 +3903,7 @@ func (m *NetworkDeviceData) Size() (n int) { return n } -func (m *NodeAllocatableResourceMapping) Size() (n int) { +func (m *NodeAllocatableMapping) Size() (n int) { if m == nil { return 0 } @@ -3350,8 +3913,46 @@ func (m *NodeAllocatableResourceMapping) Size() (n int) { l = len(*m.CapacityKey) n += 1 + l + sovGenerated(uint64(l)) } - if m.AllocationMultiplier != nil { - l = m.AllocationMultiplier.Size() + if m.CapacityMultiplier != nil { + l = m.CapacityMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DeviceMultiplier != nil { + l = m.DeviceMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableOverhead) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PerPod != nil { + l = m.PerPod.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.PerContainer != nil { + l = m.PerContainer.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableResource) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Mapping != nil { + l = m.Mapping.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Overhead != nil { + l = m.Overhead.Size() n += 1 + l + sovGenerated(uint64(l)) } return n @@ -3577,6 +4178,16 @@ func (m *ResourceSliceSpec) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } + if m.PartitionTypeAttribute != nil { + l = len(*m.PartitionTypeAttribute) + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3743,16 +4354,16 @@ func (this *Device) String() string { mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[QualifiedName(k)]) } mapStringForCapacity += "}" - keysForNodeAllocatableResourceMappings := make([]string, 0, len(this.NodeAllocatableResourceMappings)) - for k := range this.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) + keysForNodeAllocatableResources := make([]string, 0, len(this.NodeAllocatableResources)) + for k := range this.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) } - sort.Strings(keysForNodeAllocatableResourceMappings) - mapStringForNodeAllocatableResourceMappings := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping{" - for _, k := range keysForNodeAllocatableResourceMappings { - mapStringForNodeAllocatableResourceMappings += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(k)]) + sort.Strings(keysForNodeAllocatableResources) + mapStringForNodeAllocatableResources := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource{" + for _, k := range keysForNodeAllocatableResources { + mapStringForNodeAllocatableResources += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(k)]) } - mapStringForNodeAllocatableResourceMappings += "}" + mapStringForNodeAllocatableResources += "}" s := strings.Join([]string{`&Device{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `Attributes:` + mapStringForAttributes + `,`, @@ -3766,7 +4377,7 @@ func (this *Device) String() string { `BindingConditions:` + fmt.Sprintf("%v", this.BindingConditions) + `,`, `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `AllowMultipleAllocations:` + valueToStringGenerated(this.AllowMultipleAllocations) + `,`, - `NodeAllocatableResourceMappings:` + mapStringForNodeAllocatableResourceMappings + `,`, + `NodeAllocatableResources:` + mapStringForNodeAllocatableResources + `,`, `}`, }, "") return s @@ -3968,6 +4579,18 @@ func (this *DeviceCounterConsumption) String() string { s := strings.Join([]string{`&DeviceCounterConsumption{`, `CounterSet:` + fmt.Sprintf("%v", this.CounterSet) + `,`, `Counters:` + mapStringForCounters + `,`, + `CompatibilityGroups:` + fmt.Sprintf("%v", this.CompatibilityGroups) + `,`, + `}`, + }, "") + return s +} +func (this *DeviceDerivedAttribute) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceDerivedAttribute{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Expression:` + fmt.Sprintf("%v", this.Expression) + `,`, `}`, }, "") return s @@ -4019,6 +4642,7 @@ func (this *DeviceRequestAllocationResult) String() string { `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `ShareID:` + valueToStringGenerated(this.ShareID) + `,`, `ConsumedCapacity:` + mapStringForConsumedCapacity + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, `}`, }, "") return s @@ -4047,6 +4671,11 @@ func (this *DeviceSubRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&DeviceSubRequest{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, @@ -4055,6 +4684,73 @@ func (this *DeviceSubRequest) String() string { `Count:` + fmt.Sprintf("%v", this.Count) + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, + `}`, + }, "") + return s +} +func (this *DeviceTaintRule) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceTaintRule{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "DeviceTaintRuleSpec", "DeviceTaintRuleSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "DeviceTaintRuleStatus", "DeviceTaintRuleStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeviceTaintRuleList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]DeviceTaintRule{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "DeviceTaintRule", "DeviceTaintRule", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&DeviceTaintRuleList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *DeviceTaintRuleSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceTaintRuleSpec{`, + `DeviceSelector:` + strings.Replace(this.DeviceSelector.String(), "DeviceTaintSelector", "DeviceTaintSelector", 1) + `,`, + `Taint:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Taint), "DeviceTaint", "DeviceTaint", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeviceTaintRuleStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + s := strings.Join([]string{`&DeviceTaintRuleStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `}`, + }, "") + return s +} +func (this *DeviceTaintSelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceTaintSelector{`, + `Driver:` + valueToStringGenerated(this.Driver) + `,`, + `Pool:` + valueToStringGenerated(this.Pool) + `,`, + `Device:` + valueToStringGenerated(this.Device) + `,`, `}`, }, "") return s @@ -4087,6 +4783,11 @@ func (this *ExactDeviceRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&ExactDeviceRequest{`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, `Selectors:` + repeatedStringForSelectors + `,`, @@ -4095,6 +4796,7 @@ func (this *ExactDeviceRequest) String() string { `AdminAccess:` + valueToStringGenerated(this.AdminAccess) + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, `}`, }, "") return s @@ -4111,13 +4813,36 @@ func (this *NetworkDeviceData) String() string { }, "") return s } -func (this *NodeAllocatableResourceMapping) String() string { +func (this *NodeAllocatableMapping) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&NodeAllocatableResourceMapping{`, + s := strings.Join([]string{`&NodeAllocatableMapping{`, `CapacityKey:` + valueToStringGenerated(this.CapacityKey) + `,`, - `AllocationMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.AllocationMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `CapacityMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.CapacityMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `DeviceMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.DeviceMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableOverhead) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableOverhead{`, + `PerPod:` + strings.Replace(fmt.Sprintf("%v", this.PerPod), "Quantity", "resource.Quantity", 1) + `,`, + `PerContainer:` + strings.Replace(fmt.Sprintf("%v", this.PerContainer), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableResource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableResource{`, + `Mapping:` + strings.Replace(this.Mapping.String(), "NodeAllocatableMapping", "NodeAllocatableMapping", 1) + `,`, + `Overhead:` + strings.Replace(this.Overhead.String(), "NodeAllocatableOverhead", "NodeAllocatableOverhead", 1) + `,`, `}`, }, "") return s @@ -4296,29 +5021,867 @@ func (this *ResourceSliceSpec) String() string { for _, f := range this.SharedCounters { repeatedStringForSharedCounters += strings.Replace(strings.Replace(f.String(), "CounterSet", "CounterSet", 1), `&`, ``, 1) + "," } - repeatedStringForSharedCounters += "}" - s := strings.Join([]string{`&ResourceSliceSpec{`, - `Driver:` + fmt.Sprintf("%v", this.Driver) + `,`, - `Pool:` + strings.Replace(strings.Replace(this.Pool.String(), "ResourcePool", "ResourcePool", 1), `&`, ``, 1) + `,`, - `NodeName:` + valueToStringGenerated(this.NodeName) + `,`, - `NodeSelector:` + strings.Replace(fmt.Sprintf("%v", this.NodeSelector), "NodeSelector", "v11.NodeSelector", 1) + `,`, - `AllNodes:` + valueToStringGenerated(this.AllNodes) + `,`, - `Devices:` + repeatedStringForDevices + `,`, - `PerDeviceNodeSelection:` + valueToStringGenerated(this.PerDeviceNodeSelection) + `,`, - `SharedCounters:` + repeatedStringForSharedCounters + `,`, - `}`, - }, "") - return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" + repeatedStringForSharedCounters += "}" + s := strings.Join([]string{`&ResourceSliceSpec{`, + `Driver:` + fmt.Sprintf("%v", this.Driver) + `,`, + `Pool:` + strings.Replace(strings.Replace(this.Pool.String(), "ResourcePool", "ResourcePool", 1), `&`, ``, 1) + `,`, + `NodeName:` + valueToStringGenerated(this.NodeName) + `,`, + `NodeSelector:` + strings.Replace(fmt.Sprintf("%v", this.NodeSelector), "NodeSelector", "v11.NodeSelector", 1) + `,`, + `AllNodes:` + valueToStringGenerated(this.AllNodes) + `,`, + `Devices:` + repeatedStringForDevices + `,`, + `PerDeviceNodeSelection:` + valueToStringGenerated(this.PerDeviceNodeSelection) + `,`, + `SharedCounters:` + repeatedStringForSharedCounters + `,`, + `PartitionTypeAttribute:` + valueToStringGenerated(this.PartitionTypeAttribute) + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllocatedDeviceStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllocatedDeviceStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Driver = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Pool = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Device = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Data == nil { + m.Data = &runtime.RawExtension{} + } + if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NetworkData", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NetworkData == nil { + m.NetworkData = &NetworkDeviceData{} + } + if err := m.NetworkData.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShareID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ShareID = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AllocationResult) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllocationResult: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Devices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Devices.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeSelector", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.NodeSelector == nil { + m.NodeSelector = &v11.NodeSelector{} + } + if err := m.NodeSelector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AllocationTimestamp", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.AllocationTimestamp == nil { + m.AllocationTimestamp = &v1.Time{} + } + if err := m.AllocationTimestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CELDeviceSelector) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CELDeviceSelector: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CELDeviceSelector: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Expression", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Expression = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CapacityRequestPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CapacityRequestPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CapacityRequestPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Default", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Default == nil { + m.Default = &resource.Quantity{} + } + if err := m.Default.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidValues", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidValues = append(m.ValidValues, resource.Quantity{}) + if err := m.ValidValues[len(m.ValidValues)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidRange", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ValidRange == nil { + m.ValidRange = &CapacityRequestPolicyRange{} + } + if err := m.ValidRange.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CapacityRequestPolicyRange) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CapacityRequestPolicyRange: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CapacityRequestPolicyRange: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Min", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Min == nil { + m.Min = &resource.Quantity{} + } + if err := m.Min.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Max == nil { + m.Max = &resource.Quantity{} + } + if err := m.Max.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Step", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Step == nil { + m.Step = &resource.Quantity{} + } + if err := m.Step.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) + return nil } -func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { +func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -4341,17 +5904,17 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: AllocatedDeviceStatus: wiretype end group for non-group") + return fmt.Errorf("proto: CapacityRequirements: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: AllocatedDeviceStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: CapacityRequirements: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -4361,91 +5924,174 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Driver = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) + if m.Requests == nil { + m.Requests = make(map[QualifiedName]resource.Quantity) } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF + var mapkey QualifiedName + mapvalue := &resource.Quantity{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &resource.Quantity{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated + m.Requests[QualifiedName(mapkey)] = *mapvalue + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - postIndex := iNdEx + intStringLen - if postIndex < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } - if postIndex > l { + if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } - m.Pool = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Counter) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - if postIndex > l { + if iNdEx >= l { return io.ErrUnexpectedEOF } - m.Device = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Counter: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Counter: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4472,16 +6118,65 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Conditions = append(m.Conditions, v1.Condition{}) - if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 5: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CounterSet) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CounterSet: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CounterSet: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -4491,31 +6186,27 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Data == nil { - m.Data = &runtime.RawExtension{} - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 6: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NetworkData", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Counters", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4542,45 +6233,105 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.NetworkData == nil { - m.NetworkData = &NetworkDeviceData{} - } - if err := m.NetworkData.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShareID", wireType) + if m.Counters == nil { + m.Counters = make(map[string]Counter) } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF + var mapkey string + mapvalue := &Counter{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &Counter{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - s := string(dAtA[iNdEx:postIndex]) - m.ShareID = &s + m.Counters[mapkey] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -4603,7 +6354,7 @@ func (m *AllocatedDeviceStatus) Unmarshal(dAtA []byte) error { } return nil } -func (m *AllocationResult) Unmarshal(dAtA []byte) error { +func (m *Device) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -4626,50 +6377,17 @@ func (m *AllocationResult) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: AllocationResult: wiretype end group for non-group") + return fmt.Errorf("proto: Device: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: AllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Device: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Devices", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Devices.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeSelector", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -4679,31 +6397,27 @@ func (m *AllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.NodeSelector == nil { - m.NodeSelector = &v11.NodeSelector{} - } - if err := m.NodeSelector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationTimestamp", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4730,148 +6444,109 @@ func (m *AllocationResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.AllocationTimestamp == nil { - m.AllocationTimestamp = &v1.Time{} - } - if err := m.AllocationTimestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CELDeviceSelector) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CELDeviceSelector: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CELDeviceSelector: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Expression", wireType) + if m.Attributes == nil { + m.Attributes = make(map[QualifiedName]DeviceAttribute) } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF + var mapkey QualifiedName + mapvalue := &DeviceAttribute{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &DeviceAttribute{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Expression = string(dAtA[iNdEx:postIndex]) + m.Attributes[QualifiedName(mapkey)] = *mapvalue iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CapacityRequestPolicy) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CapacityRequestPolicy: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CapacityRequestPolicy: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Default", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4898,16 +6573,109 @@ func (m *CapacityRequestPolicy) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Default == nil { - m.Default = &resource.Quantity{} + if m.Capacity == nil { + m.Capacity = make(map[QualifiedName]DeviceCapacity) } - if err := m.Default.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + var mapkey QualifiedName + mapvalue := &DeviceCapacity{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &DeviceCapacity{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } } + m.Capacity[QualifiedName(mapkey)] = *mapvalue iNdEx = postIndex - case 3: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidValues", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumesCounters", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -4934,16 +6702,16 @@ func (m *CapacityRequestPolicy) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ValidValues = append(m.ValidValues, resource.Quantity{}) - if err := m.ValidValues[len(m.ValidValues)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.ConsumesCounters = append(m.ConsumesCounters, DeviceCounterConsumption{}) + if err := m.ConsumesCounters[len(m.ConsumesCounters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 4: + case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidRange", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -4953,81 +6721,28 @@ func (m *CapacityRequestPolicy) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.ValidRange == nil { - m.ValidRange = &CapacityRequestPolicyRange{} - } - if err := m.ValidRange.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + s := string(dAtA[iNdEx:postIndex]) + m.NodeName = &s iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CapacityRequestPolicyRange) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CapacityRequestPolicyRange: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CapacityRequestPolicyRange: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Min", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeSelector", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5054,16 +6769,37 @@ func (m *CapacityRequestPolicyRange) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Min == nil { - m.Min = &resource.Quantity{} + if m.NodeSelector == nil { + m.NodeSelector = &v11.NodeSelector{} } - if err := m.Min.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.NodeSelector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 2: + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllNodes", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.AllNodes = &b + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Taints", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5090,18 +6826,37 @@ func (m *CapacityRequestPolicyRange) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Max == nil { - m.Max = &resource.Quantity{} - } - if err := m.Max.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Taints = append(m.Taints, DeviceTaint{}) + if err := m.Taints[len(m.Taints)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 3: + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BindsToNode", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.BindsToNode = &b + case 10: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Step", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BindingConditions", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5111,81 +6866,80 @@ func (m *CapacityRequestPolicyRange) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Step == nil { - m.Step = &resource.Quantity{} + m.BindingConditions = append(m.BindingConditions, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BindingFailureConditions", wireType) } - if err := m.Step.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated } - if (skippy < 0) || (iNdEx+skippy) < 0 { + postIndex := iNdEx + intStringLen + if postIndex < 0 { return ErrInvalidLengthGenerated } - if (iNdEx + skippy) > l { + if postIndex > l { return io.ErrUnexpectedEOF } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF + m.BindingFailureConditions = append(m.BindingFailureConditions, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 12: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowMultipleAllocations", wireType) } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CapacityRequirements: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CapacityRequirements: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + b := bool(v != 0) + m.AllowMultipleAllocations = &b + case 14: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResources", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5212,11 +6966,11 @@ func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Requests == nil { - m.Requests = make(map[QualifiedName]resource.Quantity) + if m.NodeAllocatableResources == nil { + m.NodeAllocatableResources = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource) } - var mapkey QualifiedName - mapvalue := &resource.Quantity{} + var mapkey k8s_io_api_core_v1.ResourceName + mapvalue := &NodeAllocatableResource{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 @@ -5262,7 +7016,7 @@ func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { if postStringIndexmapkey > l { return io.ErrUnexpectedEOF } - mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) + mapkey = k8s_io_api_core_v1.ResourceName(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { var mapmsglen int @@ -5290,7 +7044,7 @@ func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { if postmsgIndex > l { return io.ErrUnexpectedEOF } - mapvalue = &resource.Quantity{} + mapvalue = &NodeAllocatableResource{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } @@ -5310,7 +7064,7 @@ func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { iNdEx += skippy } } - m.Requests[QualifiedName(mapkey)] = *mapvalue + m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -5333,7 +7087,7 @@ func (m *CapacityRequirements) Unmarshal(dAtA []byte) error { } return nil } -func (m *Counter) Unmarshal(dAtA []byte) error { +func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5356,17 +7110,17 @@ func (m *Counter) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Counter: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceAllocationConfiguration: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Counter: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceAllocationConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5376,78 +7130,27 @@ func (m *Counter) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Source = AllocationConfigSource(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CounterSet) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CounterSet: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CounterSet: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -5475,11 +7178,11 @@ func (m *CounterSet) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Counters", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceConfiguration", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5506,105 +7209,9 @@ func (m *CounterSet) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Counters == nil { - m.Counters = make(map[string]Counter) - } - var mapkey string - mapvalue := &Counter{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &Counter{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } + if err := m.DeviceConfiguration.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.Counters[mapkey] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -5627,7 +7234,7 @@ func (m *CounterSet) Unmarshal(dAtA []byte) error { } return nil } -func (m *Device) Unmarshal(dAtA []byte) error { +func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -5650,17 +7257,17 @@ func (m *Device) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: Device: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceAllocationResult: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: Device: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceAllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Results", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5670,27 +7277,29 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + m.Results = append(m.Results, DeviceRequestAllocationResult{}) + if err := m.Results[len(m.Results)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Attributes", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5717,111 +7326,107 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Attributes == nil { - m.Attributes = make(map[QualifiedName]DeviceAttribute) + m.Config = append(m.Config, DeviceAllocationConfiguration{}) + if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - var mapkey QualifiedName - mapvalue := &DeviceAttribute{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &DeviceAttribute{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceAttribute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceAttribute: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IntValue", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break } } - m.Attributes[QualifiedName(mapkey)] = *mapvalue - iNdEx = postIndex + m.IntValue = &v case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BoolValue", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.BoolValue = &b + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StringValue", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5831,29 +7436,61 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Capacity == nil { - m.Capacity = make(map[QualifiedName]DeviceCapacity) + s := string(dAtA[iNdEx:postIndex]) + m.StringValue = &s + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VersionValue", wireType) } - var mapkey QualifiedName - mapvalue := &DeviceCapacity{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.VersionValue = &s + iNdEx = postIndex + case 6: + if wireType == 0 { + var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5863,43 +7500,51 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - wire |= uint64(b&0x7F) << shift + v |= int64(b&0x7F) << shift if b < 0x80 { break } } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + m.IntValues = append(m.IntValues, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated + if iNdEx >= l { + return io.ErrUnexpectedEOF } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF + } + if packedLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ } - mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int + } + elementCount = count + if elementCount != 0 && len(m.IntValues) == 0 { + m.IntValues = make([]int64, 0, elementCount) + } + for iNdEx < postIndex { + var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5909,48 +7554,91 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - mapmsglen |= int(b&0x7F) << shift + v |= int64(b&0x7F) << shift if b < 0x80 { break } } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated + m.IntValues = append(m.IntValues, v) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field IntValues", wireType) + } + case 7: + if wireType == 0 { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - if postmsgIndex > l { + if iNdEx >= l { return io.ErrUnexpectedEOF } - mapvalue = &DeviceCapacity{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated + } + m.BoolValues = append(m.BoolValues, bool(v != 0)) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated } - if (iNdEx + skippy) > postIndex { + if iNdEx >= l { return io.ErrUnexpectedEOF } - iNdEx += skippy + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + elementCount = packedLen + if elementCount != 0 && len(m.BoolValues) == 0 { + m.BoolValues = make([]bool, 0, elementCount) + } + for iNdEx < postIndex { + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.BoolValues = append(m.BoolValues, bool(v != 0)) } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field BoolValues", wireType) } - m.Capacity[QualifiedName(mapkey)] = *mapvalue - iNdEx = postIndex - case 4: + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumesCounters", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StringValues", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -5960,29 +7648,27 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.ConsumesCounters = append(m.ConsumesCounters, DeviceCounterConsumption{}) - if err := m.ConsumesCounters[len(m.ConsumesCounters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.StringValues = append(m.StringValues, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 5: + case 9: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field VersionValues", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6010,12 +7696,61 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.NodeName = &s + m.VersionValues = append(m.VersionValues, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 6: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceCapacity) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceCapacity: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeSelector", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6042,18 +7777,15 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.NodeSelector == nil { - m.NodeSelector = &v11.NodeSelector{} - } - if err := m.NodeSelector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AllNodes", wireType) + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RequestPolicy", wireType) } - var v int + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6063,16 +7795,81 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - b := bool(v != 0) - m.AllNodes = &b - case 8: + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.RequestPolicy == nil { + m.RequestPolicy = &CapacityRequestPolicy{} + } + if err := m.RequestPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceClaim) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Taints", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6099,16 +7896,16 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Taints = append(m.Taints, DeviceTaint{}) - if err := m.Taints[len(m.Taints)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Requests = append(m.Requests, DeviceRequest{}) + if err := m.Requests[len(m.Requests)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BindsToNode", wireType) + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Constraints", wireType) } - var v int + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6118,18 +7915,31 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - b := bool(v != 0) - m.BindsToNode = &b - case 10: + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Constraints = append(m.Constraints, DeviceConstraint{}) + if err := m.Constraints[len(m.Constraints)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BindingConditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6139,27 +7949,79 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } - if postIndex > l { + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Config = append(m.Config, DeviceClaimConfiguration{}) + if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { return io.ErrUnexpectedEOF } - m.BindingConditions = append(m.BindingConditions, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 11: + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceClaimConfiguration: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceClaimConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BindingFailureConditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6187,32 +8049,11 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.BindingFailureConditions = append(m.BindingFailureConditions, string(dAtA[iNdEx:postIndex])) + m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 12: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowMultipleAllocations", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - b := bool(v != 0) - m.AllowMultipleAllocations = &b - case 13: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResourceMappings", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceConfiguration", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6239,105 +8080,9 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.NodeAllocatableResourceMappings == nil { - m.NodeAllocatableResourceMappings = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping) - } - var mapkey k8s_io_api_core_v1.ResourceName - mapvalue := &NodeAllocatableResourceMapping{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = k8s_io_api_core_v1.ResourceName(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &NodeAllocatableResourceMapping{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } + if err := m.DeviceConfiguration.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -6360,7 +8105,7 @@ func (m *Device) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { +func (m *DeviceClass) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6383,17 +8128,17 @@ func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceAllocationConfiguration: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceClass: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceAllocationConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceClass: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6403,29 +8148,30 @@ func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Source = AllocationConfigSource(dAtA[iNdEx:postIndex]) + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6435,25 +8181,76 @@ func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 3: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceClassConfiguration) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceClassConfiguration: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceClassConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DeviceConfiguration", wireType) } @@ -6507,7 +8304,7 @@ func (m *DeviceAllocationConfiguration) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { +func (m *DeviceClassList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6530,15 +8327,15 @@ func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceAllocationResult: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceClassList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceAllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceClassList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Results", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6565,14 +8362,13 @@ func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Results = append(m.Results, DeviceRequestAllocationResult{}) - if err := m.Results[len(m.Results)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6599,8 +8395,8 @@ func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Config = append(m.Config, DeviceAllocationConfiguration{}) - if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Items = append(m.Items, DeviceClass{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -6625,7 +8421,7 @@ func (m *DeviceAllocationResult) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { +func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -6648,58 +8444,17 @@ func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceAttribute: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceClassSpec: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceAttribute: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceClassSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field IntValue", wireType) - } - var v int64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IntValue = &v - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BoolValue", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - b := bool(v != 0) - m.BoolValue = &b - case 4: + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringValue", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6709,209 +8464,31 @@ func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.StringValue = &s - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VersionValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF + m.Selectors = append(m.Selectors, DeviceSelector{}) + if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - s := string(dAtA[iNdEx:postIndex]) - m.VersionValue = &s iNdEx = postIndex - case 6: - if wireType == 0 { - var v int64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IntValues = append(m.IntValues, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.IntValues) == 0 { - m.IntValues = make([]int64, 0, elementCount) - } - for iNdEx < postIndex { - var v int64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IntValues = append(m.IntValues, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field IntValues", wireType) - } - case 7: - if wireType == 0 { - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.BoolValues = append(m.BoolValues, bool(v != 0)) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - elementCount = packedLen - if elementCount != 0 && len(m.BoolValues) == 0 { - m.BoolValues = make([]bool, 0, elementCount) - } - for iNdEx < postIndex { - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.BoolValues = append(m.BoolValues, bool(v != 0)) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field BoolValues", wireType) - } - case 8: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringValues", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -6921,27 +8498,29 @@ func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.StringValues = append(m.StringValues, string(dAtA[iNdEx:postIndex])) + m.Config = append(m.Config, DeviceClassConfiguration{}) + if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 9: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VersionValues", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ExtendedResourceName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -6969,7 +8548,8 @@ func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.VersionValues = append(m.VersionValues, string(dAtA[iNdEx:postIndex])) + s := string(dAtA[iNdEx:postIndex]) + m.ExtendedResourceName = &s iNdEx = postIndex default: iNdEx = preIndex @@ -6992,7 +8572,7 @@ func (m *DeviceAttribute) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceCapacity) Unmarshal(dAtA []byte) error { +func (m *DeviceConfiguration) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7015,48 +8595,15 @@ func (m *DeviceCapacity) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceCapacity: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceConfiguration: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestPolicy", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Opaque", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -7083,10 +8630,10 @@ func (m *DeviceCapacity) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.RequestPolicy == nil { - m.RequestPolicy = &CapacityRequestPolicy{} + if m.Opaque == nil { + m.Opaque = &OpaqueDeviceConfiguration{} } - if err := m.RequestPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Opaque.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -7111,7 +8658,7 @@ func (m *DeviceCapacity) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceClaim) Unmarshal(dAtA []byte) error { +func (m *DeviceConstraint) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7134,17 +8681,17 @@ func (m *DeviceClaim) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceClaim: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceConstraint: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceConstraint: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7154,31 +8701,29 @@ func (m *DeviceClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Requests = append(m.Requests, DeviceRequest{}) - if err := m.Requests[len(m.Requests)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Constraints", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field MatchAttribute", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7188,31 +8733,30 @@ func (m *DeviceClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Constraints = append(m.Constraints, DeviceConstraint{}) - if err := m.Constraints[len(m.Constraints)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + s := FullyQualifiedName(dAtA[iNdEx:postIndex]) + m.MatchAttribute = &s iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DistinctAttribute", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7222,25 +8766,24 @@ func (m *DeviceClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Config = append(m.Config, DeviceClaimConfiguration{}) - if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + s := FullyQualifiedName(dAtA[iNdEx:postIndex]) + m.DistinctAttribute = &s iNdEx = postIndex default: iNdEx = preIndex @@ -7263,7 +8806,7 @@ func (m *DeviceClaim) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { +func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7286,15 +8829,15 @@ func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceClaimConfiguration: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceCounterConsumption: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClaimConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceCounterConsumption: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CounterSet", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7322,13 +8865,142 @@ func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) + m.CounterSet = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Counters", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Counters == nil { + m.Counters = make(map[string]Counter) + } + var mapkey string + mapvalue := &Counter{} + for iNdEx < postIndex { + entryPreIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthGenerated + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthGenerated + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthGenerated + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &Counter{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.Counters[mapkey] = *mapvalue iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DeviceConfiguration", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CompatibilityGroups", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7338,24 +9010,23 @@ func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.DeviceConfiguration.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.CompatibilityGroups = append(m.CompatibilityGroups, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex @@ -7378,7 +9049,7 @@ func (m *DeviceClaimConfiguration) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceClass) Unmarshal(dAtA []byte) error { +func (m *DeviceDerivedAttribute) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7401,17 +9072,17 @@ func (m *DeviceClass) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceClass: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceDerivedAttribute: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClass: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceDerivedAttribute: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7421,30 +9092,29 @@ func (m *DeviceClass) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = FullyQualifiedName(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Expression", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7454,24 +9124,23 @@ func (m *DeviceClass) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Expression = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -7494,7 +9163,7 @@ func (m *DeviceClass) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceClassConfiguration) Unmarshal(dAtA []byte) error { +func (m *DeviceRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7517,17 +9186,17 @@ func (m *DeviceClassConfiguration) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceClassConfiguration: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClassConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DeviceConfiguration", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7537,78 +9206,27 @@ func (m *DeviceClassConfiguration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.DeviceConfiguration.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DeviceClassList) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DeviceClassList: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClassList: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Exactly", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -7635,13 +9253,16 @@ func (m *DeviceClassList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if m.Exactly == nil { + m.Exactly = &ExactDeviceRequest{} + } + if err := m.Exactly.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field FirstAvailable", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -7668,8 +9289,8 @@ func (m *DeviceClassList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, DeviceClass{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.FirstAvailable = append(m.FirstAvailable, DeviceSubRequest{}) + if err := m.FirstAvailable[len(m.FirstAvailable)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -7694,7 +9315,7 @@ func (m *DeviceClassList) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { +func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -7717,17 +9338,17 @@ func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceClassSpec: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceRequestAllocationResult: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceClassSpec: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceRequestAllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7737,31 +9358,29 @@ func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Selectors = append(m.Selectors, DeviceSelector{}) - if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Request = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7771,29 +9390,27 @@ func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Config = append(m.Config, DeviceClassConfiguration{}) - if err := m.Config[len(m.Config)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Driver = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExtendedResourceName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -7821,64 +9438,45 @@ func (m *DeviceClassSpec) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.ExtendedResourceName = &s + m.Pool = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DeviceConfiguration) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated } - if iNdEx >= l { + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DeviceConfiguration: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceConfiguration: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Opaque", wireType) + m.Device = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AdminAccess", wireType) } - var msglen int + var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7888,83 +9486,18 @@ func (m *DeviceConfiguration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + v |= int(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Opaque == nil { - m.Opaque = &OpaqueDeviceConfiguration{} - } - if err := m.Opaque.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DeviceConstraint) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DeviceConstraint: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceConstraint: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + b := bool(v != 0) + m.AdminAccess = &b + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requests", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -7974,27 +9507,29 @@ func (m *DeviceConstraint) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Requests = append(m.Requests, string(dAtA[iNdEx:postIndex])) + m.Tolerations = append(m.Tolerations, DeviceToleration{}) + if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: + case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MatchAttribute", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BindingConditions", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -8022,12 +9557,11 @@ func (m *DeviceConstraint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := FullyQualifiedName(dAtA[iNdEx:postIndex]) - m.MatchAttribute = &s + m.BindingConditions = append(m.BindingConditions, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 3: + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DistinctAttribute", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BindingFailureConditions", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -8055,62 +9589,11 @@ func (m *DeviceConstraint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := FullyQualifiedName(dAtA[iNdEx:postIndex]) - m.DistinctAttribute = &s + m.BindingFailureConditions = append(m.BindingFailureConditions, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DeviceCounterConsumption: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceCounterConsumption: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + case 9: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CounterSet", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ShareID", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -8138,11 +9621,12 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.CounterSet = string(dAtA[iNdEx:postIndex]) + s := k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) + m.ShareID = &s iNdEx = postIndex - case 2: + case 10: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Counters", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ConsumedCapacity", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -8169,11 +9653,11 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Counters == nil { - m.Counters = make(map[string]Counter) + if m.ConsumedCapacity == nil { + m.ConsumedCapacity = make(map[QualifiedName]resource.Quantity) } - var mapkey string - mapvalue := &Counter{} + var mapkey QualifiedName + mapvalue := &resource.Quantity{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 @@ -8219,7 +9703,7 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { if postStringIndexmapkey > l { return io.ErrUnexpectedEOF } - mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) iNdEx = postStringIndexmapkey } else if fieldNum == 2 { var mapmsglen int @@ -8247,7 +9731,7 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { if postmsgIndex > l { return io.ErrUnexpectedEOF } - mapvalue = &Counter{} + mapvalue = &resource.Quantity{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } @@ -8267,7 +9751,125 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { iNdEx += skippy } } - m.Counters[mapkey] = *mapvalue + m.ConsumedCapacity[QualifiedName(mapkey)] = *mapvalue + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceSelector) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceSelector: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceSelector: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CEL", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CEL == nil { + m.CEL = &CELDeviceSelector{} + } + if err := m.CEL.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -8290,7 +9892,7 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceRequest) Unmarshal(dAtA []byte) error { +func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -8313,10 +9915,10 @@ func (m *DeviceRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceRequest: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceSubRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceSubRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -8353,9 +9955,9 @@ func (m *DeviceRequest) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Exactly", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceClassName", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8365,31 +9967,27 @@ func (m *DeviceRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Exactly == nil { - m.Exactly = &ExactDeviceRequest{} - } - if err := m.Exactly.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.DeviceClassName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FirstAvailable", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -8416,66 +10014,67 @@ func (m *DeviceRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.FirstAvailable = append(m.FirstAvailable, DeviceSubRequest{}) - if err := m.FirstAvailable[len(m.FirstAvailable)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Selectors = append(m.Selectors, DeviceSelector{}) + if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AllocationMode", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated } - if iNdEx >= l { + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + m.AllocationMode = DeviceAllocationMode(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType) } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DeviceRequestAllocationResult: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceRequestAllocationResult: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: + m.Count = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Count |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8485,29 +10084,31 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Request = string(dAtA[iNdEx:postIndex]) + m.Tolerations = append(m.Tolerations, DeviceToleration{}) + if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: + case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8517,29 +10118,33 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Driver = string(dAtA[iNdEx:postIndex]) + if m.Capacity == nil { + m.Capacity = &CapacityRequirements{} + } + if err := m.Capacity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 3: + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8549,27 +10154,79 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Pool = string(dAtA[iNdEx:postIndex]) + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 4: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceTaint) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceTaint: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceTaint: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -8597,34 +10254,13 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Device = string(dAtA[iNdEx:postIndex]) + m.Key = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AdminAccess", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - b := bool(v != 0) - m.AdminAccess = &b - case 6: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8634,29 +10270,27 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Tolerations = append(m.Tolerations, DeviceToleration{}) - if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.Value = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 7: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BindingConditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -8684,13 +10318,13 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.BindingConditions = append(m.BindingConditions, string(dAtA[iNdEx:postIndex])) + m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 8: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BindingFailureConditions", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TimeAdded", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8700,29 +10334,83 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.BindingFailureConditions = append(m.BindingFailureConditions, string(dAtA[iNdEx:postIndex])) + if m.TimeAdded == nil { + m.TimeAdded = &v1.Time{} + } + if err := m.TimeAdded.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 9: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceTaintRule) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceTaintRule: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceTaintRule: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShareID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -8732,28 +10420,28 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - s := k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) - m.ShareID = &s + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 10: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConsumedCapacity", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -8765,120 +10453,57 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.ConsumedCapacity == nil { - m.ConsumedCapacity = make(map[QualifiedName]resource.Quantity) - } - var mapkey QualifiedName - mapvalue := &resource.Quantity{} - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = QualifiedName(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var mapmsglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - mapmsglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if mapmsglen < 0 { - return ErrInvalidLengthGenerated - } - postmsgIndex := iNdEx + mapmsglen - if postmsgIndex < 0 { - return ErrInvalidLengthGenerated - } - if postmsgIndex > l { - return io.ErrUnexpectedEOF - } - mapvalue = &resource.Quantity{} - if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { - return err - } - iNdEx = postmsgIndex - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break } } - m.ConsumedCapacity[QualifiedName(mapkey)] = *mapvalue + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex default: iNdEx = preIndex @@ -8901,7 +10526,7 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceSelector) Unmarshal(dAtA []byte) error { +func (m *DeviceTaintRuleList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -8924,15 +10549,15 @@ func (m *DeviceSelector) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceSelector: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceTaintRuleList: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceSelector: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceTaintRuleList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CEL", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -8959,10 +10584,41 @@ func (m *DeviceSelector) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.CEL == nil { - m.CEL = &CELDeviceSelector{} + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - if err := m.CEL.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, DeviceTaintRule{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -8987,7 +10643,7 @@ func (m *DeviceSelector) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { +func (m *DeviceTaintRuleSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9010,17 +10666,17 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceSubRequest: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceTaintRuleSpec: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceSubRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceTaintRuleSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceSelector", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9030,29 +10686,33 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Name = string(dAtA[iNdEx:postIndex]) + if m.DeviceSelector == nil { + m.DeviceSelector = &DeviceTaintSelector{} + } + if err := m.DeviceSelector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DeviceClassName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Taint", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9062,27 +10722,78 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.DeviceClassName = string(dAtA[iNdEx:postIndex]) + if err := m.Taint.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 3: + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceTaintRuleStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceTaintRuleStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceTaintRuleStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -9109,48 +10820,66 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Selectors = append(m.Selectors, DeviceSelector{}) - if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationMode", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - intStringLen := int(stringLen) - if intStringLen < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF } - if postIndex > l { + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceTaintSelector) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { return io.ErrUnexpectedEOF } - m.AllocationMode = DeviceAllocationMode(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType) + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break } - m.Count = 0 + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceTaintSelector: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceTaintSelector: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + } + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9160,16 +10889,30 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Count |= int64(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - case 6: + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.Driver = &s + iNdEx = postIndex + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9179,31 +10922,30 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Tolerations = append(m.Tolerations, DeviceToleration{}) - if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + s := string(dAtA[iNdEx:postIndex]) + m.Pool = &s iNdEx = postIndex - case 7: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9213,27 +10955,24 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.Capacity == nil { - m.Capacity = &CapacityRequirements{} - } - if err := m.Capacity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + s := string(dAtA[iNdEx:postIndex]) + m.Device = &s iNdEx = postIndex default: iNdEx = preIndex @@ -9256,7 +10995,7 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceTaint) Unmarshal(dAtA []byte) error { +func (m *DeviceToleration) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9279,10 +11018,10 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceTaint: wiretype end group for non-group") + return fmt.Errorf("proto: DeviceToleration: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceTaint: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: DeviceToleration: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -9319,7 +11058,7 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Operator", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9347,11 +11086,11 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Value = string(dAtA[iNdEx:postIndex]) + m.Operator = DeviceTolerationOperator(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9379,13 +11118,13 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + m.Value = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeAdded", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9395,28 +11134,44 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.TimeAdded == nil { - m.TimeAdded = &v1.Time{} + m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TolerationSeconds", wireType) } - if err := m.TimeAdded.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } } - iNdEx = postIndex + m.TolerationSeconds = &v default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9438,7 +11193,7 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceToleration) Unmarshal(dAtA []byte) error { +func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9461,15 +11216,15 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceToleration: wiretype end group for non-group") + return fmt.Errorf("proto: ExactDeviceRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceToleration: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: ExactDeviceRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceClassName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9497,13 +11252,13 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Key = string(dAtA[iNdEx:postIndex]) + m.DeviceClassName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Operator", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9513,27 +11268,29 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Operator = DeviceTolerationOperator(dAtA[iNdEx:postIndex]) + m.Selectors = append(m.Selectors, DeviceSelector{}) + if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field AllocationMode", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9561,13 +11318,53 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Value = string(dAtA[iNdEx:postIndex]) + m.AllocationMode = DeviceAllocationMode(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType) + } + m.Count = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Count |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AdminAccess", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + b := bool(v != 0) + m.AdminAccess = &b + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9577,29 +11374,31 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + m.Tolerations = append(m.Tolerations, DeviceToleration{}) + if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TolerationSeconds", wireType) + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) } - var v int64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9609,12 +11408,62 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - m.TolerationSeconds = &v + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Capacity == nil { + m.Capacity = &CapacityRequirements{} + } + if err := m.Capacity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9636,7 +11485,7 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } return nil } -func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { +func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9659,15 +11508,15 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: ExactDeviceRequest: wiretype end group for non-group") + return fmt.Errorf("proto: NetworkDeviceData: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: ExactDeviceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NetworkDeviceData: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DeviceClassName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field InterfaceName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9695,13 +11544,13 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.DeviceClassName = string(dAtA[iNdEx:postIndex]) + m.InterfaceName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Selectors", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field IPs", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9711,29 +11560,27 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Selectors = append(m.Selectors, DeviceSelector{}) - if err := m.Selectors[len(m.Selectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.IPs = append(m.IPs, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationMode", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field HardwareAddress", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9761,32 +11608,63 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.AllocationMode = DeviceAllocationMode(dAtA[iNdEx:postIndex]) + m.HardwareAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Count", wireType) + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - m.Count = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Count |= int64(b&0x7F) << shift - if b < 0x80 { - break - } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AdminAccess", wireType) + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF } - var v int + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NodeAllocatableMapping) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodeAllocatableMapping: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodeAllocatableMapping: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CapacityKey", wireType) + } + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9796,16 +11674,28 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - b := bool(v != 0) - m.AdminAccess = &b - case 6: + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := QualifiedName(dAtA[iNdEx:postIndex]) + m.CapacityKey = &s + iNdEx = postIndex + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Tolerations", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CapacityMultiplier", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -9832,14 +11722,16 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Tolerations = append(m.Tolerations, DeviceToleration{}) - if err := m.Tolerations[len(m.Tolerations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if m.CapacityMultiplier == nil { + m.CapacityMultiplier = &resource.Quantity{} + } + if err := m.CapacityMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 7: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceMultiplier", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -9866,10 +11758,10 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.Capacity == nil { - m.Capacity = &CapacityRequirements{} + if m.DeviceMultiplier == nil { + m.DeviceMultiplier = &resource.Quantity{} } - if err := m.Capacity.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.DeviceMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -9894,7 +11786,7 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableOverhead) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9917,17 +11809,17 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NetworkDeviceData: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableOverhead: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkDeviceData: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableOverhead: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterfaceName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PerPod", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9937,29 +11829,33 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.InterfaceName = string(dAtA[iNdEx:postIndex]) + if m.PerPod == nil { + m.PerPod = &resource.Quantity{} + } + if err := m.PerPod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IPs", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PerContainer", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9969,55 +11865,27 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.IPs = append(m.IPs, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardwareAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + if m.PerContainer == nil { + m.PerContainer = &resource.Quantity{} } - if postIndex > l { - return io.ErrUnexpectedEOF + if err := m.PerContainer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.HardwareAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -10040,7 +11908,7 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } return nil } -func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableResource) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -10063,17 +11931,17 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableResource: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableResource: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CapacityKey", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Mapping", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -10083,28 +11951,31 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - s := QualifiedName(dAtA[iNdEx:postIndex]) - m.CapacityKey = &s + if m.Mapping == nil { + m.Mapping = &NodeAllocatableMapping{} + } + if err := m.Mapping.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationMultiplier", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Overhead", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -10131,10 +12002,10 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.AllocationMultiplier == nil { - m.AllocationMultiplier = &resource.Quantity{} + if m.Overhead == nil { + m.Overhead = &NodeAllocatableOverhead{} } - if err := m.AllocationMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Overhead.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -11930,6 +13801,71 @@ func (m *ResourceSliceSpec) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartitionTypeAttribute", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := FullyQualifiedName(dAtA[iNdEx:postIndex]) + m.PartitionTypeAttribute = &s + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/resource/v1/generated.proto b/constraint/vendor/k8s.io/api/resource/v1/generated.proto index 8bacfd846..76559dc94 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/resource/v1/generated.proto @@ -65,8 +65,8 @@ message AllocatedDeviceStatus { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 7; // Conditions contains the latest observation of the device's state. @@ -78,6 +78,9 @@ message AllocatedDeviceStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 4; // Data contains arbitrary driver-specific data. @@ -90,7 +93,7 @@ message AllocatedDeviceStatus { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional NetworkDeviceData networkData = 6; } @@ -130,7 +133,7 @@ message CELDeviceSelector { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -163,6 +166,15 @@ message CELDeviceSelector { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -232,6 +244,13 @@ message CapacityRequestPolicy { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -315,8 +334,8 @@ message CounterSet { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string name = 1; // Counters defines the set of counters for this CounterSet @@ -325,8 +344,8 @@ message CounterSet { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; } @@ -345,7 +364,7 @@ message Device { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional map attributes = 2; // Capacity defines the set of capacities for this device. @@ -366,13 +385,13 @@ message Device { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 repeated DeviceCounterConsumption consumesCounters = 4; // NodeName identifies the node where the device is available. @@ -419,7 +438,7 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceTaint taints = 8; // BindsToNode indicates if the usage of an allocation involving this device @@ -449,8 +468,8 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 10; // BindingFailureConditions defines the conditions for binding failure. @@ -467,8 +486,8 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 11; // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -480,7 +499,7 @@ message Device { // +featureGate=DRAConsumableCapacity optional bool allowMultipleAllocations = 12; - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -492,8 +511,9 @@ message Device { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - map nodeAllocatableResourceMappings = 13; + map nodeAllocatableResources = 14; } // DeviceAllocationConfiguration gets embedded in an AllocationResult. @@ -503,7 +523,7 @@ message DeviceAllocationConfiguration { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string source = 1; // Requests lists the names of requests where the configuration applies. @@ -515,10 +535,10 @@ message DeviceAllocationConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 2; optional DeviceConfiguration deviceConfiguration = 3; @@ -530,8 +550,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequestAllocationResult results = 1; // This field is a combination of all the claim and class configuration parameters. @@ -544,8 +564,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 repeated DeviceAllocationConfiguration config = 2; } @@ -554,30 +574,30 @@ message DeviceAttribute { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional int64 int = 2; // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional bool bool = 3; // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string string = 4; // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string version = 5; // IntValues is a non-empty list of numbers. @@ -587,8 +607,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated int64 ints = 6; @@ -597,8 +617,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated bool bools = 7; @@ -610,8 +630,9 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes repeated string strings = 8; @@ -623,8 +644,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated string versions = 9; } @@ -662,11 +683,11 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequest requests = 1; // These constraints must be satisfied by the set of devices that get @@ -674,8 +695,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceConstraint constraints = 2; // This field holds configuration for multiple potential drivers which @@ -684,8 +705,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClaimConfiguration config = 3; } @@ -700,10 +721,10 @@ message DeviceClaimConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; optional DeviceConfiguration deviceConfiguration = 2; @@ -716,8 +737,8 @@ message DeviceClaimConfiguration { message DeviceClass { // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines what can be allocated and how to configure it. @@ -728,6 +749,7 @@ message DeviceClass { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional optional DeviceClassSpec spec = 2; } @@ -753,8 +775,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 1; // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -765,8 +787,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClassConfiguration config = 2; // ExtendedResourceName is the extended resource name for the devices of this class. @@ -778,11 +800,10 @@ message DeviceClassSpec { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name optional string extendedResourceName = 4; } @@ -794,7 +815,7 @@ message DeviceConfiguration { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional OpaqueDeviceConfiguration opaque = 1; } @@ -812,10 +833,10 @@ message DeviceConstraint { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; // MatchAttribute requires that all devices in question have this @@ -838,8 +859,8 @@ message DeviceConstraint { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string matchAttribute = 2; // DistinctAttribute requires that all devices in question have this @@ -861,6 +882,8 @@ message DeviceConstraint { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string distinctAttribute = 3; } @@ -871,8 +894,8 @@ message DeviceCounterConsumption { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string counterSet = 1; // Counters defines the counters that will be consumed by the device. @@ -880,9 +903,94 @@ message DeviceCounterConsumption { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + repeated string compatibilityGroups = 3; +} + +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +message DeviceDerivedAttribute { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + optional string name = 1; + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + optional string expression = 2; } // DeviceRequest is a request for devices required for a claim. @@ -911,7 +1019,7 @@ message DeviceRequest { // // +optional // +oneOf=deviceRequestType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional ExactDeviceRequest exactly = 2; // FirstAvailable contains subrequests, of which exactly one will be @@ -932,11 +1040,11 @@ message DeviceRequest { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated DeviceSubRequest firstAvailable = 3; } @@ -961,9 +1069,9 @@ message DeviceRequestAllocationResult { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string driver = 2; // This name together with the driver name and the device name field @@ -973,8 +1081,8 @@ message DeviceRequestAllocationResult { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name optional string pool = 3; // Device references one device instance via its name in the driver's @@ -1005,7 +1113,7 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // BindingConditions contains a copy of the BindingConditions @@ -1017,8 +1125,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 7; // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1030,8 +1138,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 8; // ShareID uniquely identifies an individual allocation share of the device, @@ -1041,8 +1149,8 @@ message DeviceRequestAllocationResult { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 9; // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -1057,6 +1165,19 @@ message DeviceRequestAllocationResult { // +optional // +featureGate=DRAConsumableCapacity map consumedCapacity = 10; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 11; } // DeviceSelector must have exactly one field set. @@ -1099,8 +1220,8 @@ message DeviceSubRequest { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name optional string deviceClassName = 2; // Selectors define criteria which must be satisfied by a specific @@ -1110,8 +1231,8 @@ message DeviceSubRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 3; // AllocationMode and its related fields define how devices are allocated @@ -1133,7 +1254,7 @@ message DeviceSubRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 4; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1164,7 +1285,7 @@ message DeviceSubRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // Capacity define resource requirements against each capacity. @@ -1183,6 +1304,34 @@ message DeviceSubRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 7; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 8; } // The device this taint is attached to has the "effect" on @@ -1211,7 +1360,7 @@ message DeviceTaint { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string effect = 3; // TimeAdded represents the time at which the taint was added or @@ -1230,6 +1379,119 @@ message DeviceTaint { optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time timeAdded = 4; } +// DeviceTaintRule adds one taint to all devices which match the selector. +// This has the same effect as if the taint was specified directly +// in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" +message DeviceTaintRule { + // Standard object metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // Spec specifies the selector and one taint. + // + // Changing the spec automatically increments the metadata.generation number. + // +required + optional DeviceTaintRuleSpec spec = 2; + + // Status provides information about what was requested in the spec. + // + // +optional + optional DeviceTaintRuleStatus status = 3; +} + +// DeviceTaintRuleList is a collection of DeviceTaintRules. +message DeviceTaintRuleList { + // Standard list metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of DeviceTaintRules. + repeated DeviceTaintRule items = 2; +} + +// DeviceTaintRuleSpec specifies the selector and one taint. +message DeviceTaintRuleSpec { + // DeviceSelector defines which device(s) the taint is applied to. + // All selector criteria must be satisfied for a device to + // match. The empty selector matches all devices. Without + // a selector, no devices are matches. + // + // +optional + optional DeviceTaintSelector deviceSelector = 1; + + // The taint that gets applied to matching devices. + // + // +required + optional DeviceTaint taint = 2; +} + +// DeviceTaintRuleStatus provides information about an on-going pod eviction. +message DeviceTaintRuleStatus { + // Conditions provide information about the state of the DeviceTaintRule + // and the cluster at some point in time, + // in a machine-readable and human-readable format. + // + // The following condition is currently defined as part of this API, more may + // get added: + // - Type: EvictionInProgress + // - Status: True if there are currently pods which need to be evicted, False otherwise + // (includes the effects which don't cause eviction). + // - Reason: not specified, may change + // - Message: includes information about number of pending pods and already evicted pods + // in a human-readable format, updated periodically, may change + // + // For `effect: None`, the condition above gets set once for each change to + // the spec, with the message containing information about what would happen + // if the effect was `NoExecute`. This feedback can be used to decide whether + // changing the effect to `NoExecute` will work as intended. It only gets + // set once to avoid having to constantly update the status. + // + // Must have 8 or fewer entries. + // + // +optional + // +listType=map + // +listMapKey=type + // +patchStrategy=merge + // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; +} + +// DeviceTaintSelector defines which device(s) a DeviceTaintRule applies to. +// The empty selector matches all devices. Without a selector, no devices +// are matched. +message DeviceTaintSelector { + // If driver is set, only devices from that driver are selected. + // This fields corresponds to slice.spec.driver. + // + // +optional + optional string driver = 2; + + // If pool is set, only devices in that pool are selected. + // + // Also setting the driver name may be useful to avoid + // ambiguity when different drivers use the same pool name, + // but this is not required because selecting pools from + // different drivers may also be useful, for example when + // drivers with node-local devices use the node name as + // their pool name. + // + // +optional + optional string pool = 3; + + // If device is set, only devices with that name are selected. + // This field corresponds to slice.spec.devices[].name. + // + // Setting also driver and pool may be required to avoid ambiguity, + // but is not required. + // + // +optional + optional string device = 4; +} + // The ResourceClaim this DeviceToleration is attached to tolerates any taint that matches // the triple using the matching operator . message DeviceToleration { @@ -1238,8 +1500,8 @@ message DeviceToleration { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key optional string key = 1; // Operator represents a key's relationship to the value. @@ -1249,7 +1511,7 @@ message DeviceToleration { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string operator = 2; // Value is the taint value the toleration matches to. @@ -1263,7 +1525,7 @@ message DeviceToleration { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string effect = 4; // TolerationSeconds represents the period of time the toleration (which must be @@ -1301,8 +1563,8 @@ message ExactDeviceRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 2; // AllocationMode and its related fields define how devices are allocated @@ -1325,7 +1587,7 @@ message ExactDeviceRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 3; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1369,7 +1631,7 @@ message ExactDeviceRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // Capacity define resource requirements against each capacity. @@ -1388,6 +1650,34 @@ message ExactDeviceRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 7; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 8; } // NetworkDeviceData provides network-related details for the allocated device. @@ -1401,8 +1691,8 @@ message NetworkDeviceData { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 optional string interfaceName = 1; // IPs lists the network addresses assigned to the device's network interface. @@ -1413,10 +1703,10 @@ message NetworkDeviceData { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 repeated string ips = 2; // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -1424,47 +1714,104 @@ message NetworkDeviceData { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 optional string hardwareAddress = 3; } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -message NodeAllocatableResourceMapping { +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +message NodeAllocatableMapping { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") optional string capacityKey = 1; - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - optional .k8s.io.apimachinery.pkg.api.resource.Quantity allocationMultiplier = 2; + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + optional .k8s.io.apimachinery.pkg.api.resource.Quantity capacityMultiplier = 2; + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + optional .k8s.io.apimachinery.pkg.api.resource.Quantity deviceMultiplier = 3; +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +message NodeAllocatableOverhead { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perPod = 1; + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perContainer = 2; +} + +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +message NodeAllocatableResource { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + optional NodeAllocatableMapping mapping = 3; + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + optional NodeAllocatableOverhead overhead = 4; } // OpaqueDeviceConfiguration contains configuration parameters for a driver @@ -1480,9 +1827,9 @@ message OpaqueDeviceConfiguration { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string driver = 1; // Parameters can contain arbitrary data. It is the responsibility of @@ -1508,7 +1855,8 @@ message ResourceClaim { // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional optional ResourceClaimSpec spec = 2; // Status describes whether the claim is ready to use and what has been allocated. @@ -1563,8 +1911,8 @@ message ResourceClaimStatus { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify optional AllocationResult allocation = 1; // ReservedFor indicates which entities are currently allowed to use @@ -1592,10 +1940,10 @@ message ResourceClaimStatus { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 repeated ResourceClaimConsumerReference reservedFor = 2; // Devices contains the status of each device allocated for this @@ -1603,18 +1951,18 @@ message ResourceClaimStatus { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID repeated AllocatedDeviceStatus devices = 4; } @@ -1629,6 +1977,7 @@ message ResourceClaimTemplate { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional optional ResourceClaimTemplateSpec spec = 2; } @@ -1648,11 +1997,13 @@ message ResourceClaimTemplateSpec { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional optional ResourceClaimSpec spec = 2; } @@ -1660,6 +2011,8 @@ message ResourceClaimTemplateSpec { message ResourcePool { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -1797,7 +2150,7 @@ message ResourceSliceSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType repeated Device devices = 6; @@ -1823,14 +2176,50 @@ message ResourceSliceSpec { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated CounterSet sharedCounters = 8; + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + optional string partitionTypeAttribute = 9; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 10; } diff --git a/constraint/vendor/k8s.io/api/resource/v1/register.go b/constraint/vendor/k8s.io/api/resource/v1/register.go index dca649225..c634e4c9a 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/register.go +++ b/constraint/vendor/k8s.io/api/resource/v1/register.go @@ -46,6 +46,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &DeviceClass{}, &DeviceClassList{}, + &DeviceTaintRule{}, + &DeviceTaintRuleList{}, &ResourceClaim{}, &ResourceClaimList{}, &ResourceClaimTemplate{}, diff --git a/constraint/vendor/k8s.io/api/resource/v1/types.go b/constraint/vendor/k8s.io/api/resource/v1/types.go index 27d5eff29..580ffc327 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/types.go +++ b/constraint/vendor/k8s.io/api/resource/v1/types.go @@ -93,7 +93,7 @@ const ( // For resources that are not local to a node, the node name is not set. Instead, // the driver may use a node selector to specify where the devices are available. type ResourceSlice struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -112,6 +112,9 @@ const ( // ResourceSliceSelectorDriver can be used in a [metav1.ListOptions] // field selector to filter based on [ResourceSliceSpec.Driver]. ResourceSliceSelectorDriver = "spec.driver" + // ResourceSliceSelectorPoolName can be used in a [metav1.ListOptions] + // field selector to filter based on [ResourceSliceSpec.Pool.Name]. + ResourceSliceSelectorPoolName = "spec.pool.name" ) // ResourceSliceSpec contains the information published by the driver in one ResourceSlice. @@ -175,7 +178,7 @@ type ResourceSliceSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType Devices []Device `json:"devices,omitempty" protobuf:"bytes,6,name=devices"` @@ -201,17 +204,68 @@ type ResourceSliceSpec struct { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 SharedCounters []CounterSet `json:"sharedCounters,omitempty" protobuf:"bytes,8,name=sharedCounters"` + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + PartitionTypeAttribute *FullyQualifiedName `json:"partitionTypeAttribute,omitempty" protobuf:"bytes,9,opt,name=partitionTypeAttribute"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,10,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } +// +enum +// +k8s:enum +type SkipNodeOperation string + +const ( + // SkipNodeOperationNodePrepareResources indicates that NodePrepareResources gRPC calls are skipped. + SkipNodeOperationNodePrepareResources SkipNodeOperation = "NodePrepareResources" + + // SkipNodeOperationNodeUnprepareResources indicates that NodeUnprepareResources gRPC calls are skipped. + SkipNodeOperationNodeUnprepareResources SkipNodeOperation = "NodeUnprepareResources" + + // SkipNodeOperationAll indicates that all node-local resource operations are skipped. + SkipNodeOperationAll SkipNodeOperation = "*" +) + // CounterSet defines a named set of counters // that are available to be used by devices defined in the // ResourcePool. @@ -225,8 +279,8 @@ type CounterSet struct { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name Name string `json:"name" protobuf:"bytes,1,name=name"` // Counters defines the set of counters for this CounterSet @@ -235,8 +289,8 @@ type CounterSet struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,name=counters"` } @@ -248,6 +302,8 @@ const DriverNameMaxLength = 63 type ResourcePool struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -312,6 +368,10 @@ const ResourceSliceMaxDeviceCounterConsumptionsPerDevice = 2 // per device counter consumption. const ResourceSliceMaxCountersPerDeviceCounterConsumption = 32 +// Defines the maximum number of compatibility groups that can be +// declared per device counter consumption. +const DeviceCompatibilityGroupsMaxSize = 2 + // Device represents one individual hardware instance that can be selected based // on its attributes. Besides the name, exactly one field must be set. type Device struct { @@ -327,7 +387,7 @@ type Device struct { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Attributes map[QualifiedName]DeviceAttribute `json:"attributes,omitempty" protobuf:"bytes,2,rep,name=attributes"` // Capacity defines the set of capacities for this device. @@ -348,13 +408,13 @@ type Device struct { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 ConsumesCounters []DeviceCounterConsumption `json:"consumesCounters,omitempty" protobuf:"bytes,4,rep,name=consumesCounters"` // NodeName identifies the node where the device is available. @@ -401,7 +461,7 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Taints []DeviceTaint `json:"taints,omitempty" protobuf:"bytes,8,rep,name=taints"` // BindsToNode indicates if the usage of an allocation involving this device @@ -431,8 +491,8 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,10,rep,name=bindingConditions"` // BindingFailureConditions defines the conditions for binding failure. @@ -449,8 +509,8 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,11,rep,name=bindingFailureConditions"` // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -462,7 +522,10 @@ type Device struct { // +featureGate=DRAConsumableCapacity AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty" protobuf:"bytes,12,opt,name=allowMultipleAllocations"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResourceMappings is tombstoned as it got replaced with NodeAllocatableResources. + // NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,13,opt,name=nodeAllocatableResourceMappings"` + + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -474,46 +537,104 @@ type Device struct { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,13,opt,name=nodeAllocatableResourceMappings"` + NodeAllocatableResources map[v1.ResourceName]NodeAllocatableResource `json:"nodeAllocatableResources,omitempty" protobuf:"bytes,14,opt,name=nodeAllocatableResources"` } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity +// NodeAllocatableResource defines the translation between the DRA device/capacity // units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMapping struct { +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResource struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + Mapping *NodeAllocatableMapping `json:"mapping,omitempty" protobuf:"bytes,3,opt,name=mapping"` + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + Overhead *NodeAllocatableOverhead `json:"overhead,omitempty" protobuf:"bytes,4,opt,name=overhead"` +} + +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMapping struct { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") CapacityKey *QualifiedName `json:"capacityKey,omitempty" protobuf:"bytes,1,opt,name=capacityKey"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty" protobuf:"bytes,2,opt,name=allocationMultiplier"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty" protobuf:"bytes,2,opt,name=capacityMultiplier"` + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty" protobuf:"bytes,3,opt,name=deviceMultiplier"` +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverhead struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + PerPod *resource.Quantity `json:"perPod,omitempty" protobuf:"bytes,1,opt,name=perPod"` + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + PerContainer *resource.Quantity `json:"perContainer,omitempty" protobuf:"bytes,2,opt,name=perContainer"` } // DeviceCounterConsumption defines a set of counters that @@ -523,8 +644,8 @@ type DeviceCounterConsumption struct { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name CounterSet string `json:"counterSet" protobuf:"bytes,1,opt,name=counterSet"` // Counters defines the counters that will be consumed by the device. @@ -532,9 +653,39 @@ type DeviceCounterConsumption struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,opt,name=counters"` + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + CompatibilityGroups []string `json:"compatibilityGroups,omitempty" protobuf:"bytes,3,rep,name=compatibilityGroups"` } // DeviceCapacity describes a quantity associated with a device. @@ -618,6 +769,13 @@ type CapacityRequestPolicy struct { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -697,30 +855,30 @@ type DeviceAttribute struct { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember IntValue *int64 `json:"int,omitempty" protobuf:"varint,2,opt,name=int"` // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember BoolValue *bool `json:"bool,omitempty" protobuf:"varint,3,opt,name=bool"` // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember StringValue *string `json:"string,omitempty" protobuf:"bytes,4,opt,name=string"` // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember VersionValue *string `json:"version,omitempty" protobuf:"bytes,5,opt,name=version"` // IntValues is a non-empty list of numbers. @@ -730,8 +888,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes IntValues []int64 `json:"ints,omitempty" protobuf:"varint,6,opt,name=ints"` @@ -740,8 +898,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes BoolValues []bool `json:"bools,omitempty" protobuf:"varint,7,opt,name=bools"` @@ -753,8 +911,9 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes StringValues []string `json:"strings,omitempty" protobuf:"bytes,8,opt,name=strings"` @@ -766,8 +925,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes VersionValues []string `json:"versions,omitempty" protobuf:"bytes,9,opt,name=versions"` } @@ -804,7 +963,7 @@ type DeviceTaint struct { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Effect DeviceTaintEffect `json:"effect" protobuf:"bytes,3,name=effect,casttype=DeviceTaintEffect"` // ^^^^ @@ -843,7 +1002,7 @@ type DeviceTaint struct { } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTaintEffect string const ( @@ -859,12 +1018,166 @@ const ( DeviceTaintEffectNoExecute DeviceTaintEffect = "NoExecute" ) +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// DeviceTaintRule adds one taint to all devices which match the selector. +// This has the same effect as if the taint was specified directly +// in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" +type DeviceTaintRule struct { + metav1.TypeMeta `json:""` + // Standard object metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Spec specifies the selector and one taint. + // + // Changing the spec automatically increments the metadata.generation number. + // +required + Spec DeviceTaintRuleSpec `json:"spec" protobuf:"bytes,2,name=spec"` + + // Status provides information about what was requested in the spec. + // + // +optional + Status DeviceTaintRuleStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// DeviceTaintRuleSpec specifies the selector and one taint. +type DeviceTaintRuleSpec struct { + // DeviceSelector defines which device(s) the taint is applied to. + // All selector criteria must be satisfied for a device to + // match. The empty selector matches all devices. Without + // a selector, no devices are matches. + // + // +optional + DeviceSelector *DeviceTaintSelector `json:"deviceSelector,omitempty" protobuf:"bytes,1,opt,name=deviceSelector"` + + // The taint that gets applied to matching devices. + // + // +required + Taint DeviceTaint `json:"taint,omitempty" protobuf:"bytes,2,rep,name=taint"` +} + +// DeviceTaintSelector defines which device(s) a DeviceTaintRule applies to. +// The empty selector matches all devices. Without a selector, no devices +// are matched. +type DeviceTaintSelector struct { + // If DeviceClassName is set, the selectors defined there must be + // satisfied by a device to be selected. This field corresponds + // to class.metadata.name. + // + // +optional + // + // Tombstoned since 1.35 because it turned out that supporting this in all cases + // would depend on copying the device attributes into the ResourceClaim allocation + // result. Without that the eviction controller cannot evaluate these CEL expressions. + // + // DeviceClassName *string `json:"deviceClassName,omitempty" protobuf:"bytes,1,opt,name=deviceClassName"` + + // If driver is set, only devices from that driver are selected. + // This fields corresponds to slice.spec.driver. + // + // +optional + Driver *string `json:"driver,omitempty" protobuf:"bytes,2,opt,name=driver"` + + // If pool is set, only devices in that pool are selected. + // + // Also setting the driver name may be useful to avoid + // ambiguity when different drivers use the same pool name, + // but this is not required because selecting pools from + // different drivers may also be useful, for example when + // drivers with node-local devices use the node name as + // their pool name. + // + // +optional + Pool *string `json:"pool,omitempty" protobuf:"bytes,3,opt,name=pool"` + + // If device is set, only devices with that name are selected. + // This field corresponds to slice.spec.devices[].name. + // + // Setting also driver and pool may be required to avoid ambiguity, + // but is not required. + // + // +optional + Device *string `json:"device,omitempty" protobuf:"bytes,4,opt,name=device"` + + // Selectors contains the same selection criteria as a ResourceClaim. + // Currently, CEL expressions are supported. All of these selectors + // must be satisfied. + // + // +optional + // +listType=atomic + // + // Tombstoned since 1.35 because it turned out that supporting this in all cases + // would depend on copying the device attributes into the ResourceClaim allocation + // result. Without that the eviction controller cannot evaluate these CEL expressions. + // + // Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,5,rep,name=selectors"` +} + +// DeviceTaintRuleStatus provides information about an on-going pod eviction. +type DeviceTaintRuleStatus struct { + // Conditions provide information about the state of the DeviceTaintRule + // and the cluster at some point in time, + // in a machine-readable and human-readable format. + // + // The following condition is currently defined as part of this API, more may + // get added: + // - Type: EvictionInProgress + // - Status: True if there are currently pods which need to be evicted, False otherwise + // (includes the effects which don't cause eviction). + // - Reason: not specified, may change + // - Message: includes information about number of pending pods and already evicted pods + // in a human-readable format, updated periodically, may change + // + // For `effect: None`, the condition above gets set once for each change to + // the spec, with the message containing information about what would happen + // if the effect was `NoExecute`. This feedback can be used to decide whether + // changing the effect to `NoExecute` will work as intended. It only gets + // set once to avoid having to constantly update the status. + // + // Must have 8 or fewer entries. + // + // +optional + // +listType=map + // +listMapKey=type + // +patchStrategy=merge + // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` +} + +// DeviceTaintRuleStatusMaxConditions is the maximum number of conditions in DeviceTaintRuleStatus. +const DeviceTaintRuleStatusMaxConditions = 8 + +// DeviceTaintConditionEvictionInProgress is the publicly documented condition type for the DeviceTaintRuleStatus. +const DeviceTaintConditionEvictionInProgress = "EvictionInProgress" + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// DeviceTaintRuleList is a collection of DeviceTaintRules. +type DeviceTaintRuleList struct { + metav1.TypeMeta `json:""` + // Standard list metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of DeviceTaintRules. + Items []DeviceTaintRule `json:"items" protobuf:"bytes,2,rep,name=items"` +} + // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.34 // ResourceSliceList is a collection of ResourceSlices. type ResourceSliceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -884,14 +1197,15 @@ type ResourceSliceList struct { // stanza tracks whether this claim has been satisfied and what specific // resources have been allocated. type ResourceClaim struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` // Status describes whether the claim is ready to use and what has been allocated. @@ -919,11 +1233,11 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []DeviceRequest `json:"requests" protobuf:"bytes,1,name=requests"` // These constraints must be satisfied by the set of devices that get @@ -931,8 +1245,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Constraints []DeviceConstraint `json:"constraints,omitempty" protobuf:"bytes,2,opt,name=constraints"` // This field holds configuration for multiple potential drivers which @@ -941,8 +1255,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClaimConfiguration `json:"config,omitempty" protobuf:"bytes,3,opt,name=config"` // Potential future extension, ignored by older schedulers. This is @@ -993,7 +1307,7 @@ type DeviceRequest struct { // // +optional // +oneOf=deviceRequestType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Exactly *ExactDeviceRequest `json:"exactly,omitempty" protobuf:"bytes,2,name=exactly"` // FirstAvailable contains subrequests, of which exactly one will be @@ -1014,11 +1328,11 @@ type DeviceRequest struct { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 FirstAvailable []DeviceSubRequest `json:"firstAvailable,omitempty" protobuf:"bytes,3,name=firstAvailable"` } @@ -1046,8 +1360,8 @@ type ExactDeviceRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,2,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1070,7 +1384,7 @@ type ExactDeviceRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,3,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1114,7 +1428,7 @@ type ExactDeviceRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1133,6 +1447,34 @@ type ExactDeviceRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,7,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,8,rep,name=derivedAttributes"` } // DeviceSubRequest describes a request for device provided in the @@ -1166,8 +1508,8 @@ type DeviceSubRequest struct { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name DeviceClassName string `json:"deviceClassName" protobuf:"bytes,2,name=deviceClassName"` // Selectors define criteria which must be satisfied by a specific @@ -1177,8 +1519,8 @@ type DeviceSubRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,3,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1200,7 +1542,7 @@ type DeviceSubRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,4,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1231,7 +1573,7 @@ type DeviceSubRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1250,6 +1592,34 @@ type DeviceSubRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,7,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,8,rep,name=derivedAttributes"` } // CapacityRequirements defines the capacity requirements for a specific device request. @@ -1285,10 +1655,11 @@ const ( DeviceSelectorsMaxSize = 32 FirstAvailableDeviceRequestMaxSize = 8 DeviceTolerationsMaxLength = 16 + DeviceDerivedAttributesMaxSize = 32 ) // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceAllocationMode string // Valid [DeviceRequest.CountMode] values. @@ -1318,7 +1689,7 @@ type CELDeviceSelector struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -1351,6 +1722,15 @@ type CELDeviceSelector struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -1373,6 +1753,61 @@ type CELDeviceSelector struct { Expression string `json:"expression" protobuf:"bytes,1,name=expression"` } +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttribute struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + Name FullyQualifiedName `json:"name" protobuf:"bytes,1,name=name"` + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + Expression string `json:"expression" protobuf:"bytes,2,name=expression"` +} + // CELSelectorExpressionMaxCost specifies the cost limit for a single CEL selector // evaluation. // @@ -1398,6 +1833,25 @@ type CELDeviceSelector struct { // However, this depends on how fast the machine is. const CELSelectorExpressionMaxCost = 1000000 +// DeviceClaimDerivedAttributeCELMaxCost is the maximum combined execution cost +// allowed for all derived attribute CEL expressions within a single DeviceClaim. +// +// During validation, the API server computes the estimated execution cost of each +// derived attribute expression. The sum of these costs across all requests in the +// claim must not exceed this budget. If it does, the claim is rejected. +// +// To stay within the budget, consumers should simplify their CEL expressions, +// avoid computationally expensive operations like deep nesting or iterations +// (such as `.all()` or `.exists()`), and minimize the total number of derived +// attributes in a claim. +// +// This shared budget prevents excessively complex claims from degrading the +// performance of the kube-scheduler. The limit is set to 1,000,000 instruction +// executions (roughly 0.1 seconds of evaluation time), tying the collective +// cost of all derived attributes to the maximum cost allowed for a single +// CEL selector. +const DeviceClaimDerivedAttributeCELMaxCost = 1000000 + // CELSelectorExpressionMaxLength is the maximum length of a CEL selector expression string. const CELSelectorExpressionMaxLength = 10 * 1024 @@ -1415,10 +1869,10 @@ type DeviceConstraint struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` // MatchAttribute requires that all devices in question have this @@ -1441,8 +1895,8 @@ type DeviceConstraint struct { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name MatchAttribute *FullyQualifiedName `json:"matchAttribute,omitempty" protobuf:"bytes,2,opt,name=matchAttribute"` // Potential future extension, not part of the current design: @@ -1474,6 +1928,8 @@ type DeviceConstraint struct { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name DistinctAttribute *FullyQualifiedName `json:"distinctAttribute,omitempty" protobuf:"bytes,3,opt,name=distinctAttribute"` } @@ -1488,13 +1944,13 @@ type DeviceClaimConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,2,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,2,name=deviceConfiguration"` } // DeviceConfiguration must have exactly one field set. It gets embedded @@ -1505,7 +1961,7 @@ type DeviceConfiguration struct { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Opaque *OpaqueDeviceConfiguration `json:"opaque,omitempty" protobuf:"bytes,1,opt,name=opaque"` } @@ -1522,9 +1978,9 @@ type OpaqueDeviceConfiguration struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Driver string `json:"driver" protobuf:"bytes,1,name=driver"` // Parameters can contain arbitrary data. It is the responsibility of @@ -1550,8 +2006,8 @@ type DeviceToleration struct { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key Key string `json:"key,omitempty" protobuf:"bytes,1,opt,name=key"` // Operator represents a key's relationship to the value. @@ -1561,7 +2017,7 @@ type DeviceToleration struct { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Operator DeviceTolerationOperator `json:"operator,omitempty" protobuf:"bytes,2,opt,name=operator,casttype=DeviceTolerationOperator"` // Value is the taint value the toleration matches to. @@ -1575,7 +2031,7 @@ type DeviceToleration struct { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Effect DeviceTaintEffect `json:"effect,omitempty" protobuf:"bytes,4,opt,name=effect,casttype=DeviceTaintEffect"` // TolerationSeconds represents the period of time the toleration (which must be @@ -1592,7 +2048,7 @@ type DeviceToleration struct { // A toleration operator is the set of operators that can be used in a toleration. // // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTolerationOperator string const ( @@ -1606,8 +2062,8 @@ type ResourceClaimStatus struct { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify Allocation *AllocationResult `json:"allocation,omitempty" protobuf:"bytes,1,opt,name=allocation"` // ReservedFor indicates which entities are currently allowed to use @@ -1635,10 +2091,10 @@ type ResourceClaimStatus struct { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 ReservedFor []ResourceClaimConsumerReference `json:"reservedFor,omitempty" protobuf:"bytes,2,opt,name=reservedFor" patchStrategy:"merge" patchMergeKey:"uid"` // DeallocationRequested is tombstoned since Kubernetes 1.32 where @@ -1651,18 +2107,18 @@ type ResourceClaimStatus struct { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID Devices []AllocatedDeviceStatus `json:"devices,omitempty" protobuf:"bytes,4,opt,name=devices"` } @@ -1725,8 +2181,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Results []DeviceRequestAllocationResult `json:"results,omitempty" protobuf:"bytes,1,opt,name=results"` // This field is a combination of all the claim and class configuration parameters. @@ -1739,8 +2195,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 Config []DeviceAllocationConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` } @@ -1769,9 +2225,9 @@ type DeviceRequestAllocationResult struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Driver string `json:"driver" protobuf:"bytes,2,name=driver"` // This name together with the driver name and the device name field @@ -1781,8 +2237,8 @@ type DeviceRequestAllocationResult struct { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name Pool string `json:"pool" protobuf:"bytes,3,name=pool"` // Device references one device instance via its name in the driver's @@ -1813,7 +2269,7 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // BindingConditions contains a copy of the BindingConditions @@ -1825,8 +2281,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,7,rep,name=bindingConditions"` // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1838,8 +2294,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,8,rep,name=bindingFailureConditions"` // ShareID uniquely identifies an individual allocation share of the device, @@ -1849,8 +2305,8 @@ type DeviceRequestAllocationResult struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *types.UID `json:"shareID,omitempty" protobuf:"bytes,9,opt,name=shareID"` // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -1865,6 +2321,19 @@ type DeviceRequestAllocationResult struct { // +optional // +featureGate=DRAConsumableCapacity ConsumedCapacity map[QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty" protobuf:"bytes,10,rep,name=consumedCapacity"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,11,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } // DeviceAllocationConfiguration gets embedded in an AllocationResult. @@ -1874,7 +2343,7 @@ type DeviceAllocationConfiguration struct { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Source AllocationConfigSource `json:"source" protobuf:"bytes,1,name=source"` // Requests lists the names of requests where the configuration applies. @@ -1886,17 +2355,17 @@ type DeviceAllocationConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,2,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,3,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,3,name=deviceConfiguration"` } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type AllocationConfigSource string // Valid [DeviceAllocationConfiguration.Source] values. @@ -1910,7 +2379,7 @@ const ( // ResourceClaimList is a collection of claims. type ResourceClaimList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1929,11 +2398,11 @@ type ResourceClaimList struct { // the device requests of a claim to apply these presets. // Cluster scoped. type DeviceClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines what can be allocated and how to configure it. @@ -1944,6 +2413,7 @@ type DeviceClass struct { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional Spec DeviceClassSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -1954,8 +2424,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,1,opt,name=selectors"` // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -1966,8 +2436,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClassConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` // SuitableNodes is tombstoned since Kubernetes 1.32 where @@ -1984,17 +2454,16 @@ type DeviceClassSpec struct { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name ExtendedResourceName *string `json:"extendedResourceName,omitempty" protobuf:"bytes,4,opt,name=extendedResourceName"` } // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfiguration struct { - DeviceConfiguration `json:",inline" protobuf:"bytes,1,opt,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,1,opt,name=deviceConfiguration"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -2002,7 +2471,7 @@ type DeviceClassConfiguration struct { // DeviceClassList is a collection of classes. type DeviceClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2017,7 +2486,7 @@ type DeviceClassList struct { // ResourceClaimTemplate is used to produce ResourceClaim objects. type ResourceClaimTemplate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2027,6 +2496,7 @@ type ResourceClaimTemplate struct { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional Spec ResourceClaimTemplateSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2036,11 +2506,13 @@ type ResourceClaimTemplateSpec struct { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2049,7 +2521,7 @@ type ResourceClaimTemplateSpec struct { // ResourceClaimTemplateList is a collection of claim templates. type ResourceClaimTemplateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2111,8 +2583,8 @@ type AllocatedDeviceStatus struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *string `json:"shareID,omitempty" protobuf:"bytes,7,opt,name=shareID"` // Conditions contains the latest observation of the device's state. @@ -2124,6 +2596,9 @@ type AllocatedDeviceStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions" protobuf:"bytes,4,opt,name=conditions"` // Data contains arbitrary driver-specific data. @@ -2136,7 +2611,7 @@ type AllocatedDeviceStatus struct { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional NetworkData *NetworkDeviceData `json:"networkData,omitempty" protobuf:"bytes,6,opt,name=networkData"` } @@ -2151,8 +2626,8 @@ type NetworkDeviceData struct { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 InterfaceName string `json:"interfaceName,omitempty" protobuf:"bytes,1,opt,name=interfaceName"` // IPs lists the network addresses assigned to the device's network interface. @@ -2163,10 +2638,10 @@ type NetworkDeviceData struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 IPs []string `json:"ips,omitempty" protobuf:"bytes,2,opt,name=ips"` // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -2174,7 +2649,7 @@ type NetworkDeviceData struct { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 HardwareAddress string `json:"hardwareAddress,omitempty" protobuf:"bytes,3,opt,name=hardwareAddress"` } diff --git a/constraint/vendor/k8s.io/api/resource/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/resource/v1/types_swagger_doc_generated.go index 51915d3e2..2f7c1864d 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/resource/v1/types_swagger_doc_generated.go @@ -55,7 +55,7 @@ func (AllocationResult) SwaggerDoc() map[string]string { var map_CELDeviceSelector = map[string]string{ "": "CELDeviceSelector contains a CEL expression for selecting a device.", - "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\".\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", + "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\").\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nCommon errors: - \"no such key\": Use optional chaining (.? followed by orValue())\n or guarding the check with has() for optional fields.\n See CEL Optional Types for details:\n https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes\n\nFor more CEL expression syntax and examples, see: https://kubernetes.io/docs/reference/using-api/cel/\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", } func (CELDeviceSelector) SwaggerDoc() map[string]string { @@ -74,7 +74,7 @@ func (CapacityRequestPolicy) SwaggerDoc() map[string]string { } var map_CapacityRequestPolicyRange = map[string]string{ - "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", + "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\nIf the DRAFractionalCapacityRange feature gate is enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. its value is not an integer), milli-unit arithmetic is used instead, supporting values with up to 3 decimal places (e.g. 100m = 0.1). The largest supported value then is 1000 times smaller compared to using 64-bit integers. Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value().\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", "min": "Min specifies the minimum capacity allowed for a consumption request.\n\nMin must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum.", "max": "Max defines the upper limit for capacity that can be requested.\n\nMax must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum.", "step": "Step defines the step size between valid capacity amounts within the range.\n\nMax (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value.", @@ -113,20 +113,20 @@ func (CounterSet) SwaggerDoc() map[string]string { } var map_Device = map[string]string{ - "": "Device represents one individual hardware instance that can be selected based on its attributes. Besides the name, exactly one field must be set.", - "name": "Name is unique identifier among all devices managed by the driver in the pool. It must be a DNS label.", - "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", - "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is set to \"True\", a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", - "nodeAllocatableResourceMappings": "NodeAllocatableResourceMappings defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", + "": "Device represents one individual hardware instance that can be selected based on its attributes. Besides the name, exactly one field must be set.", + "name": "Name is unique identifier among all devices managed by the driver in the pool. It must be a DNS label.", + "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", + "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is set to \"True\", a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", + "nodeAllocatableResources": "NodeAllocatableResources defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", } func (Device) SwaggerDoc() map[string]string { @@ -231,7 +231,7 @@ var map_DeviceClassSpec = map[string]string{ "": "DeviceClassSpec is used in a [DeviceClass] to define what can be allocated and how to configure it.", "selectors": "Each selector must be satisfied by a device which is claimed via this class.", "config": "Config defines configuration parameters that apply to each device that is claimed via this class. Some classses may potentially be satisfied by multiple drivers, so each instance of a vendor configuration applies to exactly one driver.\n\nThey are passed to the driver, but are not considered while allocating the claim.", - "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.\n\nThis is a beta field.", + "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.", } func (DeviceClassSpec) SwaggerDoc() map[string]string { @@ -259,15 +259,26 @@ func (DeviceConstraint) SwaggerDoc() map[string]string { } var map_DeviceCounterConsumption = map[string]string{ - "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", - "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", - "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", + "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", + "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "compatibilityGroups": "CompatibilityGroups is a list of opaque group names for this counter set consumption.\n\nDevices that consume counters from the same counter set may only be allocated at the same time (\"co-allocated\") if they all share at least one common group: the intersection of the CompatibilityGroups of all co-allocated devices on that counter set must be non-empty. Devices that consume from different counter sets are never compared via this field.\n\nAn unset field, an explicit nil, and an empty list are equivalent and mean \"no groups\": such a device is only co-allocatable with sibling devices on the same counter set that also have no groups, and is never co-allocatable with a device that declares one or more groups.\n\nGroup names are opaque and meaningful only within the publishing driver's pool.\n\nThe maximum number of groups is 2, and the names must be unique.", } func (DeviceCounterConsumption) SwaggerDoc() map[string]string { return map_DeviceCounterConsumption } +var map_DeviceDerivedAttribute = map[string]string{ + "": "DeviceDerivedAttribute defines a derived attribute computed via CEL.", + "name": "Name is the identifier for this derived attribute, used in constraints.\n\nIt must be a DNS subdomain followed by a slash (\"/\") followed by a C identifier (e.g. \"example.com/numaNode\" or \"derived/numaNode\").\n\nIf the chosen name matches an existing physical attribute from a driver, the derived attribute's expression will shadow the physical attribute, and its evaluated value will be used in constraints instead. When the goal is to define a derived attribute that is only used within the ResourceClaim and not meant to shadow an existing attribute, use a domain prefix that no DRA driver should be using (e.g. \"derived/myAttribute\").\n\nIt is not valid to define a derived attribute that isn't used in at least one constraint.", + "expression": "Expression is a CEL expression evaluated against each candidate device. The expression must evaluate to a primitive scalar (string, integer, boolean, or semver) or a list of these scalars ([]string, []int64, []bool, []semver) to act as a virtual grouping key. Any other return type is an error and causes CEL evaluation for the device to fail.\n\nThe expression's input is an object named \"device\", which carries the same properties as in a CELDeviceSelector.\n\nWhen pod scheduling encounters CEL runtime errors (such as looking up an attribute that isn't defined) for some devices, it will abort allocation and fail scheduling for the Pod. Surfacing evaluation errors immediately prevents silent topology matching failures that are extremely hard to detect. A robust expression should, for example, check for the existence of attributes before referencing them to avoid runtime evaluation errors.\n\nThe expression gets evaluated after a device has passed the other selector expressions for the request in which this expression is used. This allows writing expressions that are tailored towards the specific devices being requested (for example, by assuming the device is from a certain vendor and skipping those checks).\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps; the combined cost of all derived attributes in a claim is capped by a shared CEL cost budget.", +} + +func (DeviceDerivedAttribute) SwaggerDoc() map[string]string { + return map_DeviceDerivedAttribute +} + var map_DeviceRequest = map[string]string{ "": "DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices. With FirstAvailable it is also possible to provide a prioritized list of requests.", "name": "Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.\n\nReferences using the name in the DeviceRequest will uniquely identify a request when the Exactly field is set. When the FirstAvailable field is set, a reference to the name of the DeviceRequest will match whatever subrequest is chosen by the scheduler.\n\nMust be a DNS label.", @@ -291,6 +302,7 @@ var map_DeviceRequestAllocationResult = map[string]string{ "bindingFailureConditions": "BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", "shareID": "ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device.", "consumedCapacity": "ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device’s requestPolicy if applicable (i.e., may not be less than the requested amount).\n\nThe total consumed capacity for each device must not exceed the DeviceCapacity's Value.\n\nThis field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for this allocated device when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. It is a copy of the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated.", } func (DeviceRequestAllocationResult) SwaggerDoc() map[string]string { @@ -307,14 +319,15 @@ func (DeviceSelector) SwaggerDoc() map[string]string { } var map_DeviceSubRequest = map[string]string{ - "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to ExactDeviceRequest, but doesn't expose the AdminAccess field as that one is only supported when requesting a specific device.", - "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to ExactDeviceRequest, but doesn't expose the AdminAccess field as that one is only supported when requesting a specific device.", + "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (DeviceSubRequest) SwaggerDoc() map[string]string { @@ -333,6 +346,57 @@ func (DeviceTaint) SwaggerDoc() map[string]string { return map_DeviceTaint } +var map_DeviceTaintRule = map[string]string{ + "": "DeviceTaintRule adds one taint to all devices which match the selector. This has the same effect as if the taint was specified directly in the ResourceSlice by the DRA driver.", + "metadata": "Standard object metadata", + "spec": "Spec specifies the selector and one taint.\n\nChanging the spec automatically increments the metadata.generation number.", + "status": "Status provides information about what was requested in the spec.", +} + +func (DeviceTaintRule) SwaggerDoc() map[string]string { + return map_DeviceTaintRule +} + +var map_DeviceTaintRuleList = map[string]string{ + "": "DeviceTaintRuleList is a collection of DeviceTaintRules.", + "metadata": "Standard list metadata", + "items": "Items is the list of DeviceTaintRules.", +} + +func (DeviceTaintRuleList) SwaggerDoc() map[string]string { + return map_DeviceTaintRuleList +} + +var map_DeviceTaintRuleSpec = map[string]string{ + "": "DeviceTaintRuleSpec specifies the selector and one taint.", + "deviceSelector": "DeviceSelector defines which device(s) the taint is applied to. All selector criteria must be satisfied for a device to match. The empty selector matches all devices. Without a selector, no devices are matches.", + "taint": "The taint that gets applied to matching devices.", +} + +func (DeviceTaintRuleSpec) SwaggerDoc() map[string]string { + return map_DeviceTaintRuleSpec +} + +var map_DeviceTaintRuleStatus = map[string]string{ + "": "DeviceTaintRuleStatus provides information about an on-going pod eviction.", + "conditions": "Conditions provide information about the state of the DeviceTaintRule and the cluster at some point in time, in a machine-readable and human-readable format.\n\nThe following condition is currently defined as part of this API, more may get added: - Type: EvictionInProgress - Status: True if there are currently pods which need to be evicted, False otherwise\n (includes the effects which don't cause eviction).\n- Reason: not specified, may change - Message: includes information about number of pending pods and already evicted pods\n in a human-readable format, updated periodically, may change\n\nFor `effect: None`, the condition above gets set once for each change to the spec, with the message containing information about what would happen if the effect was `NoExecute`. This feedback can be used to decide whether changing the effect to `NoExecute` will work as intended. It only gets set once to avoid having to constantly update the status.\n\nMust have 8 or fewer entries.", +} + +func (DeviceTaintRuleStatus) SwaggerDoc() map[string]string { + return map_DeviceTaintRuleStatus +} + +var map_DeviceTaintSelector = map[string]string{ + "": "DeviceTaintSelector defines which device(s) a DeviceTaintRule applies to. The empty selector matches all devices. Without a selector, no devices are matched.", + "driver": "If driver is set, only devices from that driver are selected. This fields corresponds to slice.spec.driver.", + "pool": "If pool is set, only devices in that pool are selected.\n\nAlso setting the driver name may be useful to avoid ambiguity when different drivers use the same pool name, but this is not required because selecting pools from different drivers may also be useful, for example when drivers with node-local devices use the node name as their pool name.", + "device": "If device is set, only devices with that name are selected. This field corresponds to slice.spec.devices[].name.\n\nSetting also driver and pool may be required to avoid ambiguity, but is not required.", +} + +func (DeviceTaintSelector) SwaggerDoc() map[string]string { + return map_DeviceTaintSelector +} + var map_DeviceToleration = map[string]string{ "": "The ResourceClaim this DeviceToleration is attached to tolerates any taint that matches the triple using the matching operator .", "key": "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. Must be a label name.", @@ -347,14 +411,15 @@ func (DeviceToleration) SwaggerDoc() map[string]string { } var map_ExactDeviceRequest = map[string]string{ - "": "ExactDeviceRequest is a request for one or more identical devices.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA DeviceClassName is required.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", - "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nAdmin access is disabled if this field is unset or set to false, otherwise it is enabled.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "ExactDeviceRequest is a request for one or more identical devices.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA DeviceClassName is required.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nAdmin access is disabled if this field is unset or set to false, otherwise it is enabled.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (ExactDeviceRequest) SwaggerDoc() map[string]string { @@ -372,14 +437,35 @@ func (NetworkDeviceData) SwaggerDoc() map[string]string { return map_NetworkDeviceData } -var map_NodeAllocatableResourceMapping = map[string]string{ - "": "NodeAllocatableResourceMapping defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource.", - "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. If `allocationMultiplier` is also set, it is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\", and `allocationMultiplier` should be omitted or set to \"1\".", - "allocationMultiplier": "AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim.\n\t a. A DRA driver representing each CPU core as a device would have\n {ResourceName: \"cpu\", allocationMultiplier: \"2\"} in its\n `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim,\n\t\t 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity.\n b. A GPU device that needs additional node memory per GPU allocation would\n have {ResourceName: \"memory\", allocationMultiplier: \"2Gi\"}. Each allocated\n\t\t GPU device instance of this type will account for 2Gi of memory.\n\n2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed.\n\t The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`.\n For example, if a Device's capacity \"dra.example.com/cores\" is consumed,\n and each \"core\" provides 2 \"cpu\"s, the mapping would be:\n {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", allocationMultiplier: \"2\"}.\n If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", +var map_NodeAllocatableMapping = map[string]string{ + "": "NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim.", + "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. `capacityMultiplier` must also be set and is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\". The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`.", + "capacityMultiplier": "CapacityMultiplier is used as a multiplier for the allocated capacity consumed. It is only valid if `capacityKey` is set. The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. For example, if a Device's capacity \"dra.example.com/cores\" is consumed, and each \"core\" provides 2 \"cpu\"s, the mapping would be: {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", capacityMultiplier: \"2\"}. If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", + "deviceMultiplier": "DeviceMultiplier is used as a multiplier for the allocated device count in the claim. The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. For example, a DRA driver representing each cache complex (CCX) as a device would have {ResourceName: \"cpu\", deviceMultiplier: \"8\"} in its `nodeAllocatableResources`. If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. It is only valid when `capacityKey` and `capacityMultiplier` are not set.", +} + +func (NodeAllocatableMapping) SwaggerDoc() map[string]string { + return map_NodeAllocatableMapping +} + +var map_NodeAllocatableOverhead = map[string]string{ + "": "NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers.", + "perPod": "PerPod is overhead applied once per pod referencing the claim on this node. This is a flat overhead incurred for every pod referencing the claim.", + "perContainer": "PerContainer is applied per container reference to the claim. This models overhead scaling linearly with the number of containers actively using the device. When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing the claim is computed as: Quantity = PerPod + (PerContainer * NumReferences) Kubelet accounts for this overhead in cgroups: - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once.", +} + +func (NodeAllocatableOverhead) SwaggerDoc() map[string]string { + return map_NodeAllocatableOverhead +} + +var map_NodeAllocatableResource = map[string]string{ + "": "NodeAllocatableResource defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource. At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration.", + "mapping": "Mapping is used when the device directly models a node allocatable resource like standard CPU or memory (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance on the node. To prevent node cgroup isolation friction, the scheduler explicitly blocks sharing mapped device claims across multiple pods.", + "overhead": "Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted for individually for each pod referencing the claim. Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping is specified for the same resource. Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), any overhead specified for the same resource will be subtracted from the node's general allocatable capacity and not from the per-socket capacity pool in Mapping.", } -func (NodeAllocatableResourceMapping) SwaggerDoc() map[string]string { - return map_NodeAllocatableResourceMapping +func (NodeAllocatableResource) SwaggerDoc() map[string]string { + return map_NodeAllocatableResource } var map_OpaqueDeviceConfiguration = map[string]string{ @@ -477,7 +563,7 @@ func (ResourceClaimTemplateSpec) SwaggerDoc() map[string]string { var map_ResourcePool = map[string]string{ "": "ResourcePool describes the pool that ResourceSlices belong to.", - "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", + "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required. A field selector can be used to list only ResourceSlice objects belonging to a certain pool.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", "generation": "Generation tracks the change in a pool over time. Whenever a driver changes something about one or more of the resources in a pool, it must change the generation in all ResourceSlices which are part of that pool. Consumers of ResourceSlices should only consider resources from the pool with the highest generation number. The generation may be reset by drivers, which should be fine for consumers, assuming that all ResourceSlices in a pool are updated to match or deleted.\n\nCombined with ResourceSliceCount, this mechanism enables consumers to detect pools which are comprised of multiple ResourceSlices and are in an incomplete state.", "resourceSliceCount": "ResourceSliceCount is the total number of ResourceSlices in the pool at this generation number. Must be greater than zero.\n\nConsumers can use this to check whether they have seen all ResourceSlices belonging to the same pool.", } @@ -516,6 +602,8 @@ var map_ResourceSliceSpec = map[string]string{ "devices": "Devices lists some or all of the devices in this pool.\n\nMust not have more than 128 entries. If any device uses taints or consumes counters the limit is 64.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.", "perDeviceNodeSelection": "PerDeviceNodeSelection defines whether the access from nodes to resources in the pool is set on the ResourceSlice level or on each device. If it is set to true, every device defined the ResourceSlice must specify this individually.\n\nExactly one of NodeName, NodeSelector, AllNodes, and PerDeviceNodeSelection must be set.", "sharedCounters": "SharedCounters defines a list of counter sets, each of which has a name and a list of counters available.\n\nThe names of the counter sets must be unique in the ResourcePool.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.\n\nThe maximum number of counter sets is 8.", + "partitionTypeAttribute": "PartitionTypeAttribute names a string device attribute (by fully qualified name, e.g. \"gpu.example.com/profile\") whose value labels each device with its partition type, such as \"Full\" or \"Half\" for a MIG-style GPU.\n\nWhen set, every partitionable device in the slice must carry the attribute and devices sharing a value must share the same ConsumesCounters cost.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for the devices in this slice when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. Valid values are:\n\n- \"NodePrepareResources\": NodePrepareResources gRPC calls are skipped. This\n value cannot be specified unless \"NodeUnprepareResources\" is also listed\n (or \"*\" is specified).\n- \"NodeUnprepareResources\": NodeUnprepareResources gRPC calls are skipped. - \"*\": All node-local resource operations are skipped.\n\nOther values may be added in the future. The kubelet must ignore unknown values.", } func (ResourceSliceSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.deepcopy.go index 0c488a05a..923193484 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.deepcopy.go @@ -302,9 +302,9 @@ func (in *Device) DeepCopyInto(out *Device) { *out = new(bool) **out = **in } - if in.NodeAllocatableResourceMappings != nil { - in, out := &in.NodeAllocatableResourceMappings, &out.NodeAllocatableResourceMappings - *out = make(map[corev1.ResourceName]NodeAllocatableResourceMapping, len(*in)) + if in.NodeAllocatableResources != nil { + in, out := &in.NodeAllocatableResources, &out.NodeAllocatableResources + *out = make(map[corev1.ResourceName]NodeAllocatableResource, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -685,6 +685,11 @@ func (in *DeviceCounterConsumption) DeepCopyInto(out *DeviceCounterConsumption) (*out)[key] = *val.DeepCopy() } } + if in.CompatibilityGroups != nil { + in, out := &in.CompatibilityGroups, &out.CompatibilityGroups + *out = make([]string, len(*in)) + copy(*out, *in) + } return } @@ -698,6 +703,22 @@ func (in *DeviceCounterConsumption) DeepCopy() *DeviceCounterConsumption { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceDerivedAttribute) DeepCopyInto(out *DeviceDerivedAttribute) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceDerivedAttribute. +func (in *DeviceDerivedAttribute) DeepCopy() *DeviceDerivedAttribute { + if in == nil { + return nil + } + out := new(DeviceDerivedAttribute) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeviceRequest) DeepCopyInto(out *DeviceRequest) { *out = *in @@ -763,6 +784,11 @@ func (in *DeviceRequestAllocationResult) DeepCopyInto(out *DeviceRequestAllocati (*out)[key] = val.DeepCopy() } } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } @@ -819,6 +845,11 @@ func (in *DeviceSubRequest) DeepCopyInto(out *DeviceSubRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -852,6 +883,143 @@ func (in *DeviceTaint) DeepCopy() *DeviceTaint { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceTaintRule) DeepCopyInto(out *DeviceTaintRule) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceTaintRule. +func (in *DeviceTaintRule) DeepCopy() *DeviceTaintRule { + if in == nil { + return nil + } + out := new(DeviceTaintRule) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DeviceTaintRule) 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 *DeviceTaintRuleList) DeepCopyInto(out *DeviceTaintRuleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DeviceTaintRule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceTaintRuleList. +func (in *DeviceTaintRuleList) DeepCopy() *DeviceTaintRuleList { + if in == nil { + return nil + } + out := new(DeviceTaintRuleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *DeviceTaintRuleList) 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 *DeviceTaintRuleSpec) DeepCopyInto(out *DeviceTaintRuleSpec) { + *out = *in + if in.DeviceSelector != nil { + in, out := &in.DeviceSelector, &out.DeviceSelector + *out = new(DeviceTaintSelector) + (*in).DeepCopyInto(*out) + } + in.Taint.DeepCopyInto(&out.Taint) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceTaintRuleSpec. +func (in *DeviceTaintRuleSpec) DeepCopy() *DeviceTaintRuleSpec { + if in == nil { + return nil + } + out := new(DeviceTaintRuleSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceTaintRuleStatus) DeepCopyInto(out *DeviceTaintRuleStatus) { + *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]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceTaintRuleStatus. +func (in *DeviceTaintRuleStatus) DeepCopy() *DeviceTaintRuleStatus { + if in == nil { + return nil + } + out := new(DeviceTaintRuleStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceTaintSelector) DeepCopyInto(out *DeviceTaintSelector) { + *out = *in + if in.Driver != nil { + in, out := &in.Driver, &out.Driver + *out = new(string) + **out = **in + } + if in.Pool != nil { + in, out := &in.Pool, &out.Pool + *out = new(string) + **out = **in + } + if in.Device != nil { + in, out := &in.Device, &out.Device + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceTaintSelector. +func (in *DeviceTaintSelector) DeepCopy() *DeviceTaintSelector { + if in == nil { + return nil + } + out := new(DeviceTaintSelector) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeviceToleration) DeepCopyInto(out *DeviceToleration) { *out = *in @@ -900,6 +1068,11 @@ func (in *ExactDeviceRequest) DeepCopyInto(out *ExactDeviceRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -935,27 +1108,84 @@ func (in *NetworkDeviceData) DeepCopy() *NetworkDeviceData { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NodeAllocatableResourceMapping) DeepCopyInto(out *NodeAllocatableResourceMapping) { +func (in *NodeAllocatableMapping) DeepCopyInto(out *NodeAllocatableMapping) { *out = *in if in.CapacityKey != nil { in, out := &in.CapacityKey, &out.CapacityKey *out = new(QualifiedName) **out = **in } - if in.AllocationMultiplier != nil { - in, out := &in.AllocationMultiplier, &out.AllocationMultiplier + if in.CapacityMultiplier != nil { + in, out := &in.CapacityMultiplier, &out.CapacityMultiplier + x := (*in).DeepCopy() + *out = &x + } + if in.DeviceMultiplier != nil { + in, out := &in.DeviceMultiplier, &out.DeviceMultiplier x := (*in).DeepCopy() *out = &x } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResourceMapping. -func (in *NodeAllocatableResourceMapping) DeepCopy() *NodeAllocatableResourceMapping { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableMapping. +func (in *NodeAllocatableMapping) DeepCopy() *NodeAllocatableMapping { if in == nil { return nil } - out := new(NodeAllocatableResourceMapping) + out := new(NodeAllocatableMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableOverhead) DeepCopyInto(out *NodeAllocatableOverhead) { + *out = *in + if in.PerPod != nil { + in, out := &in.PerPod, &out.PerPod + x := (*in).DeepCopy() + *out = &x + } + if in.PerContainer != nil { + in, out := &in.PerContainer, &out.PerContainer + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableOverhead. +func (in *NodeAllocatableOverhead) DeepCopy() *NodeAllocatableOverhead { + if in == nil { + return nil + } + out := new(NodeAllocatableOverhead) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableResource) DeepCopyInto(out *NodeAllocatableResource) { + *out = *in + if in.Mapping != nil { + in, out := &in.Mapping, &out.Mapping + *out = new(NodeAllocatableMapping) + (*in).DeepCopyInto(*out) + } + if in.Overhead != nil { + in, out := &in.Overhead, &out.Overhead + *out = new(NodeAllocatableOverhead) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResource. +func (in *NodeAllocatableResource) DeepCopy() *NodeAllocatableResource { + if in == nil { + return nil + } + out := new(NodeAllocatableResource) in.DeepCopyInto(out) return out } @@ -1296,6 +1526,16 @@ func (in *ResourceSliceSpec) DeepCopyInto(out *ResourceSliceSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.PartitionTypeAttribute != nil { + in, out := &in.PartitionTypeAttribute, &out.PartitionTypeAttribute + *out = new(FullyQualifiedName) + **out = **in + } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } diff --git a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.model_name.go index f163c61ed..aa13541c2 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.model_name.go @@ -131,6 +131,11 @@ func (in DeviceCounterConsumption) OpenAPIModelName() string { return "io.k8s.api.resource.v1.DeviceCounterConsumption" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceDerivedAttribute) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceDerivedAttribute" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in DeviceRequest) OpenAPIModelName() string { return "io.k8s.api.resource.v1.DeviceRequest" @@ -156,6 +161,31 @@ func (in DeviceTaint) OpenAPIModelName() string { return "io.k8s.api.resource.v1.DeviceTaint" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceTaintRule) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceTaintRule" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceTaintRuleList) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceTaintRuleList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceTaintRuleSpec) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceTaintRuleSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceTaintRuleStatus) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceTaintRuleStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceTaintSelector) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.DeviceTaintSelector" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in DeviceToleration) OpenAPIModelName() string { return "io.k8s.api.resource.v1.DeviceToleration" @@ -172,8 +202,18 @@ func (in NetworkDeviceData) OpenAPIModelName() string { } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in NodeAllocatableResourceMapping) OpenAPIModelName() string { - return "io.k8s.api.resource.v1.NodeAllocatableResourceMapping" +func (in NodeAllocatableMapping) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.NodeAllocatableMapping" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableOverhead) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.NodeAllocatableOverhead" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableResource) OpenAPIModelName() string { + return "io.k8s.api.resource.v1.NodeAllocatableResource" } // OpenAPIModelName returns the OpenAPI model name for this type. diff --git a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.prerelease-lifecycle.go index dbf5b3ccd..4c36f2715 100644 --- a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.prerelease-lifecycle.go @@ -33,6 +33,18 @@ func (in *DeviceClassList) APILifecycleIntroduced() (major, minor int) { return 1, 34 } +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *DeviceTaintRule) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *DeviceTaintRuleList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *ResourceClaim) APILifecycleIntroduced() (major, minor int) { diff --git a/constraint/vendor/k8s.io/api/resource/v1/zz_generated.validations.go b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.validations.go new file mode 100644 index 000000000..b771d5b92 --- /dev/null +++ b/constraint/vendor/k8s.io/api/resource/v1/zz_generated.validations.go @@ -0,0 +1,3348 @@ +//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 validation-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + corev1 "k8s.io/api/core/v1" + equality "k8s.io/apimachinery/pkg/api/equality" + operation "k8s.io/apimachinery/pkg/api/operation" + resource "k8s.io/apimachinery/pkg/api/resource" + safe "k8s.io/apimachinery/pkg/api/safe" + validate "k8s.io/apimachinery/pkg/api/validate" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + types "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + field "k8s.io/apimachinery/pkg/util/validation/field" +) + +// Validate_AllocatedDeviceStatus validates an instance of AllocatedDeviceStatus according +// to declarative validation rules in the API schema. +func Validate_AllocatedDeviceStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *AllocatedDeviceStatus) (errs field.ErrorList) { + + // field AllocatedDeviceStatus.Driver has no validation + // field AllocatedDeviceStatus.Pool has no validation + // field AllocatedDeviceStatus.Device has no validation + + { // field AllocatedDeviceStatus.ShareID + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *AllocatedDeviceStatus) *string { + return oldObj.ShareID + }) + errs = append(errs, fn(fldPath.Child("shareID"), obj.ShareID, oldVal, oldObj != nil)...) + } + + { // field AllocatedDeviceStatus.Conditions + fn := func( + fldPath *field.Path, + obj, oldObj []metav1.Condition, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *metav1.Condition, b *metav1.Condition) bool { return a.Type == b.Type }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *metav1.Condition, b *metav1.Condition) bool { return a.Type == b.Type }, validate.SemanticDeepEqual, validation.Validate_Condition); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *AllocatedDeviceStatus) []metav1.Condition { + return oldObj.Conditions + }) + errs = append(errs, fn(fldPath.Child("conditions"), obj.Conditions, oldVal, oldObj != nil)...) + } + + // field AllocatedDeviceStatus.Data has no validation + + { // field AllocatedDeviceStatus.NetworkData + fn := func( + fldPath *field.Path, + obj, oldObj *NetworkDeviceData, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_NetworkDeviceData(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *AllocatedDeviceStatus) *NetworkDeviceData { + return oldObj.NetworkData + }) + errs = append(errs, fn(fldPath.Child("networkData"), obj.NetworkData, oldVal, oldObj != nil)...) + } + + return errs +} + +var symbolsForAllocationConfigSource = sets.New(AllocationConfigSourceClaim, AllocationConfigSourceClass) + +// Validate_AllocationConfigSource validates an instance of AllocationConfigSource according +// to declarative validation rules in the API schema. +func Validate_AllocationConfigSource( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *AllocationConfigSource) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForAllocationConfigSource, nil).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_AllocationResult validates an instance of AllocationResult according +// to declarative validation rules in the API schema. +func Validate_AllocationResult( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *AllocationResult) (errs field.ErrorList) { + + { // field AllocationResult.Devices + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceAllocationResult, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceAllocationResult(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *AllocationResult) *DeviceAllocationResult { + return &oldObj.Devices + }) + errs = append(errs, fn(fldPath.Child("devices"), &obj.Devices, oldVal, oldObj != nil)...) + } + + // field AllocationResult.NodeSelector has no validation + // field AllocationResult.AllocationTimestamp has no validation + return errs +} + +// Validate_CounterSet validates an instance of CounterSet according +// to declarative validation rules in the API schema. +func Validate_CounterSet( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CounterSet) (errs field.ErrorList) { + + { // field CounterSet.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CounterSet) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field CounterSet.Counters + fn := func( + fldPath *field.Path, + obj, oldObj map[string]Counter, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredMap(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.EachMapKey(ctx, op, fldPath, obj, oldObj, validate.ShortName).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CounterSet) map[string]Counter { + return oldObj.Counters + }) + errs = append(errs, fn(fldPath.Child("counters"), obj.Counters, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_Device validates an instance of Device according +// to declarative validation rules in the API schema. +func Validate_Device( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *Device) (errs field.ErrorList) { + + // field Device.Name has no validation + + { // field Device.Attributes + fn := func( + fldPath *field.Path, + obj, oldObj map[QualifiedName]DeviceAttribute, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the map and call the value type's validation function + if e := validate.EachMapVal(ctx, op, fldPath, obj, oldObj, validate.SemanticDeepEqual, Validate_DeviceAttribute); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) map[QualifiedName]DeviceAttribute { + return oldObj.Attributes + }) + errs = append(errs, fn(fldPath.Child("attributes"), obj.Attributes, oldVal, oldObj != nil)...) + } + + // field Device.Capacity has no validation + + { // field Device.ConsumesCounters + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceCounterConsumption, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 2).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *DeviceCounterConsumption, b *DeviceCounterConsumption) bool { + return a.CounterSet == b.CounterSet + }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *DeviceCounterConsumption, b *DeviceCounterConsumption) bool { + return a.CounterSet == b.CounterSet + }, validate.SemanticDeepEqual, Validate_DeviceCounterConsumption); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) []DeviceCounterConsumption { + return oldObj.ConsumesCounters + }) + errs = append(errs, fn(fldPath.Child("consumesCounters"), obj.ConsumesCounters, oldVal, oldObj != nil)...) + } + + // field Device.NodeName has no validation + // field Device.NodeSelector has no validation + // field Device.AllNodes has no validation + + { // field Device.Taints + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceTaint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceTaint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) []DeviceTaint { + return oldObj.Taints + }) + errs = append(errs, fn(fldPath.Child("taints"), obj.Taints, oldVal, oldObj != nil)...) + } + + // field Device.BindsToNode has no validation + + { // field Device.BindingConditions + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) []string { + return oldObj.BindingConditions + }) + errs = append(errs, fn(fldPath.Child("bindingConditions"), obj.BindingConditions, oldVal, oldObj != nil)...) + } + + { // field Device.BindingFailureConditions + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) []string { + return oldObj.BindingFailureConditions + }) + errs = append(errs, fn(fldPath.Child("bindingFailureConditions"), obj.BindingFailureConditions, oldVal, oldObj != nil)...) + } + + // field Device.AllowMultipleAllocations has no validation + + { // field Device.NodeAllocatableResources + fn := func( + fldPath *field.Path, + obj, oldObj map[corev1.ResourceName]NodeAllocatableResource, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the map and call the value type's validation function + if e := validate.EachMapVal(ctx, op, fldPath, obj, oldObj, validate.SemanticDeepEqual, Validate_NodeAllocatableResource); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Device) map[corev1.ResourceName]NodeAllocatableResource { + return oldObj.NodeAllocatableResources + }) + errs = append(errs, fn(fldPath.Child("nodeAllocatableResources"), obj.NodeAllocatableResources, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceAllocationConfiguration validates an instance of DeviceAllocationConfiguration according +// to declarative validation rules in the API schema. +func Validate_DeviceAllocationConfiguration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceAllocationConfiguration) (errs field.ErrorList) { + + { // field DeviceAllocationConfiguration.Source + fn := func( + fldPath *field.Path, + obj, oldObj *AllocationConfigSource, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_AllocationConfigSource(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAllocationConfiguration) *AllocationConfigSource { + return &oldObj.Source + }) + errs = append(errs, fn(fldPath.Child("source"), &obj.Source, oldVal, oldObj != nil)...) + } + + { // field DeviceAllocationConfiguration.Requests + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAllocationConfiguration) []string { + return oldObj.Requests + }) + errs = append(errs, fn(fldPath.Child("requests"), obj.Requests, oldVal, oldObj != nil)...) + } + + { // field DeviceAllocationConfiguration.DeviceConfiguration + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceConfiguration(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAllocationConfiguration) *DeviceConfiguration { + return &oldObj.DeviceConfiguration + }) + errs = append(errs, fn(safe.Value(fldPath, func() *field.Path { return fldPath.Child("DeviceConfiguration") }), &obj.DeviceConfiguration, oldVal, oldObj != nil)...) + } + + return errs +} + +var symbolsForDeviceAllocationMode = sets.New(DeviceAllocationModeAll, DeviceAllocationModeExactCount) + +// Validate_DeviceAllocationMode validates an instance of DeviceAllocationMode according +// to declarative validation rules in the API schema. +func Validate_DeviceAllocationMode( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceAllocationMode) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForDeviceAllocationMode, nil).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_DeviceAllocationResult validates an instance of DeviceAllocationResult according +// to declarative validation rules in the API schema. +func Validate_DeviceAllocationResult( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceAllocationResult) (errs field.ErrorList) { + + { // field DeviceAllocationResult.Results + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceRequestAllocationResult, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceRequestAllocationResult); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAllocationResult) []DeviceRequestAllocationResult { + return oldObj.Results + }) + errs = append(errs, fn(fldPath.Child("results"), obj.Results, oldVal, oldObj != nil)...) + } + + { // field DeviceAllocationResult.Config + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceAllocationConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 64).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceAllocationConfiguration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAllocationResult) []DeviceAllocationConfiguration { + return oldObj.Config + }) + errs = append(errs, fn(fldPath.Child("config"), obj.Config, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_resource_v1_DeviceAttribute_ = validate.NewUnionMembership(validate.NewUnionMember("int"), validate.NewUnionMember("bool"), validate.NewUnionMember("string"), validate.NewUnionMember("version"), validate.NewUnionMember("ints"), validate.NewUnionMember("bools"), validate.NewUnionMember("strings"), validate.NewUnionMember("versions")) + +// Validate_DeviceAttribute validates an instance of DeviceAttribute according +// to declarative validation rules in the API schema. +func Validate_DeviceAttribute( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceAttribute) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_resource_v1_DeviceAttribute_, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return obj.IntValue != nil + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return obj.BoolValue != nil + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return obj.StringValue != nil + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return obj.VersionValue != nil + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return len(obj.IntValues) != 0 + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return len(obj.BoolValues) != 0 + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return len(obj.StringValues) != 0 + }, + func(obj *DeviceAttribute) bool { + if obj == nil { + return false + } + return len(obj.VersionValues) != 0 + }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + + { // field DeviceAttribute.IntValue + fn := func( + fldPath *field.Path, + obj, oldObj *int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) *int64 { + return oldObj.IntValue + }) + errs = append(errs, fn(fldPath.Child("int"), obj.IntValue, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.BoolValue + fn := func( + fldPath *field.Path, + obj, oldObj *bool, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) *bool { + return oldObj.BoolValue + }) + errs = append(errs, fn(fldPath.Child("bool"), obj.BoolValue, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.StringValue + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) *string { + return oldObj.StringValue + }) + errs = append(errs, fn(fldPath.Child("string"), obj.StringValue, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.VersionValue + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) *string { + return oldObj.VersionValue + }) + errs = append(errs, fn(fldPath.Child("version"), obj.VersionValue, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.IntValues + fn := func( + fldPath *field.Path, + obj, oldObj []int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) []int64 { + return oldObj.IntValues + }) + errs = append(errs, fn(fldPath.Child("ints"), obj.IntValues, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.BoolValues + fn := func( + fldPath *field.Path, + obj, oldObj []bool, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) []bool { + return oldObj.BoolValues + }) + errs = append(errs, fn(fldPath.Child("bools"), obj.BoolValues, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.StringValues + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxBytes(ctx, op, fldPath, obj, oldObj, 64) + }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) []string { + return oldObj.StringValues + }) + errs = append(errs, fn(fldPath.Child("strings"), obj.StringValues, oldVal, oldObj != nil)...) + } + + { // field DeviceAttribute.VersionValues + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceAttribute) []string { + return oldObj.VersionValues + }) + errs = append(errs, fn(fldPath.Child("versions"), obj.VersionValues, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceClaim validates an instance of DeviceClaim according +// to declarative validation rules in the API schema. +func Validate_DeviceClaim( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceClaim) (errs field.ErrorList) { + + { // field DeviceClaim.Requests + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceRequest, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *DeviceRequest, b *DeviceRequest) bool { return a.Name == b.Name }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *DeviceRequest, b *DeviceRequest) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_DeviceRequest); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClaim) []DeviceRequest { + return oldObj.Requests + }) + errs = append(errs, fn(fldPath.Child("requests"), obj.Requests, oldVal, oldObj != nil)...) + } + + { // field DeviceClaim.Constraints + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceConstraint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceConstraint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClaim) []DeviceConstraint { + return oldObj.Constraints + }) + errs = append(errs, fn(fldPath.Child("constraints"), obj.Constraints, oldVal, oldObj != nil)...) + } + + { // field DeviceClaim.Config + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceClaimConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceClaimConfiguration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClaim) []DeviceClaimConfiguration { + return oldObj.Config + }) + errs = append(errs, fn(fldPath.Child("config"), obj.Config, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceClaimConfiguration validates an instance of DeviceClaimConfiguration according +// to declarative validation rules in the API schema. +func Validate_DeviceClaimConfiguration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceClaimConfiguration) (errs field.ErrorList) { + + { // field DeviceClaimConfiguration.Requests + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClaimConfiguration) []string { + return oldObj.Requests + }) + errs = append(errs, fn(fldPath.Child("requests"), obj.Requests, oldVal, oldObj != nil)...) + } + + { // field DeviceClaimConfiguration.DeviceConfiguration + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceConfiguration(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClaimConfiguration) *DeviceConfiguration { + return &oldObj.DeviceConfiguration + }) + errs = append(errs, fn(safe.Value(fldPath, func() *field.Path { return fldPath.Child("DeviceConfiguration") }), &obj.DeviceConfiguration, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceClassConfiguration validates an instance of DeviceClassConfiguration according +// to declarative validation rules in the API schema. +func Validate_DeviceClassConfiguration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceClassConfiguration) (errs field.ErrorList) { + + { // field DeviceClassConfiguration.DeviceConfiguration + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceConfiguration(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClassConfiguration) *DeviceConfiguration { + return &oldObj.DeviceConfiguration + }) + errs = append(errs, fn(safe.Value(fldPath, func() *field.Path { return fldPath.Child("DeviceConfiguration") }), &obj.DeviceConfiguration, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceClassSpec validates an instance of DeviceClassSpec according +// to declarative validation rules in the API schema. +func Validate_DeviceClassSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceClassSpec) (errs field.ErrorList) { + + { // field DeviceClassSpec.Selectors + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceSelector, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClassSpec) []DeviceSelector { + return oldObj.Selectors + }) + errs = append(errs, fn(fldPath.Child("selectors"), obj.Selectors, oldVal, oldObj != nil)...) + } + + { // field DeviceClassSpec.Config + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceClassConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceClassConfiguration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClassSpec) []DeviceClassConfiguration { + return oldObj.Config + }) + errs = append(errs, fn(fldPath.Child("config"), obj.Config, oldVal, oldObj != nil)...) + } + + { // field DeviceClassSpec.ExtendedResourceName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ExtendedResourceName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceClassSpec) *string { + return oldObj.ExtendedResourceName + }) + errs = append(errs, fn(fldPath.Child("extendedResourceName"), obj.ExtendedResourceName, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceConfiguration validates an instance of DeviceConfiguration according +// to declarative validation rules in the API schema. +func Validate_DeviceConfiguration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceConfiguration) (errs field.ErrorList) { + + { // field DeviceConfiguration.Opaque + fn := func( + fldPath *field.Path, + obj, oldObj *OpaqueDeviceConfiguration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_OpaqueDeviceConfiguration(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceConfiguration) *OpaqueDeviceConfiguration { + return oldObj.Opaque + }) + errs = append(errs, fn(fldPath.Child("opaque"), obj.Opaque, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceConstraint validates an instance of DeviceConstraint according +// to declarative validation rules in the API schema. +func Validate_DeviceConstraint( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceConstraint) (errs field.ErrorList) { + + { // field DeviceConstraint.Requests + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceConstraint) []string { + return oldObj.Requests + }) + errs = append(errs, fn(fldPath.Child("requests"), obj.Requests, oldVal, oldObj != nil)...) + } + + { // field DeviceConstraint.MatchAttribute + fn := func( + fldPath *field.Path, + obj, oldObj *FullyQualifiedName, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ResourceFullyQualifiedName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceConstraint) *FullyQualifiedName { + return oldObj.MatchAttribute + }) + errs = append(errs, fn(fldPath.Child("matchAttribute"), obj.MatchAttribute, oldVal, oldObj != nil)...) + } + + { // field DeviceConstraint.DistinctAttribute + fn := func( + fldPath *field.Path, + obj, oldObj *FullyQualifiedName, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ResourceFullyQualifiedName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceConstraint) *FullyQualifiedName { + return oldObj.DistinctAttribute + }) + errs = append(errs, fn(fldPath.Child("distinctAttribute"), obj.DistinctAttribute, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceCounterConsumption validates an instance of DeviceCounterConsumption according +// to declarative validation rules in the API schema. +func Validate_DeviceCounterConsumption( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceCounterConsumption) (errs field.ErrorList) { + + { // field DeviceCounterConsumption.CounterSet + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceCounterConsumption) *string { + return &oldObj.CounterSet + }) + errs = append(errs, fn(fldPath.Child("counterSet"), &obj.CounterSet, oldVal, oldObj != nil)...) + } + + { // field DeviceCounterConsumption.Counters + fn := func( + fldPath *field.Path, + obj, oldObj map[string]Counter, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredMap(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.EachMapKey(ctx, op, fldPath, obj, oldObj, validate.ShortName).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceCounterConsumption) map[string]Counter { + return oldObj.Counters + }) + errs = append(errs, fn(fldPath.Child("counters"), obj.Counters, oldVal, oldObj != nil)...) + } + + { // field DeviceCounterConsumption.CompatibilityGroups + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 2).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, validate.ShortName); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceCounterConsumption) []string { + return oldObj.CompatibilityGroups + }) + errs = append(errs, fn(fldPath.Child("compatibilityGroups"), obj.CompatibilityGroups, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceDerivedAttribute validates an instance of DeviceDerivedAttribute according +// to declarative validation rules in the API schema. +func Validate_DeviceDerivedAttribute( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceDerivedAttribute) (errs field.ErrorList) { + + { // field DeviceDerivedAttribute.Name + fn := func( + fldPath *field.Path, + obj, oldObj *FullyQualifiedName, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ResourceFullyQualifiedName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceDerivedAttribute) *FullyQualifiedName { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field DeviceDerivedAttribute.Expression + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceDerivedAttribute) *string { + return &oldObj.Expression + }) + errs = append(errs, fn(fldPath.Child("expression"), &obj.Expression, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceRequest validates an instance of DeviceRequest according +// to declarative validation rules in the API schema. +func Validate_DeviceRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceRequest) (errs field.ErrorList) { + + // field DeviceRequest.Name has no validation + + { // field DeviceRequest.Exactly + fn := func( + fldPath *field.Path, + obj, oldObj *ExactDeviceRequest, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_ExactDeviceRequest(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequest) *ExactDeviceRequest { + return oldObj.Exactly + }) + errs = append(errs, fn(fldPath.Child("exactly"), obj.Exactly, oldVal, oldObj != nil)...) + } + + { // field DeviceRequest.FirstAvailable + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceSubRequest, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *DeviceSubRequest, b *DeviceSubRequest) bool { return a.Name == b.Name }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *DeviceSubRequest, b *DeviceSubRequest) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_DeviceSubRequest); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequest) []DeviceSubRequest { + return oldObj.FirstAvailable + }) + errs = append(errs, fn(fldPath.Child("firstAvailable"), obj.FirstAvailable, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceRequestAllocationResult validates an instance of DeviceRequestAllocationResult according +// to declarative validation rules in the API schema. +func Validate_DeviceRequestAllocationResult( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceRequestAllocationResult) (errs field.ErrorList) { + + // field DeviceRequestAllocationResult.Request has no validation + + { // field DeviceRequestAllocationResult.Driver + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongNameCaseless(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 63).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) *string { + return &oldObj.Driver + }) + errs = append(errs, fn(fldPath.Child("driver"), &obj.Driver, oldVal, oldObj != nil)...) + } + + { // field DeviceRequestAllocationResult.Pool + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ResourcePoolName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) *string { + return &oldObj.Pool + }) + errs = append(errs, fn(fldPath.Child("pool"), &obj.Pool, oldVal, oldObj != nil)...) + } + + // field DeviceRequestAllocationResult.Device has no validation + // field DeviceRequestAllocationResult.AdminAccess has no validation + + { // field DeviceRequestAllocationResult.Tolerations + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceToleration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceToleration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) []DeviceToleration { + return oldObj.Tolerations + }) + errs = append(errs, fn(fldPath.Child("tolerations"), obj.Tolerations, oldVal, oldObj != nil)...) + } + + { // field DeviceRequestAllocationResult.BindingConditions + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) []string { + return oldObj.BindingConditions + }) + errs = append(errs, fn(fldPath.Child("bindingConditions"), obj.BindingConditions, oldVal, oldObj != nil)...) + } + + { // field DeviceRequestAllocationResult.BindingFailureConditions + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) []string { + return oldObj.BindingFailureConditions + }) + errs = append(errs, fn(fldPath.Child("bindingFailureConditions"), obj.BindingFailureConditions, oldVal, oldObj != nil)...) + } + + { // field DeviceRequestAllocationResult.ShareID + fn := func( + fldPath *field.Path, + obj, oldObj *types.UID, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) *types.UID { + return oldObj.ShareID + }) + errs = append(errs, fn(fldPath.Child("shareID"), obj.ShareID, oldVal, oldObj != nil)...) + } + + // field DeviceRequestAllocationResult.ConsumedCapacity has no validation + + { // field DeviceRequestAllocationResult.SkipNodeOperations + fn := func( + fldPath *field.Path, + obj, oldObj []SkipNodeOperation, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, Validate_SkipNodeOperation); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceRequestAllocationResult) []SkipNodeOperation { + return oldObj.SkipNodeOperations + }) + errs = append(errs, fn(fldPath.Child("skipNodeOperations"), obj.SkipNodeOperations, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceSubRequest validates an instance of DeviceSubRequest according +// to declarative validation rules in the API schema. +func Validate_DeviceSubRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceSubRequest) (errs field.ErrorList) { + + // field DeviceSubRequest.Name has no validation + + { // field DeviceSubRequest.DeviceClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceSubRequest) *string { + return &oldObj.DeviceClassName + }) + errs = append(errs, fn(fldPath.Child("deviceClassName"), &obj.DeviceClassName, oldVal, oldObj != nil)...) + } + + { // field DeviceSubRequest.Selectors + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceSelector, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceSubRequest) []DeviceSelector { + return oldObj.Selectors + }) + errs = append(errs, fn(fldPath.Child("selectors"), obj.Selectors, oldVal, oldObj != nil)...) + } + + { // field DeviceSubRequest.AllocationMode + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceAllocationMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeviceAllocationMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceSubRequest) *DeviceAllocationMode { + return &oldObj.AllocationMode + }) + errs = append(errs, fn(fldPath.Child("allocationMode"), &obj.AllocationMode, oldVal, oldObj != nil)...) + } + + // field DeviceSubRequest.Count has no validation + + { // field DeviceSubRequest.Tolerations + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceToleration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceToleration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceSubRequest) []DeviceToleration { + return oldObj.Tolerations + }) + errs = append(errs, fn(fldPath.Child("tolerations"), obj.Tolerations, oldVal, oldObj != nil)...) + } + + // field DeviceSubRequest.Capacity has no validation + + { // field DeviceSubRequest.DerivedAttributes + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceDerivedAttribute, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceDerivedAttribute); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceSubRequest) []DeviceDerivedAttribute { + return oldObj.DerivedAttributes + }) + errs = append(errs, fn(fldPath.Child("derivedAttributes"), obj.DerivedAttributes, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceTaint validates an instance of DeviceTaint according +// to declarative validation rules in the API schema. +func Validate_DeviceTaint( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceTaint) (errs field.ErrorList) { + + // field DeviceTaint.Key has no validation + // field DeviceTaint.Value has no validation + + { // field DeviceTaint.Effect + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceTaintEffect, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeviceTaintEffect(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceTaint) *DeviceTaintEffect { + return &oldObj.Effect + }) + errs = append(errs, fn(fldPath.Child("effect"), &obj.Effect, oldVal, oldObj != nil)...) + } + + // field DeviceTaint.TimeAdded has no validation + return errs +} + +var symbolsForDeviceTaintEffect = sets.New(DeviceTaintEffectNoExecute, DeviceTaintEffectNoSchedule, DeviceTaintEffectNone) + +// Validate_DeviceTaintEffect validates an instance of DeviceTaintEffect according +// to declarative validation rules in the API schema. +func Validate_DeviceTaintEffect( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceTaintEffect) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForDeviceTaintEffect, nil).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_DeviceTaintRuleSpec validates an instance of DeviceTaintRuleSpec according +// to declarative validation rules in the API schema. +func Validate_DeviceTaintRuleSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceTaintRuleSpec) (errs field.ErrorList) { + + // field DeviceTaintRuleSpec.DeviceSelector has no validation + + { // field DeviceTaintRuleSpec.Taint + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceTaint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceTaint(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceTaintRuleSpec) *DeviceTaint { + return &oldObj.Taint + }) + errs = append(errs, fn(fldPath.Child("taint"), &obj.Taint, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceTaintRuleStatus validates an instance of DeviceTaintRuleStatus according +// to declarative validation rules in the API schema. +func Validate_DeviceTaintRuleStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceTaintRuleStatus) (errs field.ErrorList) { + + { // field DeviceTaintRuleStatus.Conditions + fn := func( + fldPath *field.Path, + obj, oldObj []metav1.Condition, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *metav1.Condition, b *metav1.Condition) bool { return a.Type == b.Type }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *metav1.Condition, b *metav1.Condition) bool { return a.Type == b.Type }, validate.SemanticDeepEqual, validation.Validate_Condition); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceTaintRuleStatus) []metav1.Condition { + return oldObj.Conditions + }) + errs = append(errs, fn(fldPath.Child("conditions"), obj.Conditions, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeviceToleration validates an instance of DeviceToleration according +// to declarative validation rules in the API schema. +func Validate_DeviceToleration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceToleration) (errs field.ErrorList) { + + { // field DeviceToleration.Key + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LabelKey(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceToleration) *string { + return &oldObj.Key + }) + errs = append(errs, fn(fldPath.Child("key"), &obj.Key, oldVal, oldObj != nil)...) + } + + { // field DeviceToleration.Operator + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceTolerationOperator, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + // optional fields with default values are effectively required + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeviceTolerationOperator(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceToleration) *DeviceTolerationOperator { + return &oldObj.Operator + }) + errs = append(errs, fn(fldPath.Child("operator"), &obj.Operator, oldVal, oldObj != nil)...) + } + + // field DeviceToleration.Value has no validation + + { // field DeviceToleration.Effect + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceTaintEffect, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeviceTaintEffect(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DeviceToleration) *DeviceTaintEffect { + return &oldObj.Effect + }) + errs = append(errs, fn(fldPath.Child("effect"), &obj.Effect, oldVal, oldObj != nil)...) + } + + // field DeviceToleration.TolerationSeconds has no validation + return errs +} + +var symbolsForDeviceTolerationOperator = sets.New(DeviceTolerationOpEqual, DeviceTolerationOpExists) + +// Validate_DeviceTolerationOperator validates an instance of DeviceTolerationOperator according +// to declarative validation rules in the API schema. +func Validate_DeviceTolerationOperator( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DeviceTolerationOperator) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForDeviceTolerationOperator, nil).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_ExactDeviceRequest validates an instance of ExactDeviceRequest according +// to declarative validation rules in the API schema. +func Validate_ExactDeviceRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *ExactDeviceRequest) (errs field.ErrorList) { + + // field ExactDeviceRequest.DeviceClassName has no validation + + { // field ExactDeviceRequest.Selectors + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceSelector, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ExactDeviceRequest) []DeviceSelector { + return oldObj.Selectors + }) + errs = append(errs, fn(fldPath.Child("selectors"), obj.Selectors, oldVal, oldObj != nil)...) + } + + { // field ExactDeviceRequest.AllocationMode + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceAllocationMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeviceAllocationMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ExactDeviceRequest) *DeviceAllocationMode { + return &oldObj.AllocationMode + }) + errs = append(errs, fn(fldPath.Child("allocationMode"), &obj.AllocationMode, oldVal, oldObj != nil)...) + } + + // field ExactDeviceRequest.Count has no validation + // field ExactDeviceRequest.AdminAccess has no validation + + { // field ExactDeviceRequest.Tolerations + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceToleration, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceToleration); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ExactDeviceRequest) []DeviceToleration { + return oldObj.Tolerations + }) + errs = append(errs, fn(fldPath.Child("tolerations"), obj.Tolerations, oldVal, oldObj != nil)...) + } + + // field ExactDeviceRequest.Capacity has no validation + + { // field ExactDeviceRequest.DerivedAttributes + fn := func( + fldPath *field.Path, + obj, oldObj []DeviceDerivedAttribute, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_DeviceDerivedAttribute); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ExactDeviceRequest) []DeviceDerivedAttribute { + return oldObj.DerivedAttributes + }) + errs = append(errs, fn(fldPath.Child("derivedAttributes"), obj.DerivedAttributes, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_NetworkDeviceData validates an instance of NetworkDeviceData according +// to declarative validation rules in the API schema. +func Validate_NetworkDeviceData( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *NetworkDeviceData) (errs field.ErrorList) { + + { // field NetworkDeviceData.InterfaceName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxBytes(ctx, op, fldPath, obj, oldObj, 256).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NetworkDeviceData) *string { + return &oldObj.InterfaceName + }) + errs = append(errs, fn(fldPath.Child("interfaceName"), &obj.InterfaceName, oldVal, oldObj != nil)...) + } + + { // field NetworkDeviceData.IPs + fn := func( + fldPath *field.Path, + obj, oldObj []string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NetworkDeviceData) []string { + return oldObj.IPs + }) + errs = append(errs, fn(fldPath.Child("ips"), obj.IPs, oldVal, oldObj != nil)...) + } + + { // field NetworkDeviceData.HardwareAddress + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxBytes(ctx, op, fldPath, obj, oldObj, 128).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NetworkDeviceData) *string { + return &oldObj.HardwareAddress + }) + errs = append(errs, fn(fldPath.Child("hardwareAddress"), &obj.HardwareAddress, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_resource_v1_NodeAllocatableMapping_ = validate.NewUnionMembership(validate.NewUnionMember("capacityKey"), validate.NewUnionMember("deviceMultiplier")) + +// Validate_NodeAllocatableMapping validates an instance of NodeAllocatableMapping according +// to declarative validation rules in the API schema. +func Validate_NodeAllocatableMapping( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *NodeAllocatableMapping) (errs field.ErrorList) { + + if e := validate.DependentRequired(ctx, op, fldPath, obj, oldObj, "capacityKey", + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.CapacityKey != nil + }, "capacityMultiplier", + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.CapacityMultiplier != nil + }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_resource_v1_NodeAllocatableMapping_, + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.CapacityKey != nil + }, + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.DeviceMultiplier != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.DependentRequired(ctx, op, fldPath, obj, oldObj, "capacityMultiplier", + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.CapacityMultiplier != nil + }, "capacityKey", + func(obj *NodeAllocatableMapping) bool { + if obj == nil { + return false + } + return obj.CapacityKey != nil + }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + + { // field NodeAllocatableMapping.CapacityKey + fn := func( + fldPath *field.Path, + obj, oldObj *QualifiedName, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableMapping) *QualifiedName { + return oldObj.CapacityKey + }) + errs = append(errs, fn(fldPath.Child("capacityKey"), obj.CapacityKey, oldVal, oldObj != nil)...) + } + + { // field NodeAllocatableMapping.CapacityMultiplier + fn := func( + fldPath *field.Path, + obj, oldObj *resource.Quantity, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableMapping) *resource.Quantity { + return oldObj.CapacityMultiplier + }) + errs = append(errs, fn(fldPath.Child("capacityMultiplier"), obj.CapacityMultiplier, oldVal, oldObj != nil)...) + } + + { // field NodeAllocatableMapping.DeviceMultiplier + fn := func( + fldPath *field.Path, + obj, oldObj *resource.Quantity, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableMapping) *resource.Quantity { + return oldObj.DeviceMultiplier + }) + errs = append(errs, fn(fldPath.Child("deviceMultiplier"), obj.DeviceMultiplier, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_NodeAllocatableOverhead validates an instance of NodeAllocatableOverhead according +// to declarative validation rules in the API schema. +func Validate_NodeAllocatableOverhead( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *NodeAllocatableOverhead) (errs field.ErrorList) { + + { // field NodeAllocatableOverhead.PerPod + fn := func( + fldPath *field.Path, + obj, oldObj *resource.Quantity, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableOverhead) *resource.Quantity { + return oldObj.PerPod + }) + errs = append(errs, fn(fldPath.Child("perPod"), obj.PerPod, oldVal, oldObj != nil)...) + } + + { // field NodeAllocatableOverhead.PerContainer + fn := func( + fldPath *field.Path, + obj, oldObj *resource.Quantity, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableOverhead) *resource.Quantity { + return oldObj.PerContainer + }) + errs = append(errs, fn(fldPath.Child("perContainer"), obj.PerContainer, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_NodeAllocatableResource validates an instance of NodeAllocatableResource according +// to declarative validation rules in the API schema. +func Validate_NodeAllocatableResource( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *NodeAllocatableResource) (errs field.ErrorList) { + + { // field NodeAllocatableResource.Mapping + fn := func( + fldPath *field.Path, + obj, oldObj *NodeAllocatableMapping, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_NodeAllocatableMapping(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableResource) *NodeAllocatableMapping { + return oldObj.Mapping + }) + errs = append(errs, fn(fldPath.Child("mapping"), obj.Mapping, oldVal, oldObj != nil)...) + } + + { // field NodeAllocatableResource.Overhead + fn := func( + fldPath *field.Path, + obj, oldObj *NodeAllocatableOverhead, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_NodeAllocatableOverhead(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *NodeAllocatableResource) *NodeAllocatableOverhead { + return oldObj.Overhead + }) + errs = append(errs, fn(fldPath.Child("overhead"), obj.Overhead, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_OpaqueDeviceConfiguration validates an instance of OpaqueDeviceConfiguration according +// to declarative validation rules in the API schema. +func Validate_OpaqueDeviceConfiguration( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *OpaqueDeviceConfiguration) (errs field.ErrorList) { + + { // field OpaqueDeviceConfiguration.Driver + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongNameCaseless(ctx, op, fldPath, obj, oldObj).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 63).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *OpaqueDeviceConfiguration) *string { + return &oldObj.Driver + }) + errs = append(errs, fn(fldPath.Child("driver"), &obj.Driver, oldVal, oldObj != nil)...) + } + + // field OpaqueDeviceConfiguration.Parameters has no validation + return errs +} + +// Validate_ResourceClaimSpec validates an instance of ResourceClaimSpec according +// to declarative validation rules in the API schema. +func Validate_ResourceClaimSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *ResourceClaimSpec) (errs field.ErrorList) { + + { // field ResourceClaimSpec.Devices + fn := func( + fldPath *field.Path, + obj, oldObj *DeviceClaim, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_DeviceClaim(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceClaimSpec) *DeviceClaim { + return &oldObj.Devices + }) + errs = append(errs, fn(fldPath.Child("devices"), &obj.Devices, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_ResourceClaimStatus validates an instance of ResourceClaimStatus according +// to declarative validation rules in the API schema. +func Validate_ResourceClaimStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *ResourceClaimStatus) (errs field.ErrorList) { + + { // field ResourceClaimStatus.Allocation + fn := func( + fldPath *field.Path, + obj, oldObj *AllocationResult, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoModify).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_AllocationResult(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceClaimStatus) *AllocationResult { + return oldObj.Allocation + }) + errs = append(errs, fn(fldPath.Child("allocation"), obj.Allocation, oldVal, oldObj != nil)...) + } + + { // field ResourceClaimStatus.ReservedFor + fn := func( + fldPath *field.Path, + obj, oldObj []ResourceClaimConsumerReference, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *ResourceClaimConsumerReference, b *ResourceClaimConsumerReference) bool { return a.UID == b.UID }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceClaimStatus) []ResourceClaimConsumerReference { + return oldObj.ReservedFor + }) + errs = append(errs, fn(fldPath.Child("reservedFor"), obj.ReservedFor, oldVal, oldObj != nil)...) + } + + { // field ResourceClaimStatus.Devices + fn := func( + fldPath *field.Path, + obj, oldObj []AllocatedDeviceStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *AllocatedDeviceStatus, b *AllocatedDeviceStatus) bool { + return a.Driver == b.Driver && a.Device == b.Device && a.Pool == b.Pool && ((a.ShareID == nil && b.ShareID == nil) || (a.ShareID != nil && b.ShareID != nil && *a.ShareID == *b.ShareID)) + }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *AllocatedDeviceStatus, b *AllocatedDeviceStatus) bool { + return a.Driver == b.Driver && a.Device == b.Device && a.Pool == b.Pool && ((a.ShareID == nil && b.ShareID == nil) || (a.ShareID != nil && b.ShareID != nil && *a.ShareID == *b.ShareID)) + }, validate.SemanticDeepEqual, Validate_AllocatedDeviceStatus); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceClaimStatus) []AllocatedDeviceStatus { + return oldObj.Devices + }) + errs = append(errs, fn(fldPath.Child("devices"), obj.Devices, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_ResourceClaimTemplateSpec validates an instance of ResourceClaimTemplateSpec according +// to declarative validation rules in the API schema. +func Validate_ResourceClaimTemplateSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *ResourceClaimTemplateSpec) (errs field.ErrorList) { + + // field ResourceClaimTemplateSpec.ObjectMeta has no validation + + { // field ResourceClaimTemplateSpec.Spec + fn := func( + fldPath *field.Path, + obj, oldObj *ResourceClaimSpec, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_ResourceClaimSpec(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceClaimTemplateSpec) *ResourceClaimSpec { + return &oldObj.Spec + }) + errs = append(errs, fn(fldPath.Child("spec"), &obj.Spec, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_ResourceSliceSpec validates an instance of ResourceSliceSpec according +// to declarative validation rules in the API schema. +func Validate_ResourceSliceSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *ResourceSliceSpec) (errs field.ErrorList) { + + // field ResourceSliceSpec.Driver has no validation + // field ResourceSliceSpec.Pool has no validation + // field ResourceSliceSpec.NodeName has no validation + // field ResourceSliceSpec.NodeSelector has no validation + // field ResourceSliceSpec.AllNodes has no validation + + { // field ResourceSliceSpec.Devices + fn := func( + fldPath *field.Path, + obj, oldObj []Device, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_Device); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceSliceSpec) []Device { + return oldObj.Devices + }) + errs = append(errs, fn(fldPath.Child("devices"), obj.Devices, oldVal, oldObj != nil)...) + } + + // field ResourceSliceSpec.PerDeviceNodeSelection has no validation + + { // field ResourceSliceSpec.SharedCounters + fn := func( + fldPath *field.Path, + obj, oldObj []CounterSet, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkBeta().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkBeta().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *CounterSet, b *CounterSet) bool { return a.Name == b.Name }).MarkBeta(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *CounterSet, b *CounterSet) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_CounterSet); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceSliceSpec) []CounterSet { + return oldObj.SharedCounters + }) + errs = append(errs, fn(fldPath.Child("sharedCounters"), obj.SharedCounters, oldVal, oldObj != nil)...) + } + + { // field ResourceSliceSpec.PartitionTypeAttribute + fn := func( + fldPath *field.Path, + obj, oldObj *FullyQualifiedName, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "DRAPartitionableDevicesType", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "DRAPartitionableDevicesType", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "DRAPartitionableDevicesType", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "DRAPartitionableDevicesType", true, validate.ResourceFullyQualifiedName); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceSliceSpec) *FullyQualifiedName { + return oldObj.PartitionTypeAttribute + }) + errs = append(errs, fn(fldPath.Child("partitionTypeAttribute"), obj.PartitionTypeAttribute, oldVal, oldObj != nil)...) + } + + { // field ResourceSliceSpec.SkipNodeOperations + fn := func( + fldPath *field.Path, + obj, oldObj []SkipNodeOperation, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, Validate_SkipNodeOperation); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ResourceSliceSpec) []SkipNodeOperation { + return oldObj.SkipNodeOperations + }) + errs = append(errs, fn(fldPath.Child("skipNodeOperations"), obj.SkipNodeOperations, oldVal, oldObj != nil)...) + } + + return errs +} + +var symbolsForSkipNodeOperation = sets.New(SkipNodeOperationAll, SkipNodeOperationNodePrepareResources, SkipNodeOperationNodeUnprepareResources) + +// Validate_SkipNodeOperation validates an instance of SkipNodeOperation according +// to declarative validation rules in the API schema. +func Validate_SkipNodeOperation( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *SkipNodeOperation) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForSkipNodeOperation, nil); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.pb.go b/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.pb.go index fa1f5f471..77199b046 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.pb.go +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.pb.go @@ -24,6 +24,7 @@ import ( io "io" + resource "k8s.io/apimachinery/pkg/api/resource" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" math_bits "math/bits" @@ -47,6 +48,8 @@ func (m *DeviceTaintRuleStatus) Reset() { *m = DeviceTaintRuleStatus{} } func (m *DeviceTaintSelector) Reset() { *m = DeviceTaintSelector{} } +func (m *PartitionTypeStatus) Reset() { *m = PartitionTypeStatus{} } + func (m *PoolStatus) Reset() { *m = PoolStatus{} } func (m *ResourcePoolStatusRequest) Reset() { *m = ResourcePoolStatusRequest{} } @@ -57,6 +60,10 @@ func (m *ResourcePoolStatusRequestSpec) Reset() { *m = ResourcePoolStatusRequest func (m *ResourcePoolStatusRequestStatus) Reset() { *m = ResourcePoolStatusRequestStatus{} } +func (m *ShareableCapacityStatus) Reset() { *m = ShareableCapacityStatus{} } + +func (m *ShareableSummaryStatus) Reset() { *m = ShareableSummaryStatus{} } + func (m *CELDeviceSelector) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -396,6 +403,49 @@ func (m *DeviceTaintSelector) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *PartitionTypeStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PartitionTypeStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PartitionTypeStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Attribute) + copy(dAtA[i:], m.Attribute) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Attribute))) + i-- + dAtA[i] = 0x22 + if m.Allocatable != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Allocatable)) + i-- + dAtA[i] = 0x18 + } + if m.Total != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Total)) + i-- + dAtA[i] = 0x10 + } + i -= len(m.Type) + copy(dAtA[i:], m.Type) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Type))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *PoolStatus) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -416,6 +466,32 @@ func (m *PoolStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.ShareableSummary != nil { + { + size, err := m.ShareableSummary.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x6a + } + if len(m.PartitionSummary) > 0 { + for iNdEx := len(m.PartitionSummary) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PartitionSummary[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x5a + } + } if m.ValidationError != nil { i -= len(*m.ValidationError) copy(dAtA[i:], *m.ValidationError) @@ -593,6 +669,13 @@ func (m *ResourcePoolStatusRequestSpec) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if m.DefaultPartitionTypeAttribute != nil { + i -= len(*m.DefaultPartitionTypeAttribute) + copy(dAtA[i:], *m.DefaultPartitionTypeAttribute) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.DefaultPartitionTypeAttribute))) + i-- + dAtA[i] = 0x22 + } if m.Limit != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.Limit)) i-- @@ -669,6 +752,117 @@ func (m *ResourcePoolStatusRequestStatus) MarshalToSizedBuffer(dAtA []byte) (int return len(dAtA) - i, nil } +func (m *ShareableCapacityStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ShareableCapacityStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ShareableCapacityStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Available != nil { + { + size, err := m.Available.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.Consumed != nil { + { + size, err := m.Consumed.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.Total != nil { + { + size, err := m.Total.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ShareableSummaryStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ShareableSummaryStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ShareableSummaryStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Capacity) > 0 { + for iNdEx := len(m.Capacity) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Capacity[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.PartiallyAvailableDevices != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.PartiallyAvailableDevices)) + i-- + dAtA[i] = 0x10 + } + if m.FullyAvailableDevices != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.FullyAvailableDevices)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { offset -= sovGenerated(v) base := offset @@ -806,6 +1000,25 @@ func (m *DeviceTaintSelector) Size() (n int) { return n } +func (m *PartitionTypeStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Type) + n += 1 + l + sovGenerated(uint64(l)) + if m.Total != nil { + n += 1 + sovGenerated(uint64(*m.Total)) + } + if m.Allocatable != nil { + n += 1 + sovGenerated(uint64(*m.Allocatable)) + } + l = len(m.Attribute) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *PoolStatus) Size() (n int) { if m == nil { return 0 @@ -840,6 +1053,16 @@ func (m *PoolStatus) Size() (n int) { l = len(*m.ValidationError) n += 1 + l + sovGenerated(uint64(l)) } + if len(m.PartitionSummary) > 0 { + for _, e := range m.PartitionSummary { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.ShareableSummary != nil { + l = m.ShareableSummary.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -892,6 +1115,10 @@ func (m *ResourcePoolStatusRequestSpec) Size() (n int) { if m.Limit != nil { n += 1 + sovGenerated(uint64(*m.Limit)) } + if m.DefaultPartitionTypeAttribute != nil { + l = len(*m.DefaultPartitionTypeAttribute) + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -919,6 +1146,50 @@ func (m *ResourcePoolStatusRequestStatus) Size() (n int) { return n } +func (m *ShareableCapacityStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.Total != nil { + l = m.Total.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Consumed != nil { + l = m.Consumed.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Available != nil { + l = m.Available.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *ShareableSummaryStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.FullyAvailableDevices != nil { + n += 1 + sovGenerated(uint64(*m.FullyAvailableDevices)) + } + if m.PartiallyAvailableDevices != nil { + n += 1 + sovGenerated(uint64(*m.PartiallyAvailableDevices)) + } + if len(m.Capacity) > 0 { + for _, e := range m.Capacity { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func sovGenerated(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -1011,10 +1282,28 @@ func (this *DeviceTaintSelector) String() string { }, "") return s } +func (this *PartitionTypeStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PartitionTypeStatus{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Total:` + valueToStringGenerated(this.Total) + `,`, + `Allocatable:` + valueToStringGenerated(this.Allocatable) + `,`, + `Attribute:` + fmt.Sprintf("%v", this.Attribute) + `,`, + `}`, + }, "") + return s +} func (this *PoolStatus) String() string { if this == nil { return "nil" } + repeatedStringForPartitionSummary := "[]PartitionTypeStatus{" + for _, f := range this.PartitionSummary { + repeatedStringForPartitionSummary += strings.Replace(strings.Replace(f.String(), "PartitionTypeStatus", "PartitionTypeStatus", 1), `&`, ``, 1) + "," + } + repeatedStringForPartitionSummary += "}" s := strings.Join([]string{`&PoolStatus{`, `Driver:` + fmt.Sprintf("%v", this.Driver) + `,`, `PoolName:` + fmt.Sprintf("%v", this.PoolName) + `,`, @@ -1026,6 +1315,8 @@ func (this *PoolStatus) String() string { `ResourceSliceCount:` + valueToStringGenerated(this.ResourceSliceCount) + `,`, `Generation:` + fmt.Sprintf("%v", this.Generation) + `,`, `ValidationError:` + valueToStringGenerated(this.ValidationError) + `,`, + `PartitionSummary:` + repeatedStringForPartitionSummary + `,`, + `ShareableSummary:` + strings.Replace(this.ShareableSummary.String(), "ShareableSummaryStatus", "ShareableSummaryStatus", 1) + `,`, `}`, }, "") return s @@ -1066,6 +1357,7 @@ func (this *ResourcePoolStatusRequestSpec) String() string { `Driver:` + fmt.Sprintf("%v", this.Driver) + `,`, `PoolName:` + valueToStringGenerated(this.PoolName) + `,`, `Limit:` + valueToStringGenerated(this.Limit) + `,`, + `DefaultPartitionTypeAttribute:` + valueToStringGenerated(this.DefaultPartitionTypeAttribute) + `,`, `}`, }, "") return s @@ -1092,6 +1384,36 @@ func (this *ResourcePoolStatusRequestStatus) String() string { }, "") return s } +func (this *ShareableCapacityStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ShareableCapacityStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Total:` + strings.Replace(fmt.Sprintf("%v", this.Total), "Quantity", "resource.Quantity", 1) + `,`, + `Consumed:` + strings.Replace(fmt.Sprintf("%v", this.Consumed), "Quantity", "resource.Quantity", 1) + `,`, + `Available:` + strings.Replace(fmt.Sprintf("%v", this.Available), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *ShareableSummaryStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForCapacity := "[]ShareableCapacityStatus{" + for _, f := range this.Capacity { + repeatedStringForCapacity += strings.Replace(strings.Replace(f.String(), "ShareableCapacityStatus", "ShareableCapacityStatus", 1), `&`, ``, 1) + "," + } + repeatedStringForCapacity += "}" + s := strings.Join([]string{`&ShareableSummaryStatus{`, + `FullyAvailableDevices:` + valueToStringGenerated(this.FullyAvailableDevices) + `,`, + `PartiallyAvailableDevices:` + valueToStringGenerated(this.PartiallyAvailableDevices) + `,`, + `Capacity:` + repeatedStringForCapacity + `,`, + `}`, + }, "") + return s +} func valueToStringGenerated(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { @@ -2068,7 +2390,7 @@ func (m *DeviceTaintSelector) Unmarshal(dAtA []byte) error { } return nil } -func (m *PoolStatus) Unmarshal(dAtA []byte) error { +func (m *PartitionTypeStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2091,15 +2413,15 @@ func (m *PoolStatus) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PoolStatus: wiretype end group for non-group") + return fmt.Errorf("proto: PartitionTypeStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PoolStatus: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: PartitionTypeStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2127,13 +2449,13 @@ func (m *PoolStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Driver = string(dAtA[iNdEx:postIndex]) + m.Type = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolName", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) } - var stringLen uint64 + var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -2143,27 +2465,35 @@ func (m *PoolStatus) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + v |= int32(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + m.Total = &v + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Allocatable", wireType) } - if postIndex > l { - return io.ErrUnexpectedEOF + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } } - m.PoolName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: + m.Allocatable = &v + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Attribute", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2191,8 +2521,154 @@ func (m *PoolStatus) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := string(dAtA[iNdEx:postIndex]) - m.NodeName = &s + m.Attribute = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PoolStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PoolStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Driver = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.NodeName = &s iNdEx = postIndex case 4: if wireType != 0 { @@ -2346,6 +2822,76 @@ func (m *PoolStatus) Unmarshal(dAtA []byte) error { s := string(dAtA[iNdEx:postIndex]) m.ValidationError = &s iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartitionSummary", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PartitionSummary = append(m.PartitionSummary, PartitionTypeStatus{}) + if err := m.PartitionSummary[len(m.PartitionSummary)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShareableSummary", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ShareableSummary == nil { + m.ShareableSummary = &ShareableSummaryStatus{} + } + if err := m.ShareableSummary.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -2750,6 +3296,39 @@ func (m *ResourcePoolStatusRequestSpec) Unmarshal(dAtA []byte) error { } } m.Limit = &v + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DefaultPartitionTypeAttribute", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.DefaultPartitionTypeAttribute = &s + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -2909,6 +3488,320 @@ func (m *ResourcePoolStatusRequestStatus) Unmarshal(dAtA []byte) error { } return nil } +func (m *ShareableCapacityStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ShareableCapacityStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ShareableCapacityStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Total == nil { + m.Total = &resource.Quantity{} + } + if err := m.Total.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Consumed", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Consumed == nil { + m.Consumed = &resource.Quantity{} + } + if err := m.Consumed.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Available", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Available == nil { + m.Available = &resource.Quantity{} + } + if err := m.Available.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ShareableSummaryStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ShareableSummaryStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ShareableSummaryStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field FullyAvailableDevices", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.FullyAvailableDevices = &v + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PartiallyAvailableDevices", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.PartiallyAvailableDevices = &v + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Capacity", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Capacity = append(m.Capacity, ShareableCapacityStatus{}) + if err := m.Capacity[len(m.Capacity)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipGenerated(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.proto b/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.proto index d6ee31080..daa969018 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.proto +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/generated.proto @@ -21,6 +21,7 @@ syntax = "proto2"; package k8s.io.api.resource.v1alpha3; +import "k8s.io/apimachinery/pkg/api/resource/generated.proto"; import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; @@ -40,7 +41,7 @@ message CELDeviceSelector { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // // Example: Consider a device with driver="dra.example.com", which exposes @@ -71,6 +72,15 @@ message CELDeviceSelector { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -120,7 +130,7 @@ message DeviceTaint { // Consumers must treat unknown effects like None. // // +required - // +k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string effect = 3; // TimeAdded represents the time at which the taint was added or @@ -142,6 +152,7 @@ message DeviceTaint { // DeviceTaintRule adds one taint to all devices which match the selector. // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" message DeviceTaintRule { // Standard object metadata // +optional @@ -213,6 +224,9 @@ message DeviceTaintRuleStatus { // +listMapKey=type // +patchStrategy=merge // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; } @@ -248,6 +262,40 @@ message DeviceTaintSelector { optional string device = 4; } +// PartitionTypeStatus reports allocatability for a single partition type, +// identified by the value of a grouping attribute. +message PartitionTypeStatus { + // Attribute is the fully qualified name of the device attribute whose value + // groups this entry. It is the PartitionTypeAttribute declared by the + // devices' own slice, or the default named in the request when their slice + // declares none. + // + // +required + // +k8s:required + optional string attribute = 4; + + // Type is the partition type value (e.g. "Full" or "Half"). + // + // +required + // +k8s:required + optional string type = 1; + + // Total is the number of devices of this partition type in the pool. + // + // +required + // +k8s:required + // +k8s:minimum=0 + optional int32 total = 2; + + // Allocatable is the number of additional devices of this partition type + // that could still be allocated given current shared-counter consumption. + // + // +required + // +k8s:required + // +k8s:minimum=0 + optional int32 allocatable = 3; +} + // PoolStatus contains status information for a single resource pool. message PoolStatus { // Driver is the DRA driver name for this pool. @@ -339,6 +387,33 @@ message PoolStatus { // +k8s:optional // +k8s:maxBytes=256 optional string validationError = 10; + + // PartitionSummary reports allocatability per (attribute, partition type) + // for a partitionable pool that publishes SharedCounters. Each entry names + // the grouping attribute it was resolved from: the PartitionTypeAttribute + // declared by a device's own slice, or for devices whose slice declares + // none, the default named in the request. A pool that mixes partitions + // declared under different attributes reports each independently. When no + // slice declares an attribute and the request names no default, the pool + // reports no partition summary. + // + // +optional + // +k8s:optional + // +listType=atomic + // +k8s:listType=atomic + // +k8s:unique=map + // +k8s:listMapKey=attribute + // +k8s:listMapKey=type + // +k8s:maxItems=32 + repeated PartitionTypeStatus partitionSummary = 11; + + // ShareableSummary reports aggregate capacity for a pool that contains + // devices with AllowMultipleAllocations. It is populated only when at + // least one device in the pool is shareable. + // + // +optional + // +k8s:optional + optional ShareableSummaryStatus shareableSummary = 13; } // ResourcePoolStatusRequest triggers a one-time calculation of resource pool status @@ -410,6 +485,26 @@ message ResourcePoolStatusRequestSpec { // +k8s:minimum=1 // +k8s:maximum=1000 optional int32 limit = 3; + + // DefaultPartitionTypeAttribute optionally names a device attribute (by its + // fully qualified name, e.g. "gpu.example.com/profile") to use as the default + // grouping attribute for partitionable devices whose slice has not declared + // one themselves. + // + // A slice's own PartitionTypeAttribute always takes precedence. This default + // applies only to devices whose slice does not declare one, so that a request + // can still get an accurate partitionSummary from a driver that has not + // been updated to declare it. When neither the slice nor this default names + // an attribute, a partitionable pool reports no partitionSummary. + // + // Must include the domain qualifier. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + optional string defaultPartitionTypeAttribute = 4; } // ResourcePoolStatusRequestStatus contains the calculated pool status information. @@ -446,12 +541,69 @@ message ResourcePoolStatusRequestStatus { // +optional // +k8s:optional // +listType=map - // +k8s:listType=map // +listMapKey=type - // +k8s:listMapKey=type // +patchStrategy=merge // +patchMergeKey=type // +k8s:maxItems=10 + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 3; } +// ShareableCapacityStatus reports aggregate amounts for a single shareable +// capacity key. +message ShareableCapacityStatus { + // Name is the capacity name. + // + // +required + // +k8s:required + optional string name = 1; + + // Total is the sum of this capacity across shareable devices in the pool. + // + // +required + // +k8s:required + optional .k8s.io.apimachinery.pkg.api.resource.Quantity total = 2; + + // Consumed is the amount drawn by current allocations. + // + // +required + // +k8s:required + optional .k8s.io.apimachinery.pkg.api.resource.Quantity consumed = 3; + + // Available is Total minus Consumed, never negative. + // + // +required + // +k8s:required + optional .k8s.io.apimachinery.pkg.api.resource.Quantity available = 4; +} + +// ShareableSummaryStatus reports aggregate capacity for a pool that contains +// devices with AllowMultipleAllocations. +message ShareableSummaryStatus { + // FullyAvailableDevices is the number of shareable devices with no + // capacity consumed. + // + // +required + // +k8s:required + // +k8s:minimum=0 + optional int32 fullyAvailableDevices = 1; + + // PartiallyAvailableDevices is the number of shareable devices with some + // but not all capacity consumed. + // + // +required + // +k8s:required + // +k8s:minimum=0 + optional int32 partiallyAvailableDevices = 2; + + // Capacity reports aggregate total, consumed, and available amounts per + // shareable capacity key across the pool. + // + // +optional + // +k8s:optional + // +listType=atomic + // +k8s:maxItems=32 + repeated ShareableCapacityStatus capacity = 3; +} + diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/types.go b/constraint/vendor/k8s.io/api/resource/v1alpha3/types.go index 1757c8615..8e1e88450 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/types.go +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/types.go @@ -17,6 +17,7 @@ limitations under the License. package v1alpha3 import ( + resource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -41,7 +42,7 @@ type CELDeviceSelector struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // // Example: Consider a device with driver="dra.example.com", which exposes @@ -72,6 +73,15 @@ type CELDeviceSelector struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -140,7 +150,7 @@ type DeviceTaint struct { // Consumers must treat unknown effects like None. // // +required - // +k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Effect DeviceTaintEffect `json:"effect" protobuf:"bytes,3,name=effect,casttype=DeviceTaintEffect"` // ^^^^ @@ -179,7 +189,7 @@ type DeviceTaint struct { } // +enum -// +k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTaintEffect string const ( @@ -203,8 +213,9 @@ const ( // DeviceTaintRule adds one taint to all devices which match the selector. // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" type DeviceTaintRule struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -322,6 +333,9 @@ type DeviceTaintRuleStatus struct { // +listMapKey=type // +patchStrategy=merge // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` } @@ -336,7 +350,7 @@ const DeviceTaintConditionEvictionInProgress = "EvictionInProgress" // DeviceTaintRuleList is a collection of DeviceTaintRules. type DeviceTaintRuleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -355,7 +369,7 @@ type DeviceTaintRuleList struct { // based on the provided filters. Once status is set, the request is considered complete and will not be reprocessed. // Users should delete and recreate requests to get updated information. type ResourcePoolStatusRequest struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +required metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -411,6 +425,26 @@ type ResourcePoolStatusRequestSpec struct { // +k8s:minimum=1 // +k8s:maximum=1000 Limit *int32 `json:"limit,omitempty" protobuf:"varint,3,opt,name=limit"` + + // DefaultPartitionTypeAttribute optionally names a device attribute (by its + // fully qualified name, e.g. "gpu.example.com/profile") to use as the default + // grouping attribute for partitionable devices whose slice has not declared + // one themselves. + // + // A slice's own PartitionTypeAttribute always takes precedence. This default + // applies only to devices whose slice does not declare one, so that a request + // can still get an accurate partitionSummary from a driver that has not + // been updated to declare it. When neither the slice nor this default names + // an attribute, a partitionable pool reports no partitionSummary. + // + // Must include the domain qualifier. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + DefaultPartitionTypeAttribute *string `json:"defaultPartitionTypeAttribute,omitempty" protobuf:"bytes,4,opt,name=defaultPartitionTypeAttribute"` } // ResourcePoolStatusRequestLimitDefault is the default value for spec.limit. @@ -453,12 +487,12 @@ type ResourcePoolStatusRequestStatus struct { // +optional // +k8s:optional // +listType=map - // +k8s:listType=map // +listMapKey=type - // +k8s:listMapKey=type // +patchStrategy=merge // +patchMergeKey=type // +k8s:maxItems=10 + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,3,rep,name=conditions"` } @@ -553,6 +587,124 @@ type PoolStatus struct { // +k8s:optional // +k8s:maxBytes=256 ValidationError *string `json:"validationError,omitempty" protobuf:"bytes,10,opt,name=validationError"` + + // PartitionSummary reports allocatability per (attribute, partition type) + // for a partitionable pool that publishes SharedCounters. Each entry names + // the grouping attribute it was resolved from: the PartitionTypeAttribute + // declared by a device's own slice, or for devices whose slice declares + // none, the default named in the request. A pool that mixes partitions + // declared under different attributes reports each independently. When no + // slice declares an attribute and the request names no default, the pool + // reports no partition summary. + // + // +optional + // +k8s:optional + // +listType=atomic + // +k8s:listType=atomic + // +k8s:unique=map + // +k8s:listMapKey=attribute + // +k8s:listMapKey=type + // +k8s:maxItems=32 + PartitionSummary []PartitionTypeStatus `json:"partitionSummary,omitempty" protobuf:"bytes,11,rep,name=partitionSummary"` + + // ShareableSummary reports aggregate capacity for a pool that contains + // devices with AllowMultipleAllocations. It is populated only when at + // least one device in the pool is shareable. + // + // +optional + // +k8s:optional + ShareableSummary *ShareableSummaryStatus `json:"shareableSummary,omitempty" protobuf:"bytes,13,opt,name=shareableSummary"` +} + +// PartitionTypeStatus reports allocatability for a single partition type, +// identified by the value of a grouping attribute. +type PartitionTypeStatus struct { + // Attribute is the fully qualified name of the device attribute whose value + // groups this entry. It is the PartitionTypeAttribute declared by the + // devices' own slice, or the default named in the request when their slice + // declares none. + // + // +required + // +k8s:required + Attribute string `json:"attribute,omitempty" protobuf:"bytes,4,name=attribute"` + + // Type is the partition type value (e.g. "Full" or "Half"). + // + // +required + // +k8s:required + Type string `json:"type,omitempty" protobuf:"bytes,1,name=type"` + + // Total is the number of devices of this partition type in the pool. + // + // +required + // +k8s:required + // +k8s:minimum=0 + Total *int32 `json:"total,omitempty" protobuf:"varint,2,opt,name=total"` + + // Allocatable is the number of additional devices of this partition type + // that could still be allocated given current shared-counter consumption. + // + // +required + // +k8s:required + // +k8s:minimum=0 + Allocatable *int32 `json:"allocatable,omitempty" protobuf:"varint,3,opt,name=allocatable"` +} + +// ShareableSummaryStatus reports aggregate capacity for a pool that contains +// devices with AllowMultipleAllocations. +type ShareableSummaryStatus struct { + // FullyAvailableDevices is the number of shareable devices with no + // capacity consumed. + // + // +required + // +k8s:required + // +k8s:minimum=0 + FullyAvailableDevices *int32 `json:"fullyAvailableDevices,omitempty" protobuf:"varint,1,opt,name=fullyAvailableDevices"` + + // PartiallyAvailableDevices is the number of shareable devices with some + // but not all capacity consumed. + // + // +required + // +k8s:required + // +k8s:minimum=0 + PartiallyAvailableDevices *int32 `json:"partiallyAvailableDevices,omitempty" protobuf:"varint,2,opt,name=partiallyAvailableDevices"` + + // Capacity reports aggregate total, consumed, and available amounts per + // shareable capacity key across the pool. + // + // +optional + // +k8s:optional + // +listType=atomic + // +k8s:maxItems=32 + Capacity []ShareableCapacityStatus `json:"capacity,omitempty" protobuf:"bytes,3,rep,name=capacity"` +} + +// ShareableCapacityStatus reports aggregate amounts for a single shareable +// capacity key. +type ShareableCapacityStatus struct { + // Name is the capacity name. + // + // +required + // +k8s:required + Name string `json:"name,omitempty" protobuf:"bytes,1,name=name"` + + // Total is the sum of this capacity across shareable devices in the pool. + // + // +required + // +k8s:required + Total *resource.Quantity `json:"total,omitempty" protobuf:"bytes,2,opt,name=total"` + + // Consumed is the amount drawn by current allocations. + // + // +required + // +k8s:required + Consumed *resource.Quantity `json:"consumed,omitempty" protobuf:"bytes,3,opt,name=consumed"` + + // Available is Total minus Consumed, never negative. + // + // +required + // +k8s:required + Available *resource.Quantity `json:"available,omitempty" protobuf:"bytes,4,opt,name=available"` } // ResourcePoolStatusRequestConditionComplete is the condition type for completed requests. @@ -566,7 +718,7 @@ const ResourcePoolStatusRequestConditionFailed = "Failed" // ResourcePoolStatusRequestList is a collection of ResourcePoolStatusRequests. type ResourcePoolStatusRequestList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/resource/v1alpha3/types_swagger_doc_generated.go index 49ff642fe..4fddc16bc 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1alpha3 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_CELDeviceSelector = map[string]string{ "": "CELDeviceSelector contains a CEL expression for selecting a device.", - "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\".\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", + "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\").\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nCommon errors: - \"no such key\": Use optional chaining (.? followed by orValue())\n or guarding the check with has() for optional fields.\n See CEL Optional Types for details:\n https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes\n\nFor more CEL expression syntax and examples, see: https://kubernetes.io/docs/reference/using-api/cel/\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", } func (CELDeviceSelector) SwaggerDoc() map[string]string { @@ -108,6 +108,18 @@ func (DeviceTaintSelector) SwaggerDoc() map[string]string { return map_DeviceTaintSelector } +var map_PartitionTypeStatus = map[string]string{ + "": "PartitionTypeStatus reports allocatability for a single partition type, identified by the value of a grouping attribute.", + "attribute": "Attribute is the fully qualified name of the device attribute whose value groups this entry. It is the PartitionTypeAttribute declared by the devices' own slice, or the default named in the request when their slice declares none.", + "type": "Type is the partition type value (e.g. \"Full\" or \"Half\").", + "total": "Total is the number of devices of this partition type in the pool.", + "allocatable": "Allocatable is the number of additional devices of this partition type that could still be allocated given current shared-counter consumption.", +} + +func (PartitionTypeStatus) SwaggerDoc() map[string]string { + return map_PartitionTypeStatus +} + var map_PoolStatus = map[string]string{ "": "PoolStatus contains status information for a single resource pool.", "driver": "Driver is the DRA driver name for this pool. Must be a DNS subdomain (e.g., \"gpu.example.com\").", @@ -120,6 +132,8 @@ var map_PoolStatus = map[string]string{ "unavailableDevices": "UnavailableDevices is the number of devices that are not available due to taints or other conditions, but are not allocated. A value of 0 means all unallocated devices are available. May be unset when validationError is set.", "nodeName": "NodeName is the node this pool is associated with. When omitted, the pool is not associated with a specific node. Must be a valid DNS subdomain name (RFC1123).", "validationError": "ValidationError is set when the pool's data could not be fully validated (e.g., incomplete slice publication). When set, device count fields and ResourceSliceCount may be unset.", + "partitionSummary": "PartitionSummary reports allocatability per (attribute, partition type) for a partitionable pool that publishes SharedCounters. Each entry names the grouping attribute it was resolved from: the PartitionTypeAttribute declared by a device's own slice, or for devices whose slice declares none, the default named in the request. A pool that mixes partitions declared under different attributes reports each independently. When no slice declares an attribute and the request names no default, the pool reports no partition summary.", + "shareableSummary": "ShareableSummary reports aggregate capacity for a pool that contains devices with AllowMultipleAllocations. It is populated only when at least one device in the pool is shareable.", } func (PoolStatus) SwaggerDoc() map[string]string { @@ -148,10 +162,11 @@ func (ResourcePoolStatusRequestList) SwaggerDoc() map[string]string { } var map_ResourcePoolStatusRequestSpec = map[string]string{ - "": "ResourcePoolStatusRequestSpec defines the filters for the pool status request.", - "driver": "Driver specifies the DRA driver name to filter pools. Only pools from ResourceSlices with this driver will be included. Must be a DNS subdomain (e.g., \"gpu.example.com\").", - "poolName": "PoolName optionally filters to a specific pool name. If not specified, all pools from the specified driver are included. When specified, must be a non-empty valid resource pool name (DNS subdomains separated by \"/\").", - "limit": "Limit optionally specifies the maximum number of pools to return in the status. If more pools match the filter criteria, the response will be truncated (i.e., len(status.pools) < status.poolCount).\n\nDefault: 100 Minimum: 1 Maximum: 1000", + "": "ResourcePoolStatusRequestSpec defines the filters for the pool status request.", + "driver": "Driver specifies the DRA driver name to filter pools. Only pools from ResourceSlices with this driver will be included. Must be a DNS subdomain (e.g., \"gpu.example.com\").", + "poolName": "PoolName optionally filters to a specific pool name. If not specified, all pools from the specified driver are included. When specified, must be a non-empty valid resource pool name (DNS subdomains separated by \"/\").", + "limit": "Limit optionally specifies the maximum number of pools to return in the status. If more pools match the filter criteria, the response will be truncated (i.e., len(status.pools) < status.poolCount).\n\nDefault: 100 Minimum: 1 Maximum: 1000", + "defaultPartitionTypeAttribute": "DefaultPartitionTypeAttribute optionally names a device attribute (by its fully qualified name, e.g. \"gpu.example.com/profile\") to use as the default grouping attribute for partitionable devices whose slice has not declared one themselves.\n\nA slice's own PartitionTypeAttribute always takes precedence. This default applies only to devices whose slice does not declare one, so that a request can still get an accurate partitionSummary from a driver that has not been updated to declare it. When neither the slice nor this default names an attribute, a partitionable pool reports no partitionSummary.\n\nMust include the domain qualifier.", } func (ResourcePoolStatusRequestSpec) SwaggerDoc() map[string]string { @@ -169,4 +184,27 @@ func (ResourcePoolStatusRequestStatus) SwaggerDoc() map[string]string { return map_ResourcePoolStatusRequestStatus } +var map_ShareableCapacityStatus = map[string]string{ + "": "ShareableCapacityStatus reports aggregate amounts for a single shareable capacity key.", + "name": "Name is the capacity name.", + "total": "Total is the sum of this capacity across shareable devices in the pool.", + "consumed": "Consumed is the amount drawn by current allocations.", + "available": "Available is Total minus Consumed, never negative.", +} + +func (ShareableCapacityStatus) SwaggerDoc() map[string]string { + return map_ShareableCapacityStatus +} + +var map_ShareableSummaryStatus = map[string]string{ + "": "ShareableSummaryStatus reports aggregate capacity for a pool that contains devices with AllowMultipleAllocations.", + "fullyAvailableDevices": "FullyAvailableDevices is the number of shareable devices with no capacity consumed.", + "partiallyAvailableDevices": "PartiallyAvailableDevices is the number of shareable devices with some but not all capacity consumed.", + "capacity": "Capacity reports aggregate total, consumed, and available amounts per shareable capacity key across the pool.", +} + +func (ShareableSummaryStatus) SwaggerDoc() map[string]string { + return map_ShareableSummaryStatus +} + // AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.deepcopy.go index 32ec2ad8e..b3ec2e6c7 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.deepcopy.go @@ -220,6 +220,32 @@ func (in *DeviceTaintSelector) DeepCopy() *DeviceTaintSelector { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PartitionTypeStatus) DeepCopyInto(out *PartitionTypeStatus) { + *out = *in + if in.Total != nil { + in, out := &in.Total, &out.Total + *out = new(int32) + **out = **in + } + if in.Allocatable != nil { + in, out := &in.Allocatable, &out.Allocatable + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PartitionTypeStatus. +func (in *PartitionTypeStatus) DeepCopy() *PartitionTypeStatus { + if in == nil { + return nil + } + out := new(PartitionTypeStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PoolStatus) DeepCopyInto(out *PoolStatus) { *out = *in @@ -258,6 +284,18 @@ func (in *PoolStatus) DeepCopyInto(out *PoolStatus) { *out = new(string) **out = **in } + if in.PartitionSummary != nil { + in, out := &in.PartitionSummary, &out.PartitionSummary + *out = make([]PartitionTypeStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ShareableSummary != nil { + in, out := &in.ShareableSummary, &out.ShareableSummary + *out = new(ShareableSummaryStatus) + (*in).DeepCopyInto(*out) + } return } @@ -349,6 +387,11 @@ func (in *ResourcePoolStatusRequestSpec) DeepCopyInto(out *ResourcePoolStatusReq *out = new(int32) **out = **in } + if in.DefaultPartitionTypeAttribute != nil { + in, out := &in.DefaultPartitionTypeAttribute, &out.DefaultPartitionTypeAttribute + *out = new(string) + **out = **in + } return } @@ -396,3 +439,67 @@ func (in *ResourcePoolStatusRequestStatus) DeepCopy() *ResourcePoolStatusRequest in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ShareableCapacityStatus) DeepCopyInto(out *ShareableCapacityStatus) { + *out = *in + if in.Total != nil { + in, out := &in.Total, &out.Total + x := (*in).DeepCopy() + *out = &x + } + if in.Consumed != nil { + in, out := &in.Consumed, &out.Consumed + x := (*in).DeepCopy() + *out = &x + } + if in.Available != nil { + in, out := &in.Available, &out.Available + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ShareableCapacityStatus. +func (in *ShareableCapacityStatus) DeepCopy() *ShareableCapacityStatus { + if in == nil { + return nil + } + out := new(ShareableCapacityStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ShareableSummaryStatus) DeepCopyInto(out *ShareableSummaryStatus) { + *out = *in + if in.FullyAvailableDevices != nil { + in, out := &in.FullyAvailableDevices, &out.FullyAvailableDevices + *out = new(int32) + **out = **in + } + if in.PartiallyAvailableDevices != nil { + in, out := &in.PartiallyAvailableDevices, &out.PartiallyAvailableDevices + *out = new(int32) + **out = **in + } + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make([]ShareableCapacityStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ShareableSummaryStatus. +func (in *ShareableSummaryStatus) DeepCopy() *ShareableSummaryStatus { + if in == nil { + return nil + } + out := new(ShareableSummaryStatus) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.model_name.go index 3ef712c22..255ca1dda 100644 --- a/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/resource/v1alpha3/zz_generated.model_name.go @@ -61,6 +61,11 @@ func (in DeviceTaintSelector) OpenAPIModelName() string { return "io.k8s.api.resource.v1alpha3.DeviceTaintSelector" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PartitionTypeStatus) OpenAPIModelName() string { + return "io.k8s.api.resource.v1alpha3.PartitionTypeStatus" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in PoolStatus) OpenAPIModelName() string { return "io.k8s.api.resource.v1alpha3.PoolStatus" @@ -85,3 +90,13 @@ func (in ResourcePoolStatusRequestSpec) OpenAPIModelName() string { func (in ResourcePoolStatusRequestStatus) OpenAPIModelName() string { return "io.k8s.api.resource.v1alpha3.ResourcePoolStatusRequestStatus" } + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ShareableCapacityStatus) OpenAPIModelName() string { + return "io.k8s.api.resource.v1alpha3.ShareableCapacityStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ShareableSummaryStatus) OpenAPIModelName() string { + return "io.k8s.api.resource.v1alpha3.ShareableSummaryStatus" +} diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/generated.pb.go b/constraint/vendor/k8s.io/api/resource/v1beta1/generated.pb.go index 4170f7780..c279e0cc1 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/generated.pb.go @@ -84,6 +84,8 @@ func (m *DeviceConstraint) Reset() { *m = DeviceConstraint{} } func (m *DeviceCounterConsumption) Reset() { *m = DeviceCounterConsumption{} } +func (m *DeviceDerivedAttribute) Reset() { *m = DeviceDerivedAttribute{} } + func (m *DeviceRequest) Reset() { *m = DeviceRequest{} } func (m *DeviceRequestAllocationResult) Reset() { *m = DeviceRequestAllocationResult{} } @@ -98,7 +100,11 @@ func (m *DeviceToleration) Reset() { *m = DeviceToleration{} } func (m *NetworkDeviceData) Reset() { *m = NetworkDeviceData{} } -func (m *NodeAllocatableResourceMapping) Reset() { *m = NodeAllocatableResourceMapping{} } +func (m *NodeAllocatableMapping) Reset() { *m = NodeAllocatableMapping{} } + +func (m *NodeAllocatableOverhead) Reset() { *m = NodeAllocatableOverhead{} } + +func (m *NodeAllocatableResource) Reset() { *m = NodeAllocatableResource{} } func (m *OpaqueDeviceConfiguration) Reset() { *m = OpaqueDeviceConfiguration{} } @@ -286,14 +292,14 @@ func (m *BasicDevice) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.NodeAllocatableResourceMappings) > 0 { - keysForNodeAllocatableResourceMappings := make([]string, 0, len(m.NodeAllocatableResourceMappings)) - for k := range m.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) - } - sort.Strings(keysForNodeAllocatableResourceMappings) - for iNdEx := len(keysForNodeAllocatableResourceMappings) - 1; iNdEx >= 0; iNdEx-- { - v := m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResourceMappings[iNdEx])] + if len(m.NodeAllocatableResources) > 0 { + keysForNodeAllocatableResources := make([]string, 0, len(m.NodeAllocatableResources)) + for k := range m.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) + } + sort.Strings(keysForNodeAllocatableResources) + for iNdEx := len(keysForNodeAllocatableResources) - 1; iNdEx >= 0; iNdEx-- { + v := m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResources[iNdEx])] baseI := i { size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) @@ -305,14 +311,14 @@ func (m *BasicDevice) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x12 - i -= len(keysForNodeAllocatableResourceMappings[iNdEx]) - copy(dAtA[i:], keysForNodeAllocatableResourceMappings[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResourceMappings[iNdEx]))) + i -= len(keysForNodeAllocatableResources[iNdEx]) + copy(dAtA[i:], keysForNodeAllocatableResources[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResources[iNdEx]))) i-- dAtA[i] = 0xa i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) i-- - dAtA[i] = 0x62 + dAtA[i] = 0x72 } } if m.AllowMultipleAllocations != nil { @@ -1422,6 +1428,15 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error _ = i var l int _ = l + if len(m.CompatibilityGroups) > 0 { + for iNdEx := len(m.CompatibilityGroups) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.CompatibilityGroups[iNdEx]) + copy(dAtA[i:], m.CompatibilityGroups[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.CompatibilityGroups[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } if len(m.Counters) > 0 { keysForCounters := make([]string, 0, len(m.Counters)) for k := range m.Counters { @@ -1459,6 +1474,39 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error return len(dAtA) - i, nil } +func (m *DeviceDerivedAttribute) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DeviceDerivedAttribute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DeviceDerivedAttribute) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Expression) + copy(dAtA[i:], m.Expression) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Expression))) + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *DeviceRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1479,6 +1527,20 @@ func (m *DeviceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + } + } if m.Capacity != nil { { size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) @@ -1584,6 +1646,15 @@ func (m *DeviceRequestAllocationResult) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x5a + } + } if len(m.ConsumedCapacity) > 0 { keysForConsumedCapacity := make([]string, 0, len(m.ConsumedCapacity)) for k := range m.ConsumedCapacity { @@ -1740,6 +1811,20 @@ func (m *DeviceSubRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + } if m.Capacity != nil { { size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) @@ -1941,7 +2026,7 @@ func (m *NetworkDeviceData) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { +func (m *NodeAllocatableMapping) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1951,19 +2036,31 @@ func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *NodeAllocatableResourceMapping) MarshalTo(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *NodeAllocatableResourceMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.AllocationMultiplier != nil { + if m.DeviceMultiplier != nil { + { + size, err := m.DeviceMultiplier.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.CapacityMultiplier != nil { { - size, err := m.AllocationMultiplier.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.CapacityMultiplier.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -1983,6 +2080,100 @@ func (m *NodeAllocatableResourceMapping) MarshalToSizedBuffer(dAtA []byte) (int, return len(dAtA) - i, nil } +func (m *NodeAllocatableOverhead) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableOverhead) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableOverhead) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PerContainer != nil { + { + size, err := m.PerContainer.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.PerPod != nil { + { + size, err := m.PerPod.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *NodeAllocatableResource) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableResource) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableResource) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Overhead != nil { + { + size, err := m.Overhead.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.Mapping != nil { + { + size, err := m.Mapping.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} + func (m *OpaqueDeviceConfiguration) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2537,6 +2728,22 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x52 + } + } + if m.PartitionTypeAttribute != nil { + i -= len(*m.PartitionTypeAttribute) + copy(dAtA[i:], *m.PartitionTypeAttribute) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PartitionTypeAttribute))) + i-- + dAtA[i] = 0x4a + } if len(m.SharedCounters) > 0 { for iNdEx := len(m.SharedCounters) - 1; iNdEx >= 0; iNdEx-- { { @@ -2746,8 +2953,8 @@ func (m *BasicDevice) Size() (n int) { if m.AllowMultipleAllocations != nil { n += 2 } - if len(m.NodeAllocatableResourceMappings) > 0 { - for k, v := range m.NodeAllocatableResourceMappings { + if len(m.NodeAllocatableResources) > 0 { + for k, v := range m.NodeAllocatableResources { _ = k _ = v l = v.Size() @@ -3138,6 +3345,25 @@ func (m *DeviceCounterConsumption) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.CompatibilityGroups) > 0 { + for _, s := range m.CompatibilityGroups { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DeviceDerivedAttribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Expression) + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -3179,6 +3405,12 @@ func (m *DeviceRequest) Size() (n int) { l = m.Capacity.Size() n += 1 + l + sovGenerated(uint64(l)) } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3230,6 +3462,12 @@ func (m *DeviceRequestAllocationResult) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3275,6 +3513,12 @@ func (m *DeviceSubRequest) Size() (n int) { l = m.Capacity.Size() n += 1 + l + sovGenerated(uint64(l)) } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3336,7 +3580,7 @@ func (m *NetworkDeviceData) Size() (n int) { return n } -func (m *NodeAllocatableResourceMapping) Size() (n int) { +func (m *NodeAllocatableMapping) Size() (n int) { if m == nil { return 0 } @@ -3346,8 +3590,46 @@ func (m *NodeAllocatableResourceMapping) Size() (n int) { l = len(*m.CapacityKey) n += 1 + l + sovGenerated(uint64(l)) } - if m.AllocationMultiplier != nil { - l = m.AllocationMultiplier.Size() + if m.CapacityMultiplier != nil { + l = m.CapacityMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DeviceMultiplier != nil { + l = m.DeviceMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableOverhead) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PerPod != nil { + l = m.PerPod.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.PerContainer != nil { + l = m.PerContainer.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableResource) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Mapping != nil { + l = m.Mapping.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Overhead != nil { + l = m.Overhead.Size() n += 1 + l + sovGenerated(uint64(l)) } return n @@ -3569,6 +3851,16 @@ func (m *ResourceSliceSpec) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } + if m.PartitionTypeAttribute != nil { + l = len(*m.PartitionTypeAttribute) + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3645,16 +3937,16 @@ func (this *BasicDevice) String() string { mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[QualifiedName(k)]) } mapStringForCapacity += "}" - keysForNodeAllocatableResourceMappings := make([]string, 0, len(this.NodeAllocatableResourceMappings)) - for k := range this.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) + keysForNodeAllocatableResources := make([]string, 0, len(this.NodeAllocatableResources)) + for k := range this.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) } - sort.Strings(keysForNodeAllocatableResourceMappings) - mapStringForNodeAllocatableResourceMappings := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping{" - for _, k := range keysForNodeAllocatableResourceMappings { - mapStringForNodeAllocatableResourceMappings += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(k)]) + sort.Strings(keysForNodeAllocatableResources) + mapStringForNodeAllocatableResources := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource{" + for _, k := range keysForNodeAllocatableResources { + mapStringForNodeAllocatableResources += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(k)]) } - mapStringForNodeAllocatableResourceMappings += "}" + mapStringForNodeAllocatableResources += "}" s := strings.Join([]string{`&BasicDevice{`, `Attributes:` + mapStringForAttributes + `,`, `Capacity:` + mapStringForCapacity + `,`, @@ -3667,7 +3959,7 @@ func (this *BasicDevice) String() string { `BindingConditions:` + fmt.Sprintf("%v", this.BindingConditions) + `,`, `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `AllowMultipleAllocations:` + valueToStringGenerated(this.AllowMultipleAllocations) + `,`, - `NodeAllocatableResourceMappings:` + mapStringForNodeAllocatableResourceMappings + `,`, + `NodeAllocatableResources:` + mapStringForNodeAllocatableResources + `,`, `}`, }, "") return s @@ -3970,6 +4262,18 @@ func (this *DeviceCounterConsumption) String() string { s := strings.Join([]string{`&DeviceCounterConsumption{`, `CounterSet:` + fmt.Sprintf("%v", this.CounterSet) + `,`, `Counters:` + mapStringForCounters + `,`, + `CompatibilityGroups:` + fmt.Sprintf("%v", this.CompatibilityGroups) + `,`, + `}`, + }, "") + return s +} +func (this *DeviceDerivedAttribute) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceDerivedAttribute{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Expression:` + fmt.Sprintf("%v", this.Expression) + `,`, `}`, }, "") return s @@ -3993,6 +4297,11 @@ func (this *DeviceRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&DeviceRequest{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, @@ -4003,6 +4312,7 @@ func (this *DeviceRequest) String() string { `FirstAvailable:` + repeatedStringForFirstAvailable + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, `}`, }, "") return s @@ -4037,6 +4347,7 @@ func (this *DeviceRequestAllocationResult) String() string { `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `ShareID:` + valueToStringGenerated(this.ShareID) + `,`, `ConsumedCapacity:` + mapStringForConsumedCapacity + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, `}`, }, "") return s @@ -4065,6 +4376,11 @@ func (this *DeviceSubRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&DeviceSubRequest{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, @@ -4073,6 +4389,7 @@ func (this *DeviceSubRequest) String() string { `Count:` + fmt.Sprintf("%v", this.Count) + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, `}`, }, "") return s @@ -4103,13 +4420,36 @@ func (this *NetworkDeviceData) String() string { }, "") return s } -func (this *NodeAllocatableResourceMapping) String() string { +func (this *NodeAllocatableMapping) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&NodeAllocatableResourceMapping{`, + s := strings.Join([]string{`&NodeAllocatableMapping{`, `CapacityKey:` + valueToStringGenerated(this.CapacityKey) + `,`, - `AllocationMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.AllocationMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `CapacityMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.CapacityMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `DeviceMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.DeviceMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableOverhead) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableOverhead{`, + `PerPod:` + strings.Replace(fmt.Sprintf("%v", this.PerPod), "Quantity", "resource.Quantity", 1) + `,`, + `PerContainer:` + strings.Replace(fmt.Sprintf("%v", this.PerContainer), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableResource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableResource{`, + `Mapping:` + strings.Replace(this.Mapping.String(), "NodeAllocatableMapping", "NodeAllocatableMapping", 1) + `,`, + `Overhead:` + strings.Replace(this.Overhead.String(), "NodeAllocatableOverhead", "NodeAllocatableOverhead", 1) + `,`, `}`, }, "") return s @@ -4298,6 +4638,8 @@ func (this *ResourceSliceSpec) String() string { `Devices:` + repeatedStringForDevices + `,`, `PerDeviceNodeSelection:` + valueToStringGenerated(this.PerDeviceNodeSelection) + `,`, `SharedCounters:` + repeatedStringForSharedCounters + `,`, + `PartitionTypeAttribute:` + valueToStringGenerated(this.PartitionTypeAttribute) + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, `}`, }, "") return s @@ -5301,9 +5643,9 @@ func (m *BasicDevice) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.AllowMultipleAllocations = &b - case 12: + case 14: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResourceMappings", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResources", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -5330,11 +5672,11 @@ func (m *BasicDevice) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.NodeAllocatableResourceMappings == nil { - m.NodeAllocatableResourceMappings = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping) + if m.NodeAllocatableResources == nil { + m.NodeAllocatableResources = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource) } var mapkey k8s_io_api_core_v1.ResourceName - mapvalue := &NodeAllocatableResourceMapping{} + mapvalue := &NodeAllocatableResource{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 @@ -5408,7 +5750,7 @@ func (m *BasicDevice) Unmarshal(dAtA []byte) error { if postmsgIndex > l { return io.ErrUnexpectedEOF } - mapvalue = &NodeAllocatableResourceMapping{} + mapvalue = &NodeAllocatableResource{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } @@ -5428,7 +5770,7 @@ func (m *BasicDevice) Unmarshal(dAtA []byte) error { iNdEx += skippy } } - m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue + m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -8347,17 +8689,163 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { } m.Counters[mapkey] = *mapvalue iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompatibilityGroups", wireType) } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompatibilityGroups = append(m.CompatibilityGroups, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceDerivedAttribute) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceDerivedAttribute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceDerivedAttribute: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = FullyQualifiedName(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Expression", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Expression = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF } iNdEx += skippy } @@ -8671,6 +9159,40 @@ func (m *DeviceRequest) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9130,6 +9652,38 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } m.ConsumedCapacity[QualifiedName(mapkey)] = *mapvalue iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9485,6 +10039,40 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9569,7 +10157,355 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TimeAdded", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.TimeAdded == nil { + m.TimeAdded = &v1.Time{} + } + if err := m.TimeAdded.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceToleration) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceToleration: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceToleration: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Operator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Operator = DeviceTolerationOperator(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TolerationSeconds", wireType) + } + var v int64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.TolerationSeconds = &v + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NetworkDeviceData: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NetworkDeviceData: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InterfaceName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9597,11 +10533,11 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Value = string(dAtA[iNdEx:postIndex]) + m.InterfaceName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field IPs", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9629,13 +10565,13 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) + m.IPs = append(m.IPs, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex - case 4: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeAdded", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field HardwareAddress", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9645,27 +10581,23 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - if m.TimeAdded == nil { - m.TimeAdded = &v1.Time{} - } - if err := m.TimeAdded.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } + m.HardwareAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -9688,7 +10620,7 @@ func (m *DeviceTaint) Unmarshal(dAtA []byte) error { } return nil } -func (m *DeviceToleration) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableMapping) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9711,15 +10643,15 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: DeviceToleration: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableMapping: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: DeviceToleration: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableMapping: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CapacityKey", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -9747,13 +10679,14 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Key = string(dAtA[iNdEx:postIndex]) + s := QualifiedName(dAtA[iNdEx:postIndex]) + m.CapacityKey = &s iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Operator", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CapacityMultiplier", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9763,61 +10696,33 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Operator = DeviceTolerationOperator(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + if m.CapacityMultiplier == nil { + m.CapacityMultiplier = &resource.Quantity{} } - if postIndex > l { - return io.ErrUnexpectedEOF + if err := m.CapacityMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.Value = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 4: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Effect", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field DeviceMultiplier", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9827,44 +10732,28 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.Effect = DeviceTaintEffect(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TolerationSeconds", wireType) + if m.DeviceMultiplier == nil { + m.DeviceMultiplier = &resource.Quantity{} } - var v int64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int64(b&0x7F) << shift - if b < 0x80 { - break - } + if err := m.DeviceMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.TolerationSeconds = &v + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9886,7 +10775,7 @@ func (m *DeviceToleration) Unmarshal(dAtA []byte) error { } return nil } -func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableOverhead) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -9909,17 +10798,17 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NetworkDeviceData: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableOverhead: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkDeviceData: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableOverhead: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterfaceName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PerPod", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9929,29 +10818,33 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.InterfaceName = string(dAtA[iNdEx:postIndex]) + if m.PerPod == nil { + m.PerPod = &resource.Quantity{} + } + if err := m.PerPod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IPs", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PerContainer", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -9961,55 +10854,27 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - m.IPs = append(m.IPs, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardwareAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated + if m.PerContainer == nil { + m.PerContainer = &resource.Quantity{} } - if postIndex > l { - return io.ErrUnexpectedEOF + if err := m.PerContainer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - m.HardwareAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -10032,7 +10897,7 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } return nil } -func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableResource) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -10055,17 +10920,17 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableResource: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableResource: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CapacityKey", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Mapping", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -10075,28 +10940,31 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthGenerated } if postIndex > l { return io.ErrUnexpectedEOF } - s := QualifiedName(dAtA[iNdEx:postIndex]) - m.CapacityKey = &s + if m.Mapping == nil { + m.Mapping = &NodeAllocatableMapping{} + } + if err := m.Mapping.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: + case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationMultiplier", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Overhead", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -10123,10 +10991,10 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.AllocationMultiplier == nil { - m.AllocationMultiplier = &resource.Quantity{} + if m.Overhead == nil { + m.Overhead = &NodeAllocatableOverhead{} } - if err := m.AllocationMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Overhead.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -11920,6 +12788,71 @@ func (m *ResourceSliceSpec) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartitionTypeAttribute", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := FullyQualifiedName(dAtA[iNdEx:postIndex]) + m.PartitionTypeAttribute = &s + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/resource/v1beta1/generated.proto index 79a51ee2c..874a34db3 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/generated.proto @@ -65,8 +65,8 @@ message AllocatedDeviceStatus { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 7; // Conditions contains the latest observation of the device's state. @@ -78,6 +78,9 @@ message AllocatedDeviceStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 4; // Data contains arbitrary driver-specific data. @@ -90,7 +93,7 @@ message AllocatedDeviceStatus { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional NetworkDeviceData networkData = 6; } @@ -126,7 +129,7 @@ message BasicDevice { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional map attributes = 1; // Capacity defines the set of capacities for this device. @@ -147,13 +150,13 @@ message BasicDevice { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 repeated DeviceCounterConsumption consumesCounters = 3; // NodeName identifies the node where the device is available. @@ -199,7 +202,7 @@ message BasicDevice { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceTaint taints = 7; // BindsToNode indicates if the usage of an allocation involving this device @@ -229,8 +232,8 @@ message BasicDevice { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 9; // BindingFailureConditions defines the conditions for binding failure. @@ -247,8 +250,8 @@ message BasicDevice { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 10; // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -260,7 +263,7 @@ message BasicDevice { // +featureGate=DRAConsumableCapacity optional bool allowMultipleAllocations = 11; - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -272,8 +275,9 @@ message BasicDevice { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - map nodeAllocatableResourceMappings = 12; + map nodeAllocatableResources = 14; } // CELDeviceSelector contains a CEL expression for selecting a device. @@ -288,7 +292,7 @@ message CELDeviceSelector { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -321,6 +325,15 @@ message CELDeviceSelector { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -390,6 +403,13 @@ message CapacityRequestPolicy { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -473,8 +493,8 @@ message CounterSet { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string name = 1; // Counters defines the set of counters for this CounterSet @@ -483,8 +503,8 @@ message CounterSet { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; } @@ -501,7 +521,7 @@ message Device { // // +optional // +oneOf=deviceType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional BasicDevice basic = 2; } @@ -512,7 +532,7 @@ message DeviceAllocationConfiguration { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string source = 1; // Requests lists the names of requests where the configuration applies. @@ -524,10 +544,10 @@ message DeviceAllocationConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 2; optional DeviceConfiguration deviceConfiguration = 3; @@ -539,8 +559,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequestAllocationResult results = 1; // This field is a combination of all the claim and class configuration parameters. @@ -553,8 +573,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 repeated DeviceAllocationConfiguration config = 2; } @@ -563,30 +583,30 @@ message DeviceAttribute { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional int64 int = 2; // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional bool bool = 3; // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string string = 4; // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string version = 5; // IntValues is a non-empty list of numbers. @@ -595,8 +615,8 @@ message DeviceAttribute { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated int64 ints = 6; @@ -604,8 +624,8 @@ message DeviceAttribute { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated bool bools = 7; @@ -616,8 +636,9 @@ message DeviceAttribute { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes repeated string strings = 8; @@ -628,8 +649,8 @@ message DeviceAttribute { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated string versions = 9; } @@ -667,11 +688,11 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequest requests = 1; // These constraints must be satisfied by the set of devices that get @@ -679,8 +700,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceConstraint constraints = 2; // This field holds configuration for multiple potential drivers which @@ -689,8 +710,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClaimConfiguration config = 3; } @@ -705,10 +726,10 @@ message DeviceClaimConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; optional DeviceConfiguration deviceConfiguration = 2; @@ -724,8 +745,8 @@ message DeviceClaimConfiguration { message DeviceClass { // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines what can be allocated and how to configure it. @@ -736,6 +757,7 @@ message DeviceClass { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional optional DeviceClassSpec spec = 2; } @@ -761,8 +783,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 1; // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -773,8 +795,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClassConfiguration config = 2; // ExtendedResourceName is the extended resource name for the devices of this class. @@ -786,11 +808,10 @@ message DeviceClassSpec { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name optional string extendedResourceName = 4; } @@ -802,7 +823,7 @@ message DeviceConfiguration { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional OpaqueDeviceConfiguration opaque = 1; } @@ -820,10 +841,10 @@ message DeviceConstraint { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; // MatchAttribute requires that all devices in question have this @@ -846,8 +867,8 @@ message DeviceConstraint { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string matchAttribute = 2; // DistinctAttribute requires that all devices in question have this @@ -869,6 +890,8 @@ message DeviceConstraint { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string distinctAttribute = 3; } @@ -879,8 +902,8 @@ message DeviceCounterConsumption { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string counterSet = 1; // Counters defines the counters that will be consumed by the device. @@ -888,9 +911,94 @@ message DeviceCounterConsumption { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + repeated string compatibilityGroups = 3; +} + +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +message DeviceDerivedAttribute { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + optional string name = 1; + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + optional string expression = 2; } // DeviceRequest is a request for devices required for a claim. @@ -935,8 +1043,8 @@ message DeviceRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 3; // AllocationMode and its related fields define how devices are allocated @@ -962,7 +1070,7 @@ message DeviceRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 4; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1012,11 +1120,11 @@ message DeviceRequest { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated DeviceSubRequest firstAvailable = 7; // If specified, the request's tolerations. @@ -1043,7 +1151,7 @@ message DeviceRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 8; // Capacity define resource requirements against each capacity. @@ -1062,6 +1170,34 @@ message DeviceRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 9; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 10; } // DeviceRequestAllocationResult contains the allocation result for one request. @@ -1085,9 +1221,9 @@ message DeviceRequestAllocationResult { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string driver = 2; // This name together with the driver name and the device name field @@ -1097,8 +1233,8 @@ message DeviceRequestAllocationResult { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name optional string pool = 3; // Device references one device instance via its name in the driver's @@ -1130,8 +1266,7 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // BindingConditions contains a copy of the BindingConditions @@ -1143,8 +1278,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 7; // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1156,8 +1291,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 8; // ShareID uniquely identifies an individual allocation share of the device, @@ -1167,8 +1302,8 @@ message DeviceRequestAllocationResult { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 9; // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -1183,6 +1318,19 @@ message DeviceRequestAllocationResult { // +optional // +featureGate=DRAConsumableCapacity map consumedCapacity = 10; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 11; } // DeviceSelector must have exactly one field set. @@ -1226,8 +1374,8 @@ message DeviceSubRequest { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name optional string deviceClassName = 2; // Selectors define criteria which must be satisfied by a specific @@ -1237,8 +1385,8 @@ message DeviceSubRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceSelector selectors = 3; // AllocationMode and its related fields define how devices are allocated @@ -1260,7 +1408,7 @@ message DeviceSubRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 4; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1291,7 +1439,7 @@ message DeviceSubRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 7; // Capacity define resource requirements against each capacity. @@ -1310,6 +1458,34 @@ message DeviceSubRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 8; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 9; } // The device this taint is attached to has the "effect" on @@ -1338,7 +1514,7 @@ message DeviceTaint { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string effect = 3; // TimeAdded represents the time at which the taint was added or @@ -1365,8 +1541,8 @@ message DeviceToleration { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key optional string key = 1; // Operator represents a key's relationship to the value. @@ -1376,7 +1552,7 @@ message DeviceToleration { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string operator = 2; // Value is the taint value the toleration matches to. @@ -1390,7 +1566,7 @@ message DeviceToleration { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string effect = 4; // TolerationSeconds represents the period of time the toleration (which must be @@ -1415,8 +1591,8 @@ message NetworkDeviceData { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 optional string interfaceName = 1; // IPs lists the network addresses assigned to the device's network interface. @@ -1429,10 +1605,10 @@ message NetworkDeviceData { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 repeated string ips = 2; // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -1440,47 +1616,104 @@ message NetworkDeviceData { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 optional string hardwareAddress = 3; } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -message NodeAllocatableResourceMapping { +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices or the specific capacity consumed. These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +message NodeAllocatableMapping { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") optional string capacityKey = 1; - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - optional .k8s.io.apimachinery.pkg.api.resource.Quantity allocationMultiplier = 2; + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + optional .k8s.io.apimachinery.pkg.api.resource.Quantity capacityMultiplier = 2; + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + optional .k8s.io.apimachinery.pkg.api.resource.Quantity deviceMultiplier = 3; +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +message NodeAllocatableOverhead { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perPod = 1; + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perContainer = 2; +} + +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +message NodeAllocatableResource { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + optional NodeAllocatableMapping mapping = 3; + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + optional NodeAllocatableOverhead overhead = 4; } // OpaqueDeviceConfiguration contains configuration parameters for a driver @@ -1496,9 +1729,9 @@ message OpaqueDeviceConfiguration { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless optional string driver = 1; // Parameters can contain arbitrary data. It is the responsibility of @@ -1527,7 +1760,8 @@ message ResourceClaim { // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional optional ResourceClaimSpec spec = 2; // Status describes whether the claim is ready to use and what has been allocated. @@ -1582,8 +1816,8 @@ message ResourceClaimStatus { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify optional AllocationResult allocation = 1; // ReservedFor indicates which entities are currently allowed to use @@ -1611,10 +1845,10 @@ message ResourceClaimStatus { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 repeated ResourceClaimConsumerReference reservedFor = 2; // Devices contains the status of each device allocated for this @@ -1622,18 +1856,18 @@ message ResourceClaimStatus { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID repeated AllocatedDeviceStatus devices = 4; } @@ -1651,6 +1885,7 @@ message ResourceClaimTemplate { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional optional ResourceClaimTemplateSpec spec = 2; } @@ -1670,11 +1905,13 @@ message ResourceClaimTemplateSpec { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional optional ResourceClaimSpec spec = 2; } @@ -1682,6 +1919,8 @@ message ResourceClaimTemplateSpec { message ResourcePool { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -1822,7 +2061,7 @@ message ResourceSliceSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType repeated Device devices = 6; @@ -1848,14 +2087,50 @@ message ResourceSliceSpec { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated CounterSet sharedCounters = 8; + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + optional string partitionTypeAttribute = 9; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 10; } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/types.go b/constraint/vendor/k8s.io/api/resource/v1beta1/types.go index 0d35ac989..f35e230ce 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/types.go @@ -78,7 +78,7 @@ const ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceSlice struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -97,6 +97,9 @@ const ( // ResourceSliceSelectorDriver can be used in a [metav1.ListOptions] // field selector to filter based on [ResourceSliceSpec.Driver]. ResourceSliceSelectorDriver = "spec.driver" + // ResourceSliceSelectorPoolName can be used in a [metav1.ListOptions] + // field selector to filter based on [ResourceSliceSpec.Pool.Name]. + ResourceSliceSelectorPoolName = "spec.pool.name" ) // ResourceSliceSpec contains the information published by the driver in one ResourceSlice. @@ -160,7 +163,7 @@ type ResourceSliceSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType Devices []Device `json:"devices,omitempty" protobuf:"bytes,6,name=devices"` @@ -186,17 +189,68 @@ type ResourceSliceSpec struct { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 SharedCounters []CounterSet `json:"sharedCounters,omitempty" protobuf:"bytes,8,name=sharedCounters"` + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + PartitionTypeAttribute *FullyQualifiedName `json:"partitionTypeAttribute,omitempty" protobuf:"bytes,9,opt,name=partitionTypeAttribute"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,10,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } +// +enum +// +k8s:enum +type SkipNodeOperation string + +const ( + // SkipNodeOperationNodePrepareResources indicates that NodePrepareResources gRPC calls are skipped. + SkipNodeOperationNodePrepareResources SkipNodeOperation = "NodePrepareResources" + + // SkipNodeOperationNodeUnprepareResources indicates that NodeUnprepareResources gRPC calls are skipped. + SkipNodeOperationNodeUnprepareResources SkipNodeOperation = "NodeUnprepareResources" + + // SkipNodeOperationAll indicates that all node-local resource operations are skipped. + SkipNodeOperationAll SkipNodeOperation = "*" +) + // CounterSet defines a named set of counters // that are available to be used by devices defined in the // ResourcePool. @@ -210,8 +264,8 @@ type CounterSet struct { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name Name string `json:"name" protobuf:"bytes,1,name=name"` // Counters defines the set of counters for this CounterSet @@ -220,8 +274,8 @@ type CounterSet struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,name=counters"` } @@ -241,6 +295,8 @@ const DriverNameMaxLength = 63 type ResourcePool struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -305,6 +361,10 @@ const ResourceSliceMaxDeviceCounterConsumptionsPerDevice = 2 // per device counter consumption. const ResourceSliceMaxCountersPerDeviceCounterConsumption = 32 +// Defines the maximum number of compatibility groups that can be +// declared per device counter consumption. +const DeviceCompatibilityGroupsMaxSize = 2 + // Device represents one individual hardware instance that can be selected based // on its attributes. Besides the name, exactly one field must be set. type Device struct { @@ -318,7 +378,7 @@ type Device struct { // // +optional // +oneOf=deviceType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Basic *BasicDevice `json:"basic,omitempty" protobuf:"bytes,2,opt,name=basic"` } @@ -330,7 +390,7 @@ type BasicDevice struct { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Attributes map[QualifiedName]DeviceAttribute `json:"attributes,omitempty" protobuf:"bytes,1,rep,name=attributes"` // Capacity defines the set of capacities for this device. @@ -351,13 +411,13 @@ type BasicDevice struct { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 ConsumesCounters []DeviceCounterConsumption `json:"consumesCounters,omitempty" protobuf:"bytes,3,rep,name=consumesCounters"` // NodeName identifies the node where the device is available. @@ -403,7 +463,7 @@ type BasicDevice struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Taints []DeviceTaint `json:"taints,omitempty" protobuf:"bytes,7,rep,name=taints"` // BindsToNode indicates if the usage of an allocation involving this device @@ -433,8 +493,8 @@ type BasicDevice struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,9,rep,name=bindingConditions"` // BindingFailureConditions defines the conditions for binding failure. @@ -451,8 +511,8 @@ type BasicDevice struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,10,rep,name=bindingFailureConditions"` // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -464,7 +524,10 @@ type BasicDevice struct { // +featureGate=DRAConsumableCapacity AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty" protobuf:"bytes,11,opt,name=allowMultipleAllocations"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResourceMappings is tombstoned as it got replaced with NodeAllocatableResources. + // NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,12,opt,name=nodeAllocatableResourceMappings"` + + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -476,46 +539,104 @@ type BasicDevice struct { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,12,opt,name=nodeAllocatableResourceMappings"` + NodeAllocatableResources map[v1.ResourceName]NodeAllocatableResource `json:"nodeAllocatableResources,omitempty" protobuf:"bytes,14,opt,name=nodeAllocatableResources"` } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity +// NodeAllocatableResource defines the translation between the DRA device/capacity // units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMapping struct { +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResource struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + Mapping *NodeAllocatableMapping `json:"mapping,omitempty" protobuf:"bytes,3,opt,name=mapping"` + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + Overhead *NodeAllocatableOverhead `json:"overhead,omitempty" protobuf:"bytes,4,opt,name=overhead"` +} + +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices or the specific capacity consumed. These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMapping struct { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") CapacityKey *QualifiedName `json:"capacityKey,omitempty" protobuf:"bytes,1,opt,name=capacityKey"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty" protobuf:"bytes,2,opt,name=allocationMultiplier"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty" protobuf:"bytes,2,opt,name=capacityMultiplier"` + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty" protobuf:"bytes,3,opt,name=deviceMultiplier"` +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverhead struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + PerPod *resource.Quantity `json:"perPod,omitempty" protobuf:"bytes,1,opt,name=perPod"` + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + PerContainer *resource.Quantity `json:"perContainer,omitempty" protobuf:"bytes,2,opt,name=perContainer"` } // DeviceCounterConsumption defines a set of counters that @@ -525,8 +646,8 @@ type DeviceCounterConsumption struct { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name CounterSet string `json:"counterSet" protobuf:"bytes,1,opt,name=counterSet"` // Counters defines the counters that will be consumed by the device. @@ -534,9 +655,39 @@ type DeviceCounterConsumption struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,opt,name=counters"` + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + CompatibilityGroups []string `json:"compatibilityGroups,omitempty" protobuf:"bytes,3,rep,name=compatibilityGroups"` } // DeviceCapacity describes a quantity associated with a device. @@ -612,6 +763,13 @@ type CapacityRequestPolicy struct { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -691,30 +849,30 @@ type DeviceAttribute struct { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember IntValue *int64 `json:"int,omitempty" protobuf:"varint,2,opt,name=int"` // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember BoolValue *bool `json:"bool,omitempty" protobuf:"varint,3,opt,name=bool"` // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember StringValue *string `json:"string,omitempty" protobuf:"bytes,4,opt,name=string"` // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember VersionValue *string `json:"version,omitempty" protobuf:"bytes,5,opt,name=version"` // IntValues is a non-empty list of numbers. @@ -723,8 +881,8 @@ type DeviceAttribute struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes IntValues []int64 `json:"ints,omitempty" protobuf:"varint,6,opt,name=ints"` @@ -732,8 +890,8 @@ type DeviceAttribute struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes BoolValues []bool `json:"bools,omitempty" protobuf:"varint,7,opt,name=bools"` @@ -744,8 +902,9 @@ type DeviceAttribute struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes StringValues []string `json:"strings,omitempty" protobuf:"bytes,8,opt,name=strings"` @@ -756,8 +915,8 @@ type DeviceAttribute struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes VersionValues []string `json:"versions,omitempty" protobuf:"bytes,9,opt,name=versions"` } @@ -794,7 +953,7 @@ type DeviceTaint struct { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Effect DeviceTaintEffect `json:"effect" protobuf:"bytes,3,name=effect,casttype=DeviceTaintEffect"` // ^^^^ @@ -833,7 +992,7 @@ type DeviceTaint struct { } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTaintEffect string const ( @@ -854,7 +1013,7 @@ const ( // ResourceSliceList is a collection of ResourceSlices. type ResourceSliceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -877,14 +1036,15 @@ type ResourceSliceList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaim struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` // Status describes whether the claim is ready to use and what has been allocated. @@ -912,11 +1072,11 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []DeviceRequest `json:"requests" protobuf:"bytes,1,name=requests"` // These constraints must be satisfied by the set of devices that get @@ -924,8 +1084,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Constraints []DeviceConstraint `json:"constraints,omitempty" protobuf:"bytes,2,opt,name=constraints"` // This field holds configuration for multiple potential drivers which @@ -934,8 +1094,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClaimConfiguration `json:"config,omitempty" protobuf:"bytes,3,opt,name=config"` // Potential future extension, ignored by older schedulers. This is @@ -1002,8 +1162,8 @@ type DeviceRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,3,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1029,7 +1189,7 @@ type DeviceRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,4,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1079,11 +1239,11 @@ type DeviceRequest struct { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 FirstAvailable []DeviceSubRequest `json:"firstAvailable,omitempty" protobuf:"bytes,7,name=firstAvailable"` // If specified, the request's tolerations. @@ -1110,7 +1270,7 @@ type DeviceRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,8,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1129,6 +1289,34 @@ type DeviceRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,9,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,10,rep,name=derivedAttributes"` } // DeviceSubRequest describes a request for device provided in the @@ -1163,8 +1351,8 @@ type DeviceSubRequest struct { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name DeviceClassName string `json:"deviceClassName" protobuf:"bytes,2,name=deviceClassName"` // Selectors define criteria which must be satisfied by a specific @@ -1174,8 +1362,8 @@ type DeviceSubRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,3,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1197,7 +1385,7 @@ type DeviceSubRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,4,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1228,7 +1416,7 @@ type DeviceSubRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,7,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1247,6 +1435,34 @@ type DeviceSubRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,8,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,9,rep,name=derivedAttributes"` } // CapacityRequirements defines the capacity requirements for a specific device request. @@ -1278,14 +1494,70 @@ type CapacityRequirements struct { Requests map[QualifiedName]resource.Quantity `json:"requests,omitempty" protobuf:"bytes,1,rep,name=requests,castkey=QualifiedName"` } +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttribute struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + Name FullyQualifiedName `json:"name" protobuf:"bytes,1,name=name"` + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + Expression string `json:"expression" protobuf:"bytes,2,name=expression"` +} + const ( DeviceSelectorsMaxSize = 32 FirstAvailableDeviceRequestMaxSize = 8 DeviceTolerationsMaxLength = 16 + DeviceDerivedAttributesMaxSize = 32 ) // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceAllocationMode string // Valid [DeviceRequest.CountMode] values. @@ -1315,7 +1587,7 @@ type CELDeviceSelector struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -1348,6 +1620,15 @@ type CELDeviceSelector struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -1395,6 +1676,25 @@ type CELDeviceSelector struct { // However, this depends on how fast the machine is. const CELSelectorExpressionMaxCost = 1000000 +// DeviceClaimDerivedAttributeCELMaxCost is the maximum combined execution cost +// allowed for all derived attribute CEL expressions within a single DeviceClaim. +// +// During validation, the API server computes the estimated execution cost of each +// derived attribute expression. The sum of these costs across all requests in the +// claim must not exceed this budget. If it does, the claim is rejected. +// +// To stay within the budget, consumers should simplify their CEL expressions, +// avoid computationally expensive operations like deep nesting or iterations +// (such as `.all()` or `.exists()`), and minimize the total number of derived +// attributes in a claim. +// +// This shared budget prevents excessively complex claims from degrading the +// performance of the kube-scheduler. The limit is set to 1,000,000 instruction +// executions (roughly 0.1 seconds of evaluation time), tying the collective +// cost of all derived attributes to the maximum cost allowed for a single +// CEL selector. +const DeviceClaimDerivedAttributeCELMaxCost = 1000000 + // CELSelectorExpressionMaxLength is the maximum length of a CEL selector expression string. const CELSelectorExpressionMaxLength = 10 * 1024 @@ -1412,10 +1712,10 @@ type DeviceConstraint struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` // MatchAttribute requires that all devices in question have this @@ -1438,8 +1738,8 @@ type DeviceConstraint struct { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name MatchAttribute *FullyQualifiedName `json:"matchAttribute,omitempty" protobuf:"bytes,2,opt,name=matchAttribute"` // Potential future extension, not part of the current design: @@ -1471,6 +1771,8 @@ type DeviceConstraint struct { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name DistinctAttribute *FullyQualifiedName `json:"distinctAttribute,omitempty" protobuf:"bytes,3,opt,name=distinctAttribute"` } @@ -1485,13 +1787,13 @@ type DeviceClaimConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,2,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,2,name=deviceConfiguration"` } // DeviceConfiguration must have exactly one field set. It gets embedded @@ -1502,7 +1804,7 @@ type DeviceConfiguration struct { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Opaque *OpaqueDeviceConfiguration `json:"opaque,omitempty" protobuf:"bytes,1,opt,name=opaque"` } @@ -1519,9 +1821,9 @@ type OpaqueDeviceConfiguration struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless Driver string `json:"driver" protobuf:"bytes,1,name=driver"` // Parameters can contain arbitrary data. It is the responsibility of @@ -1547,8 +1849,8 @@ type DeviceToleration struct { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key Key string `json:"key,omitempty" protobuf:"bytes,1,opt,name=key"` // Operator represents a key's relationship to the value. @@ -1558,7 +1860,7 @@ type DeviceToleration struct { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Operator DeviceTolerationOperator `json:"operator,omitempty" protobuf:"bytes,2,opt,name=operator,casttype=DeviceTolerationOperator"` // Value is the taint value the toleration matches to. @@ -1572,7 +1874,7 @@ type DeviceToleration struct { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Effect DeviceTaintEffect `json:"effect,omitempty" protobuf:"bytes,4,opt,name=effect,casttype=DeviceTaintEffect"` // TolerationSeconds represents the period of time the toleration (which must be @@ -1589,7 +1891,7 @@ type DeviceToleration struct { // A toleration operator is the set of operators that can be used in a toleration. // // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTolerationOperator string const ( @@ -1603,8 +1905,8 @@ type ResourceClaimStatus struct { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify Allocation *AllocationResult `json:"allocation,omitempty" protobuf:"bytes,1,opt,name=allocation"` // ReservedFor indicates which entities are currently allowed to use @@ -1632,10 +1934,10 @@ type ResourceClaimStatus struct { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 ReservedFor []ResourceClaimConsumerReference `json:"reservedFor,omitempty" protobuf:"bytes,2,opt,name=reservedFor" patchStrategy:"merge" patchMergeKey:"uid"` // DeallocationRequested is tombstoned since Kubernetes 1.32 where @@ -1648,18 +1950,18 @@ type ResourceClaimStatus struct { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID Devices []AllocatedDeviceStatus `json:"devices,omitempty" protobuf:"bytes,4,opt,name=devices"` } @@ -1722,8 +2024,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Results []DeviceRequestAllocationResult `json:"results,omitempty" protobuf:"bytes,1,opt,name=results"` // This field is a combination of all the claim and class configuration parameters. @@ -1736,8 +2038,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 Config []DeviceAllocationConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` } @@ -1766,9 +2068,9 @@ type DeviceRequestAllocationResult struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Driver string `json:"driver" protobuf:"bytes,2,name=driver"` // This name together with the driver name and the device name field @@ -1778,8 +2080,8 @@ type DeviceRequestAllocationResult struct { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name Pool string `json:"pool" protobuf:"bytes,3,name=pool"` // Device references one device instance via its name in the driver's @@ -1811,8 +2113,7 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // BindingConditions contains a copy of the BindingConditions @@ -1824,8 +2125,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,7,rep,name=bindingConditions"` // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1837,8 +2138,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,8,rep,name=bindingFailureConditions"` // ShareID uniquely identifies an individual allocation share of the device, @@ -1848,8 +2149,8 @@ type DeviceRequestAllocationResult struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *types.UID `json:"shareID,omitempty" protobuf:"bytes,9,opt,name=shareID"` // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -1864,6 +2165,19 @@ type DeviceRequestAllocationResult struct { // +optional // +featureGate=DRAConsumableCapacity ConsumedCapacity map[QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty" protobuf:"bytes,10,rep,name=consumedCapacity"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,11,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } // DeviceAllocationConfiguration gets embedded in an AllocationResult. @@ -1873,7 +2187,7 @@ type DeviceAllocationConfiguration struct { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Source AllocationConfigSource `json:"source" protobuf:"bytes,1,name=source"` // Requests lists the names of requests where the configuration applies. @@ -1885,17 +2199,17 @@ type DeviceAllocationConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,2,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,3,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,3,name=deviceConfiguration"` } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type AllocationConfigSource string // Valid [DeviceAllocationConfiguration.Source] values. @@ -1909,7 +2223,7 @@ const ( // ResourceClaimList is a collection of claims. type ResourceClaimList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1931,11 +2245,11 @@ type ResourceClaimList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type DeviceClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines what can be allocated and how to configure it. @@ -1946,6 +2260,7 @@ type DeviceClass struct { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional Spec DeviceClassSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -1956,8 +2271,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,1,opt,name=selectors"` // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -1968,8 +2283,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClassConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` // SuitableNodes is tombstoned since Kubernetes 1.32 where @@ -1986,17 +2301,16 @@ type DeviceClassSpec struct { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name ExtendedResourceName *string `json:"extendedResourceName,omitempty" protobuf:"bytes,4,opt,name=extendedResourceName"` } // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfiguration struct { - DeviceConfiguration `json:",inline" protobuf:"bytes,1,opt,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,1,opt,name=deviceConfiguration"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -2004,7 +2318,7 @@ type DeviceClassConfiguration struct { // DeviceClassList is a collection of classes. type DeviceClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2022,7 +2336,7 @@ type DeviceClassList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimTemplate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2032,6 +2346,7 @@ type ResourceClaimTemplate struct { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional Spec ResourceClaimTemplateSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2041,11 +2356,13 @@ type ResourceClaimTemplateSpec struct { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2054,7 +2371,7 @@ type ResourceClaimTemplateSpec struct { // ResourceClaimTemplateList is a collection of claim templates. type ResourceClaimTemplateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2116,8 +2433,8 @@ type AllocatedDeviceStatus struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *string `json:"shareID,omitempty" protobuf:"bytes,7,opt,name=shareID"` // Conditions contains the latest observation of the device's state. @@ -2129,6 +2446,9 @@ type AllocatedDeviceStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions" protobuf:"bytes,4,opt,name=conditions"` // Data contains arbitrary driver-specific data. @@ -2141,7 +2461,7 @@ type AllocatedDeviceStatus struct { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional NetworkData *NetworkDeviceData `json:"networkData,omitempty" protobuf:"bytes,6,opt,name=networkData"` } @@ -2156,8 +2476,8 @@ type NetworkDeviceData struct { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 InterfaceName string `json:"interfaceName,omitempty" protobuf:"bytes,1,opt,name=interfaceName"` // IPs lists the network addresses assigned to the device's network interface. @@ -2170,10 +2490,10 @@ type NetworkDeviceData struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 IPs []string `json:"ips,omitempty" protobuf:"bytes,2,opt,name=ips"` // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -2181,7 +2501,7 @@ type NetworkDeviceData struct { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 HardwareAddress string `json:"hardwareAddress,omitempty" protobuf:"bytes,3,opt,name=hardwareAddress"` } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/resource/v1beta1/types_swagger_doc_generated.go index 4b147a3f3..d1485ad84 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/types_swagger_doc_generated.go @@ -54,19 +54,19 @@ func (AllocationResult) SwaggerDoc() map[string]string { } var map_BasicDevice = map[string]string{ - "": "BasicDevice defines one device instance.", - "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", - "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is true, a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", - "nodeAllocatableResourceMappings": "NodeAllocatableResourceMappings defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", + "": "BasicDevice defines one device instance.", + "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", + "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is true, a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", + "nodeAllocatableResources": "NodeAllocatableResources defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", } func (BasicDevice) SwaggerDoc() map[string]string { @@ -75,7 +75,7 @@ func (BasicDevice) SwaggerDoc() map[string]string { var map_CELDeviceSelector = map[string]string{ "": "CELDeviceSelector contains a CEL expression for selecting a device.", - "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\".\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", + "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\").\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nCommon errors: - \"no such key\": Use optional chaining (.? followed by orValue())\n or guarding the check with has() for optional fields.\n See CEL Optional Types for details:\n https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes\n\nFor more CEL expression syntax and examples, see: https://kubernetes.io/docs/reference/using-api/cel/\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", } func (CELDeviceSelector) SwaggerDoc() map[string]string { @@ -94,7 +94,7 @@ func (CapacityRequestPolicy) SwaggerDoc() map[string]string { } var map_CapacityRequestPolicyRange = map[string]string{ - "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", + "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\nIf the DRAFractionalCapacityRange feature gate is enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. its value is not an integer), milli-unit arithmetic is used instead, supporting values with up to 3 decimal places (e.g. 100m = 0.1). The largest supported value then is 1000 times smaller compared to using 64-bit integers. Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value().\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", "min": "Min specifies the minimum capacity allowed for a consumption request.\n\nMin must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum.", "max": "Max defines the upper limit for capacity that can be requested.\n\nMax must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum.", "step": "Step defines the step size between valid capacity amounts within the range.\n\nMax (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value.", @@ -240,7 +240,7 @@ var map_DeviceClassSpec = map[string]string{ "": "DeviceClassSpec is used in a [DeviceClass] to define what can be allocated and how to configure it.", "selectors": "Each selector must be satisfied by a device which is claimed via this class.", "config": "Config defines configuration parameters that apply to each device that is claimed via this class. Some classses may potentially be satisfied by multiple drivers, so each instance of a vendor configuration applies to exactly one driver.\n\nThey are passed to the driver, but are not considered while allocating the claim.", - "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.\n\nThis is a beta field.", + "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.", } func (DeviceClassSpec) SwaggerDoc() map[string]string { @@ -268,26 +268,38 @@ func (DeviceConstraint) SwaggerDoc() map[string]string { } var map_DeviceCounterConsumption = map[string]string{ - "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", - "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", - "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", + "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", + "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "compatibilityGroups": "CompatibilityGroups is a list of opaque group names for this counter set consumption.\n\nDevices that consume counters from the same counter set may only be allocated at the same time (\"co-allocated\") if they all share at least one common group: the intersection of the CompatibilityGroups of all co-allocated devices on that counter set must be non-empty. Devices that consume from different counter sets are never compared via this field.\n\nAn unset field, an explicit nil, and an empty list are equivalent and mean \"no groups\": such a device is only co-allocatable with sibling devices on the same counter set that also have no groups, and is never co-allocatable with a device that declares one or more groups.\n\nGroup names are opaque and meaningful only within the publishing driver's pool.\n\nThe maximum number of groups is 2, and the names must be unique.", } func (DeviceCounterConsumption) SwaggerDoc() map[string]string { return map_DeviceCounterConsumption } +var map_DeviceDerivedAttribute = map[string]string{ + "": "DeviceDerivedAttribute defines a derived attribute computed via CEL.", + "name": "Name is the identifier for this derived attribute, used in constraints.\n\nIt must be a DNS subdomain followed by a slash (\"/\") followed by a C identifier (e.g. \"example.com/numaNode\" or \"derived/numaNode\").\n\nIf the chosen name matches an existing physical attribute from a driver, the derived attribute's expression will shadow the physical attribute, and its evaluated value will be used in constraints instead. When the goal is to define a derived attribute that is only used within the ResourceClaim and not meant to shadow an existing attribute, use a domain prefix that no DRA driver should be using (e.g. \"derived/myAttribute\").\n\nIt is not valid to define a derived attribute that isn't used in at least one constraint.", + "expression": "Expression is a CEL expression evaluated against each candidate device. The expression must evaluate to a primitive scalar (string, integer, boolean, or semver) or a list of these scalars ([]string, []int64, []bool, []semver) to act as a virtual grouping key. Any other return type is an error and causes CEL evaluation for the device to fail.\n\nThe expression's input is an object named \"device\", which carries the same properties as in a CELDeviceSelector.\n\nWhen pod scheduling encounters CEL runtime errors (such as looking up an attribute that isn't defined) for some devices, it will abort allocation and fail scheduling for the Pod. Surfacing evaluation errors immediately prevents silent topology matching failures that are extremely hard to detect. A robust expression should, for example, check for the existence of attributes before referencing them to avoid runtime evaluation errors.\n\nThe expression gets evaluated after a device has passed the other selector expressions for the request in which this expression is used. This allows writing expressions that are tailored towards the specific devices being requested (for example, by assuming the device is from a certain vendor and skipping those checks).\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps; the combined cost of all derived attributes in a claim is capped by a shared CEL cost budget.", +} + +func (DeviceDerivedAttribute) SwaggerDoc() map[string]string { + return map_DeviceDerivedAttribute +} + var map_DeviceRequest = map[string]string{ - "": "DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices.", - "name": "Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.\n\nMust be a DNS label and unique among all DeviceRequests in a ResourceClaim.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA class is required if no subrequests are specified in the firstAvailable list and no class can be set if subrequests are specified in the firstAvailable list. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.", - "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nThis is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.", - "firstAvailable": "FirstAvailable contains subrequests, of which exactly one will be satisfied by the scheduler to satisfy this request. It tries to satisfy them in the order in which they are listed here. So if there are two entries in the list, the scheduler will only check the second one if it determines that the first one cannot be used.\n\nThis field may only be set in the entries of DeviceClaim.Requests.\n\nDRA does not yet implement scoring, so the scheduler will select the first set of devices that satisfies all the requests in the claim. And if the requirements can be satisfied on more than one node, other scheduling features will determine which node is chosen. This means that the set of devices allocated to a claim might not be the optimal set available to the cluster. Scoring will be implemented later.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices.", + "name": "Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.\n\nMust be a DNS label and unique among all DeviceRequests in a ResourceClaim.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA class is required if no subrequests are specified in the firstAvailable list and no class can be set if subrequests are specified in the firstAvailable list. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.", + "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nThis is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.", + "firstAvailable": "FirstAvailable contains subrequests, of which exactly one will be satisfied by the scheduler to satisfy this request. It tries to satisfy them in the order in which they are listed here. So if there are two entries in the list, the scheduler will only check the second one if it determines that the first one cannot be used.\n\nThis field may only be set in the entries of DeviceClaim.Requests.\n\nDRA does not yet implement scoring, so the scheduler will select the first set of devices that satisfies all the requests in the claim. And if the requirements can be satisfied on more than one node, other scheduling features will determine which node is chosen. This means that the set of devices allocated to a claim might not be the optimal set available to the cluster. Scoring will be implemented later.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (DeviceRequest) SwaggerDoc() map[string]string { @@ -306,6 +318,7 @@ var map_DeviceRequestAllocationResult = map[string]string{ "bindingFailureConditions": "BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", "shareID": "ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device.", "consumedCapacity": "ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device’s requestPolicy if applicable (i.e., may not be less than the requested amount).\n\nThe total consumed capacity for each device must not exceed the DeviceCapacity's Value.\n\nThis field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for this allocated device when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. It is a copy of the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated.", } func (DeviceRequestAllocationResult) SwaggerDoc() map[string]string { @@ -322,14 +335,15 @@ func (DeviceSelector) SwaggerDoc() map[string]string { } var map_DeviceSubRequest = map[string]string{ - "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to Request, but doesn't expose the AdminAccess or FirstAvailable fields, as those can only be set on the top-level request. AdminAccess is not supported for requests with a prioritized list, and recursive FirstAvailable fields are not supported.", - "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to Request, but doesn't expose the AdminAccess or FirstAvailable fields, as those can only be set on the top-level request. AdminAccess is not supported for requests with a prioritized list, and recursive FirstAvailable fields are not supported.", + "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (DeviceSubRequest) SwaggerDoc() map[string]string { @@ -372,14 +386,35 @@ func (NetworkDeviceData) SwaggerDoc() map[string]string { return map_NetworkDeviceData } -var map_NodeAllocatableResourceMapping = map[string]string{ - "": "NodeAllocatableResourceMapping defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource.", - "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. If `allocationMultiplier` is also set, it is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\", and `allocationMultiplier` should be omitted or set to \"1\".", - "allocationMultiplier": "AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim.\n\t a. A DRA driver representing each CPU core as a device would have\n {ResourceName: \"cpu\", allocationMultiplier: \"2\"} in its\n `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim,\n\t\t 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity.\n b. A GPU device that needs additional node memory per GPU allocation would\n have {ResourceName: \"memory\", allocationMultiplier: \"2Gi\"}. Each allocated\n\t\t GPU device instance of this type will account for 2Gi of memory.\n\n2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed.\n\t The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`.\n For example, if a Device's capacity \"dra.example.com/cores\" is consumed,\n and each \"core\" provides 2 \"cpu\"s, the mapping would be:\n {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", allocationMultiplier: \"2\"}.\n If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", +var map_NodeAllocatableMapping = map[string]string{ + "": "NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. The mapping can be derived from either the count of allocated devices or the specific capacity consumed. These options are mutually exclusive. Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim.", + "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. `capacityMultiplier` must also be set and is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\". The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`.", + "capacityMultiplier": "CapacityMultiplier is used as a multiplier for the allocated capacity consumed. It is only valid if `capacityKey` is set. The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. For example, if a Device's capacity \"dra.example.com/cores\" is consumed, and each \"core\" provides 2 \"cpu\"s, the mapping would be: {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", capacityMultiplier: \"2\"}. If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", + "deviceMultiplier": "DeviceMultiplier is used as a multiplier for the allocated device count in the claim. The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. For example, a DRA driver representing each cache complex (CCX) as a device would have {ResourceName: \"cpu\", deviceMultiplier: \"8\"} in its `nodeAllocatableResources`. If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. It is only valid when `capacityKey` and `capacityMultiplier` are not set.", +} + +func (NodeAllocatableMapping) SwaggerDoc() map[string]string { + return map_NodeAllocatableMapping +} + +var map_NodeAllocatableOverhead = map[string]string{ + "": "NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers.", + "perPod": "PerPod is overhead applied once per pod referencing the claim on this node. This is a flat overhead incurred for every pod referencing the claim.", + "perContainer": "PerContainer is applied per container reference to the claim. This models overhead scaling linearly with the number of containers actively using the device. When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing the claim is computed as: Quantity = PerPod + (PerContainer * NumReferences) Kubelet accounts for this overhead in cgroups: - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once.", +} + +func (NodeAllocatableOverhead) SwaggerDoc() map[string]string { + return map_NodeAllocatableOverhead +} + +var map_NodeAllocatableResource = map[string]string{ + "": "NodeAllocatableResource defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource. At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration.", + "mapping": "Mapping is used when the device directly models a node allocatable resource like standard CPU or memory (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance on the node. To prevent node cgroup isolation friction, the scheduler explicitly blocks sharing mapped device claims across multiple pods.", + "overhead": "Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted for individually for each pod referencing the claim. Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping is specified for the same resource. Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), any overhead specified for the same resource will be subtracted from the node's general allocatable capacity and not from the per-socket capacity pool in Mapping.", } -func (NodeAllocatableResourceMapping) SwaggerDoc() map[string]string { - return map_NodeAllocatableResourceMapping +func (NodeAllocatableResource) SwaggerDoc() map[string]string { + return map_NodeAllocatableResource } var map_OpaqueDeviceConfiguration = map[string]string{ @@ -477,7 +512,7 @@ func (ResourceClaimTemplateSpec) SwaggerDoc() map[string]string { var map_ResourcePool = map[string]string{ "": "ResourcePool describes the pool that ResourceSlices belong to.", - "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", + "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required. A field selector can be used to list only ResourceSlice objects belonging to a certain pool.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", "generation": "Generation tracks the change in a pool over time. Whenever a driver changes something about one or more of the resources in a pool, it must change the generation in all ResourceSlices which are part of that pool. Consumers of ResourceSlices should only consider resources from the pool with the highest generation number. The generation may be reset by drivers, which should be fine for consumers, assuming that all ResourceSlices in a pool are updated to match or deleted.\n\nCombined with ResourceSliceCount, this mechanism enables consumers to detect pools which are comprised of multiple ResourceSlices and are in an incomplete state.", "resourceSliceCount": "ResourceSliceCount is the total number of ResourceSlices in the pool at this generation number. Must be greater than zero.\n\nConsumers can use this to check whether they have seen all ResourceSlices belonging to the same pool.", } @@ -516,6 +551,8 @@ var map_ResourceSliceSpec = map[string]string{ "devices": "Devices lists some or all of the devices in this pool.\n\nMust not have more than 128 entries. If any device uses taints or consumes counters the limit is 64.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.", "perDeviceNodeSelection": "PerDeviceNodeSelection defines whether the access from nodes to resources in the pool is set on the ResourceSlice level or on each device. If it is set to true, every device defined the ResourceSlice must specify this individually.\n\nExactly one of NodeName, NodeSelector, AllNodes, and PerDeviceNodeSelection must be set.", "sharedCounters": "SharedCounters defines a list of counter sets, each of which has a name and a list of counters available.\n\nThe names of the counter sets must be unique in the ResourcePool.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.\n\nThe maximum number of counter sets is 8.", + "partitionTypeAttribute": "PartitionTypeAttribute names a string device attribute (by fully qualified name, e.g. \"gpu.example.com/profile\") whose value labels each device with its partition type, such as \"Full\" or \"Half\" for a MIG-style GPU.\n\nWhen set, every partitionable device in the slice must carry the attribute and devices sharing a value must share the same ConsumesCounters cost.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for the devices in this slice when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. Valid values are:\n\n- \"NodePrepareResources\": NodePrepareResources gRPC calls are skipped. This\n value cannot be specified unless \"NodeUnprepareResources\" is also listed\n (or \"*\" is specified).\n- \"NodeUnprepareResources\": NodeUnprepareResources gRPC calls are skipped. - \"*\": All node-local resource operations are skipped.\n\nOther values may be added in the future. The kubelet must ignore unknown values.", } func (ResourceSliceSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.deepcopy.go index 78ec7b0d5..85ec2bdf6 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.deepcopy.go @@ -159,9 +159,9 @@ func (in *BasicDevice) DeepCopyInto(out *BasicDevice) { *out = new(bool) **out = **in } - if in.NodeAllocatableResourceMappings != nil { - in, out := &in.NodeAllocatableResourceMappings, &out.NodeAllocatableResourceMappings - *out = make(map[corev1.ResourceName]NodeAllocatableResourceMapping, len(*in)) + if in.NodeAllocatableResources != nil { + in, out := &in.NodeAllocatableResources, &out.NodeAllocatableResources + *out = make(map[corev1.ResourceName]NodeAllocatableResource, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -706,6 +706,11 @@ func (in *DeviceCounterConsumption) DeepCopyInto(out *DeviceCounterConsumption) (*out)[key] = *val.DeepCopy() } } + if in.CompatibilityGroups != nil { + in, out := &in.CompatibilityGroups, &out.CompatibilityGroups + *out = make([]string, len(*in)) + copy(*out, *in) + } return } @@ -719,6 +724,22 @@ func (in *DeviceCounterConsumption) DeepCopy() *DeviceCounterConsumption { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceDerivedAttribute) DeepCopyInto(out *DeviceDerivedAttribute) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceDerivedAttribute. +func (in *DeviceDerivedAttribute) DeepCopy() *DeviceDerivedAttribute { + if in == nil { + return nil + } + out := new(DeviceDerivedAttribute) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeviceRequest) DeepCopyInto(out *DeviceRequest) { *out = *in @@ -753,6 +774,11 @@ func (in *DeviceRequest) DeepCopyInto(out *DeviceRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -803,6 +829,11 @@ func (in *DeviceRequestAllocationResult) DeepCopyInto(out *DeviceRequestAllocati (*out)[key] = val.DeepCopy() } } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } @@ -859,6 +890,11 @@ func (in *DeviceSubRequest) DeepCopyInto(out *DeviceSubRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -935,27 +971,84 @@ func (in *NetworkDeviceData) DeepCopy() *NetworkDeviceData { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NodeAllocatableResourceMapping) DeepCopyInto(out *NodeAllocatableResourceMapping) { +func (in *NodeAllocatableMapping) DeepCopyInto(out *NodeAllocatableMapping) { *out = *in if in.CapacityKey != nil { in, out := &in.CapacityKey, &out.CapacityKey *out = new(QualifiedName) **out = **in } - if in.AllocationMultiplier != nil { - in, out := &in.AllocationMultiplier, &out.AllocationMultiplier + if in.CapacityMultiplier != nil { + in, out := &in.CapacityMultiplier, &out.CapacityMultiplier + x := (*in).DeepCopy() + *out = &x + } + if in.DeviceMultiplier != nil { + in, out := &in.DeviceMultiplier, &out.DeviceMultiplier x := (*in).DeepCopy() *out = &x } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResourceMapping. -func (in *NodeAllocatableResourceMapping) DeepCopy() *NodeAllocatableResourceMapping { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableMapping. +func (in *NodeAllocatableMapping) DeepCopy() *NodeAllocatableMapping { if in == nil { return nil } - out := new(NodeAllocatableResourceMapping) + out := new(NodeAllocatableMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableOverhead) DeepCopyInto(out *NodeAllocatableOverhead) { + *out = *in + if in.PerPod != nil { + in, out := &in.PerPod, &out.PerPod + x := (*in).DeepCopy() + *out = &x + } + if in.PerContainer != nil { + in, out := &in.PerContainer, &out.PerContainer + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableOverhead. +func (in *NodeAllocatableOverhead) DeepCopy() *NodeAllocatableOverhead { + if in == nil { + return nil + } + out := new(NodeAllocatableOverhead) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableResource) DeepCopyInto(out *NodeAllocatableResource) { + *out = *in + if in.Mapping != nil { + in, out := &in.Mapping, &out.Mapping + *out = new(NodeAllocatableMapping) + (*in).DeepCopyInto(*out) + } + if in.Overhead != nil { + in, out := &in.Overhead, &out.Overhead + *out = new(NodeAllocatableOverhead) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResource. +func (in *NodeAllocatableResource) DeepCopy() *NodeAllocatableResource { + if in == nil { + return nil + } + out := new(NodeAllocatableResource) in.DeepCopyInto(out) return out } @@ -1286,6 +1379,16 @@ func (in *ResourceSliceSpec) DeepCopyInto(out *ResourceSliceSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.PartitionTypeAttribute != nil { + in, out := &in.PartitionTypeAttribute, &out.PartitionTypeAttribute + *out = new(FullyQualifiedName) + **out = **in + } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.model_name.go index a2887e753..783ec0312 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta1/zz_generated.model_name.go @@ -136,6 +136,11 @@ func (in DeviceCounterConsumption) OpenAPIModelName() string { return "io.k8s.api.resource.v1beta1.DeviceCounterConsumption" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceDerivedAttribute) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta1.DeviceDerivedAttribute" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in DeviceRequest) OpenAPIModelName() string { return "io.k8s.api.resource.v1beta1.DeviceRequest" @@ -172,8 +177,18 @@ func (in NetworkDeviceData) OpenAPIModelName() string { } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in NodeAllocatableResourceMapping) OpenAPIModelName() string { - return "io.k8s.api.resource.v1beta1.NodeAllocatableResourceMapping" +func (in NodeAllocatableMapping) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta1.NodeAllocatableMapping" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableOverhead) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta1.NodeAllocatableOverhead" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableResource) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta1.NodeAllocatableResource" } // OpenAPIModelName returns the OpenAPI model name for this type. diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/generated.pb.go b/constraint/vendor/k8s.io/api/resource/v1beta2/generated.pb.go index 6b5909880..d1aae258e 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/generated.pb.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/generated.pb.go @@ -82,6 +82,8 @@ func (m *DeviceConstraint) Reset() { *m = DeviceConstraint{} } func (m *DeviceCounterConsumption) Reset() { *m = DeviceCounterConsumption{} } +func (m *DeviceDerivedAttribute) Reset() { *m = DeviceDerivedAttribute{} } + func (m *DeviceRequest) Reset() { *m = DeviceRequest{} } func (m *DeviceRequestAllocationResult) Reset() { *m = DeviceRequestAllocationResult{} } @@ -108,7 +110,11 @@ func (m *ExactDeviceRequest) Reset() { *m = ExactDeviceRequest{} } func (m *NetworkDeviceData) Reset() { *m = NetworkDeviceData{} } -func (m *NodeAllocatableResourceMapping) Reset() { *m = NodeAllocatableResourceMapping{} } +func (m *NodeAllocatableMapping) Reset() { *m = NodeAllocatableMapping{} } + +func (m *NodeAllocatableOverhead) Reset() { *m = NodeAllocatableOverhead{} } + +func (m *NodeAllocatableResource) Reset() { *m = NodeAllocatableResource{} } func (m *OpaqueDeviceConfiguration) Reset() { *m = OpaqueDeviceConfiguration{} } @@ -586,14 +592,14 @@ func (m *Device) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.NodeAllocatableResourceMappings) > 0 { - keysForNodeAllocatableResourceMappings := make([]string, 0, len(m.NodeAllocatableResourceMappings)) - for k := range m.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) - } - sort.Strings(keysForNodeAllocatableResourceMappings) - for iNdEx := len(keysForNodeAllocatableResourceMappings) - 1; iNdEx >= 0; iNdEx-- { - v := m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResourceMappings[iNdEx])] + if len(m.NodeAllocatableResources) > 0 { + keysForNodeAllocatableResources := make([]string, 0, len(m.NodeAllocatableResources)) + for k := range m.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) + } + sort.Strings(keysForNodeAllocatableResources) + for iNdEx := len(keysForNodeAllocatableResources) - 1; iNdEx >= 0; iNdEx-- { + v := m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(keysForNodeAllocatableResources[iNdEx])] baseI := i { size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) @@ -605,14 +611,14 @@ func (m *Device) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x12 - i -= len(keysForNodeAllocatableResourceMappings[iNdEx]) - copy(dAtA[i:], keysForNodeAllocatableResourceMappings[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResourceMappings[iNdEx]))) + i -= len(keysForNodeAllocatableResources[iNdEx]) + copy(dAtA[i:], keysForNodeAllocatableResources[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(keysForNodeAllocatableResources[iNdEx]))) i-- dAtA[i] = 0xa i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) i-- - dAtA[i] = 0x6a + dAtA[i] = 0x72 } } if m.AllowMultipleAllocations != nil { @@ -1397,6 +1403,15 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error _ = i var l int _ = l + if len(m.CompatibilityGroups) > 0 { + for iNdEx := len(m.CompatibilityGroups) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.CompatibilityGroups[iNdEx]) + copy(dAtA[i:], m.CompatibilityGroups[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.CompatibilityGroups[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } if len(m.Counters) > 0 { keysForCounters := make([]string, 0, len(m.Counters)) for k := range m.Counters { @@ -1434,6 +1449,39 @@ func (m *DeviceCounterConsumption) MarshalToSizedBuffer(dAtA []byte) (int, error return len(dAtA) - i, nil } +func (m *DeviceDerivedAttribute) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DeviceDerivedAttribute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DeviceDerivedAttribute) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Expression) + copy(dAtA[i:], m.Expression) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Expression))) + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *DeviceRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1508,6 +1556,15 @@ func (m *DeviceRequestAllocationResult) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x5a + } + } if len(m.ConsumedCapacity) > 0 { keysForConsumedCapacity := make([]string, 0, len(m.ConsumedCapacity)) for k := range m.ConsumedCapacity { @@ -1664,6 +1721,20 @@ func (m *DeviceSubRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } if m.Capacity != nil { { size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) @@ -2069,6 +2140,20 @@ func (m *ExactDeviceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DerivedAttributes) > 0 { + for iNdEx := len(m.DerivedAttributes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DerivedAttributes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } if m.Capacity != nil { { size, err := m.Capacity.MarshalToSizedBuffer(dAtA[:i]) @@ -2177,7 +2262,7 @@ func (m *NetworkDeviceData) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { +func (m *NodeAllocatableMapping) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -2187,19 +2272,31 @@ func (m *NodeAllocatableResourceMapping) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *NodeAllocatableResourceMapping) MarshalTo(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *NodeAllocatableResourceMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *NodeAllocatableMapping) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.AllocationMultiplier != nil { + if m.DeviceMultiplier != nil { + { + size, err := m.DeviceMultiplier.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.CapacityMultiplier != nil { { - size, err := m.AllocationMultiplier.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.CapacityMultiplier.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -2219,6 +2316,100 @@ func (m *NodeAllocatableResourceMapping) MarshalToSizedBuffer(dAtA []byte) (int, return len(dAtA) - i, nil } +func (m *NodeAllocatableOverhead) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableOverhead) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableOverhead) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PerContainer != nil { + { + size, err := m.PerContainer.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.PerPod != nil { + { + size, err := m.PerPod.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *NodeAllocatableResource) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *NodeAllocatableResource) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *NodeAllocatableResource) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Overhead != nil { + { + size, err := m.Overhead.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.Mapping != nil { + { + size, err := m.Mapping.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + return len(dAtA) - i, nil +} + func (m *OpaqueDeviceConfiguration) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2773,6 +2964,22 @@ func (m *ResourceSliceSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.SkipNodeOperations) > 0 { + for iNdEx := len(m.SkipNodeOperations) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SkipNodeOperations[iNdEx]) + copy(dAtA[i:], m.SkipNodeOperations[iNdEx]) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.SkipNodeOperations[iNdEx]))) + i-- + dAtA[i] = 0x52 + } + } + if m.PartitionTypeAttribute != nil { + i -= len(*m.PartitionTypeAttribute) + copy(dAtA[i:], *m.PartitionTypeAttribute) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PartitionTypeAttribute))) + i-- + dAtA[i] = 0x4a + } if len(m.SharedCounters) > 0 { for iNdEx := len(m.SharedCounters) - 1; iNdEx >= 0; iNdEx-- { { @@ -3092,8 +3299,8 @@ func (m *Device) Size() (n int) { if m.AllowMultipleAllocations != nil { n += 2 } - if len(m.NodeAllocatableResourceMappings) > 0 { - for k, v := range m.NodeAllocatableResourceMappings { + if len(m.NodeAllocatableResources) > 0 { + for k, v := range m.NodeAllocatableResources { _ = k _ = v l = v.Size() @@ -3365,6 +3572,25 @@ func (m *DeviceCounterConsumption) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.CompatibilityGroups) > 0 { + for _, s := range m.CompatibilityGroups { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DeviceDerivedAttribute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Expression) + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -3437,6 +3663,12 @@ func (m *DeviceRequestAllocationResult) Size() (n int) { n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) } } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3482,6 +3714,12 @@ func (m *DeviceSubRequest) Size() (n int) { l = m.Capacity.Size() n += 1 + l + sovGenerated(uint64(l)) } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3637,6 +3875,12 @@ func (m *ExactDeviceRequest) Size() (n int) { l = m.Capacity.Size() n += 1 + l + sovGenerated(uint64(l)) } + if len(m.DerivedAttributes) > 0 { + for _, e := range m.DerivedAttributes { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -3659,7 +3903,7 @@ func (m *NetworkDeviceData) Size() (n int) { return n } -func (m *NodeAllocatableResourceMapping) Size() (n int) { +func (m *NodeAllocatableMapping) Size() (n int) { if m == nil { return 0 } @@ -3669,8 +3913,46 @@ func (m *NodeAllocatableResourceMapping) Size() (n int) { l = len(*m.CapacityKey) n += 1 + l + sovGenerated(uint64(l)) } - if m.AllocationMultiplier != nil { - l = m.AllocationMultiplier.Size() + if m.CapacityMultiplier != nil { + l = m.CapacityMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DeviceMultiplier != nil { + l = m.DeviceMultiplier.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableOverhead) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PerPod != nil { + l = m.PerPod.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.PerContainer != nil { + l = m.PerContainer.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *NodeAllocatableResource) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Mapping != nil { + l = m.Mapping.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Overhead != nil { + l = m.Overhead.Size() n += 1 + l + sovGenerated(uint64(l)) } return n @@ -3896,6 +4178,16 @@ func (m *ResourceSliceSpec) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) } } + if m.PartitionTypeAttribute != nil { + l = len(*m.PartitionTypeAttribute) + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.SkipNodeOperations) > 0 { + for _, s := range m.SkipNodeOperations { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } return n } @@ -4062,16 +4354,16 @@ func (this *Device) String() string { mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[QualifiedName(k)]) } mapStringForCapacity += "}" - keysForNodeAllocatableResourceMappings := make([]string, 0, len(this.NodeAllocatableResourceMappings)) - for k := range this.NodeAllocatableResourceMappings { - keysForNodeAllocatableResourceMappings = append(keysForNodeAllocatableResourceMappings, string(k)) + keysForNodeAllocatableResources := make([]string, 0, len(this.NodeAllocatableResources)) + for k := range this.NodeAllocatableResources { + keysForNodeAllocatableResources = append(keysForNodeAllocatableResources, string(k)) } - sort.Strings(keysForNodeAllocatableResourceMappings) - mapStringForNodeAllocatableResourceMappings := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping{" - for _, k := range keysForNodeAllocatableResourceMappings { - mapStringForNodeAllocatableResourceMappings += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(k)]) + sort.Strings(keysForNodeAllocatableResources) + mapStringForNodeAllocatableResources := "map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource{" + for _, k := range keysForNodeAllocatableResources { + mapStringForNodeAllocatableResources += fmt.Sprintf("%v: %v,", k, this.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(k)]) } - mapStringForNodeAllocatableResourceMappings += "}" + mapStringForNodeAllocatableResources += "}" s := strings.Join([]string{`&Device{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `Attributes:` + mapStringForAttributes + `,`, @@ -4085,7 +4377,7 @@ func (this *Device) String() string { `BindingConditions:` + fmt.Sprintf("%v", this.BindingConditions) + `,`, `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `AllowMultipleAllocations:` + valueToStringGenerated(this.AllowMultipleAllocations) + `,`, - `NodeAllocatableResourceMappings:` + mapStringForNodeAllocatableResourceMappings + `,`, + `NodeAllocatableResources:` + mapStringForNodeAllocatableResources + `,`, `}`, }, "") return s @@ -4287,6 +4579,18 @@ func (this *DeviceCounterConsumption) String() string { s := strings.Join([]string{`&DeviceCounterConsumption{`, `CounterSet:` + fmt.Sprintf("%v", this.CounterSet) + `,`, `Counters:` + mapStringForCounters + `,`, + `CompatibilityGroups:` + fmt.Sprintf("%v", this.CompatibilityGroups) + `,`, + `}`, + }, "") + return s +} +func (this *DeviceDerivedAttribute) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeviceDerivedAttribute{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Expression:` + fmt.Sprintf("%v", this.Expression) + `,`, `}`, }, "") return s @@ -4338,6 +4642,7 @@ func (this *DeviceRequestAllocationResult) String() string { `BindingFailureConditions:` + fmt.Sprintf("%v", this.BindingFailureConditions) + `,`, `ShareID:` + valueToStringGenerated(this.ShareID) + `,`, `ConsumedCapacity:` + mapStringForConsumedCapacity + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, `}`, }, "") return s @@ -4366,6 +4671,11 @@ func (this *DeviceSubRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&DeviceSubRequest{`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, @@ -4374,6 +4684,7 @@ func (this *DeviceSubRequest) String() string { `Count:` + fmt.Sprintf("%v", this.Count) + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, `}`, }, "") return s @@ -4472,6 +4783,11 @@ func (this *ExactDeviceRequest) String() string { repeatedStringForTolerations += strings.Replace(strings.Replace(f.String(), "DeviceToleration", "DeviceToleration", 1), `&`, ``, 1) + "," } repeatedStringForTolerations += "}" + repeatedStringForDerivedAttributes := "[]DeviceDerivedAttribute{" + for _, f := range this.DerivedAttributes { + repeatedStringForDerivedAttributes += strings.Replace(strings.Replace(f.String(), "DeviceDerivedAttribute", "DeviceDerivedAttribute", 1), `&`, ``, 1) + "," + } + repeatedStringForDerivedAttributes += "}" s := strings.Join([]string{`&ExactDeviceRequest{`, `DeviceClassName:` + fmt.Sprintf("%v", this.DeviceClassName) + `,`, `Selectors:` + repeatedStringForSelectors + `,`, @@ -4480,6 +4796,7 @@ func (this *ExactDeviceRequest) String() string { `AdminAccess:` + valueToStringGenerated(this.AdminAccess) + `,`, `Tolerations:` + repeatedStringForTolerations + `,`, `Capacity:` + strings.Replace(this.Capacity.String(), "CapacityRequirements", "CapacityRequirements", 1) + `,`, + `DerivedAttributes:` + repeatedStringForDerivedAttributes + `,`, `}`, }, "") return s @@ -4496,13 +4813,36 @@ func (this *NetworkDeviceData) String() string { }, "") return s } -func (this *NodeAllocatableResourceMapping) String() string { +func (this *NodeAllocatableMapping) String() string { if this == nil { return "nil" } - s := strings.Join([]string{`&NodeAllocatableResourceMapping{`, + s := strings.Join([]string{`&NodeAllocatableMapping{`, `CapacityKey:` + valueToStringGenerated(this.CapacityKey) + `,`, - `AllocationMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.AllocationMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `CapacityMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.CapacityMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `DeviceMultiplier:` + strings.Replace(fmt.Sprintf("%v", this.DeviceMultiplier), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableOverhead) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableOverhead{`, + `PerPod:` + strings.Replace(fmt.Sprintf("%v", this.PerPod), "Quantity", "resource.Quantity", 1) + `,`, + `PerContainer:` + strings.Replace(fmt.Sprintf("%v", this.PerContainer), "Quantity", "resource.Quantity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAllocatableResource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAllocatableResource{`, + `Mapping:` + strings.Replace(this.Mapping.String(), "NodeAllocatableMapping", "NodeAllocatableMapping", 1) + `,`, + `Overhead:` + strings.Replace(this.Overhead.String(), "NodeAllocatableOverhead", "NodeAllocatableOverhead", 1) + `,`, `}`, }, "") return s @@ -4691,6 +5031,8 @@ func (this *ResourceSliceSpec) String() string { `Devices:` + repeatedStringForDevices + `,`, `PerDeviceNodeSelection:` + valueToStringGenerated(this.PerDeviceNodeSelection) + `,`, `SharedCounters:` + repeatedStringForSharedCounters + `,`, + `PartitionTypeAttribute:` + valueToStringGenerated(this.PartitionTypeAttribute) + `,`, + `SkipNodeOperations:` + fmt.Sprintf("%v", this.SkipNodeOperations) + `,`, `}`, }, "") return s @@ -6595,9 +6937,9 @@ func (m *Device) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.AllowMultipleAllocations = &b - case 13: + case 14: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResourceMappings", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NodeAllocatableResources", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -6624,11 +6966,11 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.NodeAllocatableResourceMappings == nil { - m.NodeAllocatableResourceMappings = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResourceMapping) + if m.NodeAllocatableResources == nil { + m.NodeAllocatableResources = make(map[k8s_io_api_core_v1.ResourceName]NodeAllocatableResource) } var mapkey k8s_io_api_core_v1.ResourceName - mapvalue := &NodeAllocatableResourceMapping{} + mapvalue := &NodeAllocatableResource{} for iNdEx < postIndex { entryPreIndex := iNdEx var wire uint64 @@ -6702,7 +7044,7 @@ func (m *Device) Unmarshal(dAtA []byte) error { if postmsgIndex > l { return io.ErrUnexpectedEOF } - mapvalue = &NodeAllocatableResourceMapping{} + mapvalue = &NodeAllocatableResource{} if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { return err } @@ -6722,7 +7064,7 @@ func (m *Device) Unmarshal(dAtA []byte) error { iNdEx += skippy } } - m.NodeAllocatableResourceMappings[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue + m.NodeAllocatableResources[k8s_io_api_core_v1.ResourceName(mapkey)] = *mapvalue iNdEx = postIndex default: iNdEx = preIndex @@ -8654,16 +8996,162 @@ func (m *DeviceCounterConsumption) Unmarshal(dAtA []byte) error { } m.Counters[mapkey] = *mapvalue iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompatibilityGroups", wireType) } - if (iNdEx + skippy) > l { + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompatibilityGroups = append(m.CompatibilityGroups, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DeviceDerivedAttribute) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DeviceDerivedAttribute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DeviceDerivedAttribute: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = FullyQualifiedName(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Expression", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Expression = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy @@ -9265,6 +9753,38 @@ func (m *DeviceRequestAllocationResult) Unmarshal(dAtA []byte) error { } m.ConsumedCapacity[QualifiedName(mapkey)] = *mapvalue iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9620,6 +10140,40 @@ func (m *DeviceSubRequest) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -10876,6 +11430,40 @@ func (m *ExactDeviceRequest) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DerivedAttributes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DerivedAttributes = append(m.DerivedAttributes, DeviceDerivedAttribute{}) + if err := m.DerivedAttributes[len(m.DerivedAttributes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -11043,7 +11631,7 @@ func (m *NetworkDeviceData) Unmarshal(dAtA []byte) error { } return nil } -func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { +func (m *NodeAllocatableMapping) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -11066,10 +11654,10 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: wiretype end group for non-group") + return fmt.Errorf("proto: NodeAllocatableMapping: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: NodeAllocatableResourceMapping: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: NodeAllocatableMapping: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -11107,7 +11695,7 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllocationMultiplier", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CapacityMultiplier", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -11134,29 +11722,309 @@ func (m *NodeAllocatableResourceMapping) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.AllocationMultiplier == nil { - m.AllocationMultiplier = &resource.Quantity{} + if m.CapacityMultiplier == nil { + m.CapacityMultiplier = &resource.Quantity{} } - if err := m.AllocationMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.CapacityMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeviceMultiplier", wireType) } - iNdEx += skippy - } - } - + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DeviceMultiplier == nil { + m.DeviceMultiplier = &resource.Quantity{} + } + if err := m.DeviceMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NodeAllocatableOverhead) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodeAllocatableOverhead: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodeAllocatableOverhead: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PerPod", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PerPod == nil { + m.PerPod = &resource.Quantity{} + } + if err := m.PerPod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PerContainer", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PerContainer == nil { + m.PerContainer = &resource.Quantity{} + } + if err := m.PerContainer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *NodeAllocatableResource) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: NodeAllocatableResource: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: NodeAllocatableResource: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Mapping", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Mapping == nil { + m.Mapping = &NodeAllocatableMapping{} + } + if err := m.Mapping.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Overhead", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Overhead == nil { + m.Overhead = &NodeAllocatableOverhead{} + } + if err := m.Overhead.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + if iNdEx > l { return io.ErrUnexpectedEOF } @@ -12933,6 +13801,71 @@ func (m *ResourceSliceSpec) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PartitionTypeAttribute", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := FullyQualifiedName(dAtA[iNdEx:postIndex]) + m.PartitionTypeAttribute = &s + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SkipNodeOperations", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SkipNodeOperations = append(m.SkipNodeOperations, SkipNodeOperation(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/generated.proto b/constraint/vendor/k8s.io/api/resource/v1beta2/generated.proto index 82bb033b3..3268169ce 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/generated.proto +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/generated.proto @@ -65,8 +65,8 @@ message AllocatedDeviceStatus { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 7; // Conditions contains the latest observation of the device's state. @@ -78,6 +78,9 @@ message AllocatedDeviceStatus { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 4; // Data contains arbitrary driver-specific data. @@ -90,7 +93,7 @@ message AllocatedDeviceStatus { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional NetworkDeviceData networkData = 6; } @@ -130,7 +133,7 @@ message CELDeviceSelector { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -163,6 +166,15 @@ message CELDeviceSelector { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -232,6 +244,13 @@ message CapacityRequestPolicy { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -315,8 +334,8 @@ message CounterSet { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string name = 1; // Counters defines the set of counters for this CounterSet @@ -325,8 +344,8 @@ message CounterSet { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; } @@ -345,7 +364,7 @@ message Device { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional map attributes = 2; // Capacity defines the set of capacities for this device. @@ -366,13 +385,13 @@ message Device { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 repeated DeviceCounterConsumption consumesCounters = 4; // NodeName identifies the node where the device is available. @@ -419,7 +438,7 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceTaint taints = 8; // BindsToNode indicates if the usage of an allocation involving this device @@ -449,8 +468,8 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 10; // BindingFailureConditions defines the conditions for binding failure. @@ -467,8 +486,8 @@ message Device { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 11; // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -480,7 +499,7 @@ message Device { // +featureGate=DRAConsumableCapacity optional bool allowMultipleAllocations = 12; - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -492,8 +511,9 @@ message Device { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - map nodeAllocatableResourceMappings = 13; + map nodeAllocatableResources = 14; } // DeviceAllocationConfiguration gets embedded in an AllocationResult. @@ -503,7 +523,7 @@ message DeviceAllocationConfiguration { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string source = 1; // Requests lists the names of requests where the configuration applies. @@ -515,10 +535,10 @@ message DeviceAllocationConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 2; optional DeviceConfiguration deviceConfiguration = 3; @@ -530,8 +550,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequestAllocationResult results = 1; // This field is a combination of all the claim and class configuration parameters. @@ -544,8 +564,8 @@ message DeviceAllocationResult { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 repeated DeviceAllocationConfiguration config = 2; } @@ -554,30 +574,30 @@ message DeviceAttribute { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional int64 int = 2; // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional bool bool = 3; // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string string = 4; // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember optional string version = 5; // IntValues is a non-empty list of numbers. @@ -587,8 +607,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated int64 ints = 6; @@ -597,8 +617,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated bool bools = 7; @@ -610,8 +630,9 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes repeated string strings = 8; @@ -623,8 +644,8 @@ message DeviceAttribute { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes repeated string versions = 9; } @@ -662,11 +683,11 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceRequest requests = 1; // These constraints must be satisfied by the set of devices that get @@ -674,8 +695,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceConstraint constraints = 2; // This field holds configuration for multiple potential drivers which @@ -684,8 +705,8 @@ message DeviceClaim { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClaimConfiguration config = 3; } @@ -700,10 +721,10 @@ message DeviceClaimConfiguration { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; optional DeviceConfiguration deviceConfiguration = 2; @@ -719,8 +740,8 @@ message DeviceClaimConfiguration { message DeviceClass { // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec defines what can be allocated and how to configure it. @@ -731,6 +752,7 @@ message DeviceClass { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional optional DeviceClassSpec spec = 2; } @@ -756,8 +778,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 1; // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -768,8 +790,8 @@ message DeviceClassSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceClassConfiguration config = 2; // ExtendedResourceName is the extended resource name for the devices of this class. @@ -781,11 +803,10 @@ message DeviceClassSpec { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name optional string extendedResourceName = 4; } @@ -797,7 +818,7 @@ message DeviceConfiguration { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional OpaqueDeviceConfiguration opaque = 1; } @@ -815,10 +836,10 @@ message DeviceConstraint { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated string requests = 1; // MatchAttribute requires that all devices in question have this @@ -841,8 +862,8 @@ message DeviceConstraint { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string matchAttribute = 2; // DistinctAttribute requires that all devices in question have this @@ -864,6 +885,8 @@ message DeviceConstraint { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name optional string distinctAttribute = 3; } @@ -874,8 +897,8 @@ message DeviceCounterConsumption { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name optional string counterSet = 1; // Counters defines the counters that will be consumed by the device. @@ -883,9 +906,94 @@ message DeviceCounterConsumption { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name map counters = 2; + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + repeated string compatibilityGroups = 3; +} + +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +message DeviceDerivedAttribute { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + optional string name = 1; + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + optional string expression = 2; } // DeviceRequest is a request for devices required for a claim. @@ -914,7 +1022,7 @@ message DeviceRequest { // // +optional // +oneOf=deviceRequestType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional ExactDeviceRequest exactly = 2; // FirstAvailable contains subrequests, of which exactly one will be @@ -935,11 +1043,11 @@ message DeviceRequest { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated DeviceSubRequest firstAvailable = 3; } @@ -964,9 +1072,9 @@ message DeviceRequestAllocationResult { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required optional string driver = 2; // This name together with the driver name and the device name field @@ -976,8 +1084,8 @@ message DeviceRequestAllocationResult { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name optional string pool = 3; // Device references one device instance via its name in the driver's @@ -1009,7 +1117,7 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // BindingConditions contains a copy of the BindingConditions @@ -1021,8 +1129,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingConditions = 7; // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1034,8 +1142,8 @@ message DeviceRequestAllocationResult { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 repeated string bindingFailureConditions = 8; // ShareID uniquely identifies an individual allocation share of the device, @@ -1045,8 +1153,8 @@ message DeviceRequestAllocationResult { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid optional string shareID = 9; // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -1061,6 +1169,19 @@ message DeviceRequestAllocationResult { // +optional // +featureGate=DRAConsumableCapacity map consumedCapacity = 10; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 11; } // DeviceSelector must have exactly one field set. @@ -1103,8 +1224,8 @@ message DeviceSubRequest { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name optional string deviceClassName = 2; // Selectors define criteria which must be satisfied by a specific @@ -1114,8 +1235,8 @@ message DeviceSubRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 3; // AllocationMode and its related fields define how devices are allocated @@ -1137,7 +1258,7 @@ message DeviceSubRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 4; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1168,7 +1289,7 @@ message DeviceSubRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // Capacity define resource requirements against each capacity. @@ -1187,6 +1308,34 @@ message DeviceSubRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 7; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 8; } // The device this taint is attached to has the "effect" on @@ -1215,7 +1364,7 @@ message DeviceTaint { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required optional string effect = 3; // TimeAdded represents the time at which the taint was added or @@ -1237,6 +1386,7 @@ message DeviceTaint { // DeviceTaintRule adds one taint to all devices which match the selector. // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" message DeviceTaintRule { // Standard object metadata // +optional @@ -1308,6 +1458,9 @@ message DeviceTaintRuleStatus { // +listMapKey=type // +patchStrategy=merge // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; } @@ -1351,8 +1504,8 @@ message DeviceToleration { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key optional string key = 1; // Operator represents a key's relationship to the value. @@ -1362,7 +1515,7 @@ message DeviceToleration { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string operator = 2; // Value is the taint value the toleration matches to. @@ -1376,7 +1529,7 @@ message DeviceToleration { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string effect = 4; // TolerationSeconds represents the period of time the toleration (which must be @@ -1414,8 +1567,8 @@ message ExactDeviceRequest { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 repeated DeviceSelector selectors = 2; // AllocationMode and its related fields define how devices are allocated @@ -1438,7 +1591,7 @@ message ExactDeviceRequest { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional optional string allocationMode = 3; // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1483,7 +1636,7 @@ message ExactDeviceRequest { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional repeated DeviceToleration tolerations = 6; // Capacity define resource requirements against each capacity. @@ -1502,6 +1655,34 @@ message ExactDeviceRequest { // +optional // +featureGate=DRAConsumableCapacity optional CapacityRequirements capacity = 7; + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + repeated DeviceDerivedAttribute derivedAttributes = 8; } // NetworkDeviceData provides network-related details for the allocated device. @@ -1515,8 +1696,8 @@ message NetworkDeviceData { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 optional string interfaceName = 1; // IPs lists the network addresses assigned to the device's network interface. @@ -1527,10 +1708,10 @@ message NetworkDeviceData { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 repeated string ips = 2; // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -1538,47 +1719,104 @@ message NetworkDeviceData { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 optional string hardwareAddress = 3; } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -message NodeAllocatableResourceMapping { +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +message NodeAllocatableMapping { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") optional string capacityKey = 1; - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - optional .k8s.io.apimachinery.pkg.api.resource.Quantity allocationMultiplier = 2; + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + optional .k8s.io.apimachinery.pkg.api.resource.Quantity capacityMultiplier = 2; + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + optional .k8s.io.apimachinery.pkg.api.resource.Quantity deviceMultiplier = 3; +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +message NodeAllocatableOverhead { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perPod = 1; + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + optional .k8s.io.apimachinery.pkg.api.resource.Quantity perContainer = 2; +} + +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +message NodeAllocatableResource { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + optional NodeAllocatableMapping mapping = 3; + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + optional NodeAllocatableOverhead overhead = 4; } // OpaqueDeviceConfiguration contains configuration parameters for a driver @@ -1594,9 +1832,9 @@ message OpaqueDeviceConfiguration { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless optional string driver = 1; // Parameters can contain arbitrary data. It is the responsibility of @@ -1625,7 +1863,8 @@ message ResourceClaim { // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional optional ResourceClaimSpec spec = 2; // Status describes whether the claim is ready to use and what has been allocated. @@ -1680,8 +1919,8 @@ message ResourceClaimStatus { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify optional AllocationResult allocation = 1; // ReservedFor indicates which entities are currently allowed to use @@ -1709,10 +1948,10 @@ message ResourceClaimStatus { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 repeated ResourceClaimConsumerReference reservedFor = 2; // Devices contains the status of each device allocated for this @@ -1720,18 +1959,18 @@ message ResourceClaimStatus { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID repeated AllocatedDeviceStatus devices = 4; } @@ -1749,6 +1988,7 @@ message ResourceClaimTemplate { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional optional ResourceClaimTemplateSpec spec = 2; } @@ -1768,11 +2008,13 @@ message ResourceClaimTemplateSpec { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional optional ResourceClaimSpec spec = 2; } @@ -1780,6 +2022,8 @@ message ResourceClaimTemplateSpec { message ResourcePool { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -1920,7 +2164,7 @@ message ResourceSliceSpec { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType repeated Device devices = 6; @@ -1946,14 +2190,50 @@ message ResourceSliceSpec { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 repeated CounterSet sharedCounters = 8; + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + optional string partitionTypeAttribute = 9; + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + repeated string skipNodeOperations = 10; } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/types.go b/constraint/vendor/k8s.io/api/resource/v1beta2/types.go index 47a46355f..04b5e9fbc 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/types.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/types.go @@ -78,7 +78,7 @@ const ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceSlice struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -97,6 +97,9 @@ const ( // ResourceSliceSelectorDriver can be used in a [metav1.ListOptions] // field selector to filter based on [ResourceSliceSpec.Driver]. ResourceSliceSelectorDriver = "spec.driver" + // ResourceSliceSelectorPoolName can be used in a [metav1.ListOptions] + // field selector to filter based on [ResourceSliceSpec.Pool.Name]. + ResourceSliceSelectorPoolName = "spec.pool.name" ) // ResourceSliceSpec contains the information published by the driver in one ResourceSlice. @@ -160,7 +163,7 @@ type ResourceSliceSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +zeroOrOneOf=ResourceSliceType Devices []Device `json:"devices,omitempty" protobuf:"bytes,6,name=devices"` @@ -186,17 +189,68 @@ type ResourceSliceSpec struct { // The maximum number of counter sets is 8. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name // +featureGate=DRAPartitionableDevices // +zeroOrOneOf=ResourceSliceType - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 SharedCounters []CounterSet `json:"sharedCounters,omitempty" protobuf:"bytes,8,name=sharedCounters"` + + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + // + // +optional + // +featureGate=DRAPartitionableDevicesType + // +k8s:ifDisabled(DRAPartitionableDevicesType)=+k8s:forbidden + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:optional + // +k8s:ifEnabled(DRAPartitionableDevicesType)=+k8s:format=k8s-resource-fully-qualified-name + PartitionTypeAttribute *FullyQualifiedName `json:"partitionTypeAttribute,omitempty" protobuf:"bytes,9,opt,name=partitionTypeAttribute"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,10,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } +// +enum +// +k8s:enum +type SkipNodeOperation string + +const ( + // SkipNodeOperationNodePrepareResources indicates that NodePrepareResources gRPC calls are skipped. + SkipNodeOperationNodePrepareResources SkipNodeOperation = "NodePrepareResources" + + // SkipNodeOperationNodeUnprepareResources indicates that NodeUnprepareResources gRPC calls are skipped. + SkipNodeOperationNodeUnprepareResources SkipNodeOperation = "NodeUnprepareResources" + + // SkipNodeOperationAll indicates that all node-local resource operations are skipped. + SkipNodeOperationAll SkipNodeOperation = "*" +) + // CounterSet defines a named set of counters // that are available to be used by devices defined in the // ResourcePool. @@ -210,8 +264,8 @@ type CounterSet struct { // It must be a DNS label. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name Name string `json:"name" protobuf:"bytes,1,name=name"` // Counters defines the set of counters for this CounterSet @@ -220,8 +274,8 @@ type CounterSet struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,name=counters"` } @@ -233,6 +287,8 @@ const DriverNameMaxLength = 63 type ResourcePool struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. @@ -297,6 +353,10 @@ const ResourceSliceMaxDeviceCounterConsumptionsPerDevice = 2 // per device counter consumption. const ResourceSliceMaxCountersPerDeviceCounterConsumption = 32 +// Defines the maximum number of compatibility groups that can be +// declared per device counter consumption. +const DeviceCompatibilityGroupsMaxSize = 2 + // Device represents one individual hardware instance that can be selected based // on its attributes. Besides the name, exactly one field must be set. type Device struct { @@ -312,7 +372,7 @@ type Device struct { // The maximum number of attributes and capacities combined is 32. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Attributes map[QualifiedName]DeviceAttribute `json:"attributes,omitempty" protobuf:"bytes,2,rep,name=attributes"` // Capacity defines the set of capacities for this device. @@ -333,13 +393,13 @@ type Device struct { // device is 2. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=counterSet + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=counterSet // +featureGate=DRAPartitionableDevices - // +k8s:alpha(since: "1.36")=+k8s:maxItems=2 + // +k8s:beta(since: "1.37")=+k8s:maxItems=2 ConsumesCounters []DeviceCounterConsumption `json:"consumesCounters,omitempty" protobuf:"bytes,4,rep,name=consumesCounters"` // NodeName identifies the node where the device is available. @@ -386,7 +446,7 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Taints []DeviceTaint `json:"taints,omitempty" protobuf:"bytes,8,rep,name=taints"` // BindsToNode indicates if the usage of an allocation involving this device @@ -416,8 +476,8 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,10,rep,name=bindingConditions"` // BindingFailureConditions defines the conditions for binding failure. @@ -434,8 +494,8 @@ type Device struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,11,rep,name=bindingFailureConditions"` // AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests. @@ -447,7 +507,10 @@ type Device struct { // +featureGate=DRAConsumableCapacity AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty" protobuf:"bytes,12,opt,name=allowMultipleAllocations"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResourceMappings is tombstoned as it got replaced with NodeAllocatableResources. + // NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,13,opt,name=nodeAllocatableResourceMappings"` + + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -459,46 +522,104 @@ type Device struct { // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. // +optional + // +k8s:optional // +featureGate=DRANodeAllocatableResources - NodeAllocatableResourceMappings map[v1.ResourceName]NodeAllocatableResourceMapping `json:"nodeAllocatableResourceMappings,omitempty" protobuf:"bytes,13,opt,name=nodeAllocatableResourceMappings"` + NodeAllocatableResources map[v1.ResourceName]NodeAllocatableResource `json:"nodeAllocatableResources,omitempty" protobuf:"bytes,14,opt,name=nodeAllocatableResources"` } -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity +// NodeAllocatableResource defines the translation between the DRA device/capacity // units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMapping struct { +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResource struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + // +optional + // +k8s:optional + Mapping *NodeAllocatableMapping `json:"mapping,omitempty" protobuf:"bytes,3,opt,name=mapping"` + + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + // +optional + // +k8s:optional + Overhead *NodeAllocatableOverhead `json:"overhead,omitempty" protobuf:"bytes,4,opt,name=overhead"` +} + +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMapping struct { // CapacityKey references a capacity name defined as a key in the // `spec.devices[*].capacity` map. When this field is set, the value associated with // this key in the `status.allocation.devices.results[*].consumedCapacity` map // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is + // the node allocatable resource. `capacityMultiplier` must also be set and is // multiplied with the base quantity. // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", // and this field is set to "dra.example.com/memory", then for a claim allocation // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityMultiplier") CapacityKey *QualifiedName `json:"capacityKey,omitempty" protobuf:"bytes,1,opt,name=capacityKey"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - // +optional - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty" protobuf:"bytes,2,opt,name=allocationMultiplier"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + // +optional + // +k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("capacityKey") + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty" protobuf:"bytes,2,opt,name=capacityMultiplier"` + + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + // +optional + // +k8s:optional + // +k8s:unionMember + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty" protobuf:"bytes,3,opt,name=deviceMultiplier"` +} + +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverhead struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + // +optional + // +k8s:optional + PerPod *resource.Quantity `json:"perPod,omitempty" protobuf:"bytes,1,opt,name=perPod"` + + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // +optional + // +k8s:optional + PerContainer *resource.Quantity `json:"perContainer,omitempty" protobuf:"bytes,2,opt,name=perContainer"` } // DeviceCounterConsumption defines a set of counters that @@ -508,8 +629,8 @@ type DeviceCounterConsumption struct { // counters defined will be consumed. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-short-name CounterSet string `json:"counterSet" protobuf:"bytes,1,opt,name=counterSet"` // Counters defines the counters that will be consumed by the device. @@ -517,9 +638,39 @@ type DeviceCounterConsumption struct { // The maximum number of counters is 32. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:eachKey=+k8s:format=k8s-short-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:eachKey=+k8s:format=k8s-short-name Counters map[string]Counter `json:"counters,omitempty" protobuf:"bytes,2,opt,name=counters"` + + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + // + // +optional + // +listType=atomic + // +featureGate=DRADeviceCompatibilityGroups + // +k8s:listType=atomic + // +k8s:optional + // +k8s:maxItems=2 + // +k8s:unique=set + // +k8s:eachVal=+k8s:format=k8s-short-name + CompatibilityGroups []string `json:"compatibilityGroups,omitempty" protobuf:"bytes,3,rep,name=compatibilityGroups"` } // DeviceCapacity describes a quantity associated with a device. @@ -603,6 +754,13 @@ type CapacityRequestPolicy struct { // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). @@ -682,30 +840,30 @@ type DeviceAttribute struct { // IntValue is a number. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember IntValue *int64 `json:"int,omitempty" protobuf:"varint,2,opt,name=int"` // BoolValue is a true/false value. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember BoolValue *bool `json:"bool,omitempty" protobuf:"varint,3,opt,name=bool"` // StringValue is a string. Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember StringValue *string `json:"string,omitempty" protobuf:"bytes,4,opt,name=string"` // VersionValue is a semantic version according to semver.org spec 2.0.0. // Must not be longer than 64 characters. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember VersionValue *string `json:"version,omitempty" protobuf:"bytes,5,opt,name=version"` // IntValues is a non-empty list of numbers. @@ -715,8 +873,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes IntValues []int64 `json:"ints,omitempty" protobuf:"varint,6,opt,name=ints"` @@ -725,8 +883,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes BoolValues []bool `json:"bools,omitempty" protobuf:"varint,7,opt,name=bools"` @@ -738,8 +896,9 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember + // +k8s:alpha(since: "1.37")=+k8s:eachVal=+k8s:maxBytes=64 // +featureGate=DRAListTypeAttributes StringValues []string `json:"strings,omitempty" protobuf:"bytes,8,opt,name=strings"` @@ -751,8 +910,8 @@ type DeviceAttribute struct { // +optional // +listType=atomic // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:unionMember + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:unionMember // +featureGate=DRAListTypeAttributes VersionValues []string `json:"versions,omitempty" protobuf:"bytes,9,opt,name=versions"` } @@ -789,7 +948,7 @@ type DeviceTaint struct { // Consumers must treat unknown effects like None. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Effect DeviceTaintEffect `json:"effect" protobuf:"bytes,3,name=effect,casttype=DeviceTaintEffect"` // ^^^^ @@ -828,7 +987,7 @@ type DeviceTaint struct { } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTaintEffect string const ( @@ -852,8 +1011,9 @@ const ( // DeviceTaintRule adds one taint to all devices which match the selector. // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. +// +k8s:supportsSubresource="/status" type DeviceTaintRule struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -971,6 +1131,9 @@ type DeviceTaintRuleStatus struct { // +listMapKey=type // +patchStrategy=merge // +patchMergeKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` } @@ -985,7 +1148,7 @@ const DeviceTaintConditionEvictionInProgress = "EvictionInProgress" // DeviceTaintRuleList is a collection of DeviceTaintRules. type DeviceTaintRuleList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -999,7 +1162,7 @@ type DeviceTaintRuleList struct { // ResourceSliceList is a collection of ResourceSlices. type ResourceSliceList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -1022,14 +1185,15 @@ type ResourceSliceList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaim struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec describes what is being requested and how to configure it. // The spec is immutable. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` // Status describes whether the claim is ready to use and what has been allocated. @@ -1057,11 +1221,11 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []DeviceRequest `json:"requests" protobuf:"bytes,1,name=requests"` // These constraints must be satisfied by the set of devices that get @@ -1069,8 +1233,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Constraints []DeviceConstraint `json:"constraints,omitempty" protobuf:"bytes,2,opt,name=constraints"` // This field holds configuration for multiple potential drivers which @@ -1079,8 +1243,8 @@ type DeviceClaim struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClaimConfiguration `json:"config,omitempty" protobuf:"bytes,3,opt,name=config"` // Potential future extension, ignored by older schedulers. This is @@ -1131,7 +1295,7 @@ type DeviceRequest struct { // // +optional // +oneOf=deviceRequestType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Exactly *ExactDeviceRequest `json:"exactly,omitempty" protobuf:"bytes,2,name=exactly"` // FirstAvailable contains subrequests, of which exactly one will be @@ -1152,11 +1316,11 @@ type DeviceRequest struct { // +oneOf=deviceRequestType // +listType=atomic // +featureGate=DRAPrioritizedList - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=name - // +k8s:alpha(since: "1.36")=+k8s:maxItems=8 + // +k8s:beta(since: "1.37")=+k8s:unique=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=name + // +k8s:beta(since: "1.37")=+k8s:maxItems=8 FirstAvailable []DeviceSubRequest `json:"firstAvailable,omitempty" protobuf:"bytes,3,name=firstAvailable"` } @@ -1184,8 +1348,8 @@ type ExactDeviceRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,2,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1208,7 +1372,7 @@ type ExactDeviceRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,3,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1253,7 +1417,7 @@ type ExactDeviceRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1272,6 +1436,34 @@ type ExactDeviceRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,7,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,8,rep,name=derivedAttributes"` } // DeviceSubRequest describes a request for device provided in the @@ -1305,8 +1497,8 @@ type DeviceSubRequest struct { // to reference. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name DeviceClassName string `json:"deviceClassName" protobuf:"bytes,2,name=deviceClassName"` // Selectors define criteria which must be satisfied by a specific @@ -1316,8 +1508,8 @@ type DeviceSubRequest struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,3,name=selectors"` // AllocationMode and its related fields define how devices are allocated @@ -1339,7 +1531,7 @@ type DeviceSubRequest struct { // requests with unknown modes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional AllocationMode DeviceAllocationMode `json:"allocationMode,omitempty" protobuf:"bytes,4,opt,name=allocationMode"` // Count is used only when the count mode is "ExactCount". Must be greater than zero. @@ -1370,7 +1562,7 @@ type DeviceSubRequest struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // Capacity define resource requirements against each capacity. @@ -1389,6 +1581,34 @@ type DeviceSubRequest struct { // +optional // +featureGate=DRAConsumableCapacity Capacity *CapacityRequirements `json:"capacity,omitempty" protobuf:"bytes,7,opt,name=capacity"` + + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + // + // +optional + // +listType=atomic + // +featureGate=DRADerivedAttributes + // +k8s:optional + // +k8s:maxItems=32 + DerivedAttributes []DeviceDerivedAttribute `json:"derivedAttributes,omitempty" protobuf:"bytes,8,rep,name=derivedAttributes"` } // CapacityRequirements defines the capacity requirements for a specific device request. @@ -1420,14 +1640,70 @@ type CapacityRequirements struct { Requests map[QualifiedName]resource.Quantity `json:"requests,omitempty" protobuf:"bytes,1,rep,name=requests,castkey=QualifiedName"` } +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttribute struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + // + // +required + // +k8s:required + // +k8s:format=k8s-resource-fully-qualified-name + Name FullyQualifiedName `json:"name" protobuf:"bytes,1,name=name"` + + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + // + // +required + // +k8s:required + Expression string `json:"expression" protobuf:"bytes,2,name=expression"` +} + const ( DeviceSelectorsMaxSize = 32 FirstAvailableDeviceRequestMaxSize = 8 DeviceTolerationsMaxLength = 16 + DeviceDerivedAttributesMaxSize = 32 ) // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceAllocationMode string // Valid [DeviceRequest.CountMode] values. @@ -1457,7 +1733,7 @@ type CELDeviceSelector struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -1490,6 +1766,15 @@ type CELDeviceSelector struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: @@ -1537,6 +1822,25 @@ type CELDeviceSelector struct { // However, this depends on how fast the machine is. const CELSelectorExpressionMaxCost = 1000000 +// DeviceClaimDerivedAttributeCELMaxCost is the maximum combined execution cost +// allowed for all derived attribute CEL expressions within a single DeviceClaim. +// +// During validation, the API server computes the estimated execution cost of each +// derived attribute expression. The sum of these costs across all requests in the +// claim must not exceed this budget. If it does, the claim is rejected. +// +// To stay within the budget, consumers should simplify their CEL expressions, +// avoid computationally expensive operations like deep nesting or iterations +// (such as `.all()` or `.exists()`), and minimize the total number of derived +// attributes in a claim. +// +// This shared budget prevents excessively complex claims from degrading the +// performance of the kube-scheduler. The limit is set to 1,000,000 instruction +// executions (roughly 0.1 seconds of evaluation time), tying the collective +// cost of all derived attributes to the maximum cost allowed for a single +// CEL selector. +const DeviceClaimDerivedAttributeCELMaxCost = 1000000 + // CELSelectorExpressionMaxLength is the maximum length of a CEL selector expression string. const CELSelectorExpressionMaxLength = 10 * 1024 @@ -1554,10 +1858,10 @@ type DeviceConstraint struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` // MatchAttribute requires that all devices in question have this @@ -1580,8 +1884,8 @@ type DeviceConstraint struct { // // +optional // +oneOf=ConstraintType - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-fully-qualified-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name MatchAttribute *FullyQualifiedName `json:"matchAttribute,omitempty" protobuf:"bytes,2,opt,name=matchAttribute"` // Potential future extension, not part of the current design: @@ -1613,6 +1917,8 @@ type DeviceConstraint struct { // +optional // +oneOf=ConstraintType // +featureGate=DRAConsumableCapacity + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-fully-qualified-name DistinctAttribute *FullyQualifiedName `json:"distinctAttribute,omitempty" protobuf:"bytes,3,opt,name=distinctAttribute"` } @@ -1627,13 +1933,13 @@ type DeviceClaimConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,1,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,2,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,2,name=deviceConfiguration"` } // DeviceConfiguration must have exactly one field set. It gets embedded @@ -1644,7 +1950,7 @@ type DeviceConfiguration struct { // // +optional // +oneOf=ConfigurationType - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Opaque *OpaqueDeviceConfiguration `json:"opaque,omitempty" protobuf:"bytes,1,opt,name=opaque"` } @@ -1661,9 +1967,9 @@ type OpaqueDeviceConfiguration struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless Driver string `json:"driver" protobuf:"bytes,1,name=driver"` // Parameters can contain arbitrary data. It is the responsibility of @@ -1689,8 +1995,8 @@ type DeviceToleration struct { // Must be a label name. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-label-key + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-label-key Key string `json:"key,omitempty" protobuf:"bytes,1,opt,name=key"` // Operator represents a key's relationship to the value. @@ -1700,7 +2006,7 @@ type DeviceToleration struct { // // +optional // +default="Equal" - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Operator DeviceTolerationOperator `json:"operator,omitempty" protobuf:"bytes,2,opt,name=operator,casttype=DeviceTolerationOperator"` // Value is the taint value the toleration matches to. @@ -1714,7 +2020,7 @@ type DeviceToleration struct { // When specified, allowed values are NoSchedule and NoExecute. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Effect DeviceTaintEffect `json:"effect,omitempty" protobuf:"bytes,4,opt,name=effect,casttype=DeviceTaintEffect"` // TolerationSeconds represents the period of time the toleration (which must be @@ -1731,7 +2037,7 @@ type DeviceToleration struct { // A toleration operator is the set of operators that can be used in a toleration. // // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type DeviceTolerationOperator string const ( @@ -1745,8 +2051,8 @@ type ResourceClaimStatus struct { // Allocation is set once the claim has been allocated successfully. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:update=NoModify + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:update=NoModify Allocation *AllocationResult `json:"allocation,omitempty" protobuf:"bytes,1,opt,name=allocation"` // ReservedFor indicates which entities are currently allowed to use @@ -1774,10 +2080,10 @@ type ResourceClaimStatus struct { // +listMapKey=uid // +patchStrategy=merge // +patchMergeKey=uid - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=uid - // +k8s:alpha(since: "1.36")=+k8s:maxItems=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=uid + // +k8s:beta(since: "1.37")=+k8s:maxItems=256 ReservedFor []ResourceClaimConsumerReference `json:"reservedFor,omitempty" protobuf:"bytes,2,opt,name=reservedFor" patchStrategy:"merge" patchMergeKey:"uid"` // DeallocationRequested is tombstoned since Kubernetes 1.32 where @@ -1790,18 +2096,18 @@ type ResourceClaimStatus struct { // information. Entries are owned by their respective drivers. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +listType=map // +listMapKey=driver // +listMapKey=device // +listMapKey=pool // +listMapKey=shareID // +featureGate=DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:listType=map - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=driver - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=device - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=pool - // +k8s:alpha(since: "1.36")=+k8s:listMapKey=shareID + // +k8s:beta(since: "1.37")=+k8s:listType=map + // +k8s:beta(since: "1.37")=+k8s:listMapKey=driver + // +k8s:beta(since: "1.37")=+k8s:listMapKey=device + // +k8s:beta(since: "1.37")=+k8s:listMapKey=pool + // +k8s:beta(since: "1.37")=+k8s:listMapKey=shareID Devices []AllocatedDeviceStatus `json:"devices,omitempty" protobuf:"bytes,4,opt,name=devices"` } @@ -1864,8 +2170,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Results []DeviceRequestAllocationResult `json:"results,omitempty" protobuf:"bytes,1,opt,name=results"` // This field is a combination of all the claim and class configuration parameters. @@ -1878,8 +2184,8 @@ type DeviceAllocationResult struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=64 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=64 Config []DeviceAllocationConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` } @@ -1908,9 +2214,9 @@ type DeviceRequestAllocationResult struct { // vendor of the driver. It should use only lower case characters. // // +required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-long-name-caseless - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-long-name-caseless + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required Driver string `json:"driver" protobuf:"bytes,2,name=driver"` // This name together with the driver name and the device name field @@ -1920,8 +2226,8 @@ type DeviceRequestAllocationResult struct { // DNS sub-domains separated by slashes. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-resource-pool-name + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format=k8s-resource-pool-name Pool string `json:"pool" protobuf:"bytes,3,name=pool"` // Device references one device instance via its name in the driver's @@ -1953,7 +2259,7 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceTaints - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional Tolerations []DeviceToleration `json:"tolerations,omitempty" protobuf:"bytes,6,opt,name=tolerations"` // BindingConditions contains a copy of the BindingConditions @@ -1965,8 +2271,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingConditions []string `json:"bindingConditions,omitempty" protobuf:"bytes,7,rep,name=bindingConditions"` // BindingFailureConditions contains a copy of the BindingFailureConditions @@ -1978,8 +2284,8 @@ type DeviceRequestAllocationResult struct { // +optional // +listType=atomic // +featureGate=DRADeviceBindingConditions,DRAResourceClaimDeviceStatus - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=4 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=4 BindingFailureConditions []string `json:"bindingFailureConditions,omitempty" protobuf:"bytes,8,rep,name=bindingFailureConditions"` // ShareID uniquely identifies an individual allocation share of the device, @@ -1989,8 +2295,8 @@ type DeviceRequestAllocationResult struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *types.UID `json:"shareID,omitempty" protobuf:"bytes,9,opt,name=shareID"` // ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. @@ -2005,6 +2311,19 @@ type DeviceRequestAllocationResult struct { // +optional // +featureGate=DRAConsumableCapacity ConsumedCapacity map[QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty" protobuf:"bytes,10,rep,name=consumedCapacity"` + + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + // + // +optional + // +listType=set + // +k8s:listType=set + // +featureGate=DRAOptionalNodeOperations + // +k8s:optional + SkipNodeOperations []SkipNodeOperation `json:"skipNodeOperations,omitempty" protobuf:"bytes,11,rep,name=skipNodeOperations,casttype=SkipNodeOperation"` } // DeviceAllocationConfiguration gets embedded in an AllocationResult. @@ -2014,7 +2333,7 @@ type DeviceAllocationConfiguration struct { // or from a claim. // // +required - // +k8s:alpha(since: "1.36")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:required Source AllocationConfigSource `json:"source" protobuf:"bytes,1,name=source"` // Requests lists the names of requests where the configuration applies. @@ -2026,17 +2345,17 @@ type DeviceAllocationConfiguration struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Requests []string `json:"requests,omitempty" protobuf:"bytes,2,opt,name=requests"` - DeviceConfiguration `json:",inline" protobuf:"bytes,3,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,3,name=deviceConfiguration"` } // +enum -// +k8s:alpha(since: "1.36")=+k8s:enum +// +k8s:beta(since: "1.37")=+k8s:enum type AllocationConfigSource string // Valid [DeviceAllocationConfiguration.Source] values. @@ -2050,7 +2369,7 @@ const ( // ResourceClaimList is a collection of claims. type ResourceClaimList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2072,11 +2391,11 @@ type ResourceClaimList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type DeviceClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:subfield(name)=+k8s:format=k8s-long-name + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:subfield(name)=+k8s:format=k8s-long-name metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines what can be allocated and how to configure it. @@ -2087,6 +2406,7 @@ type DeviceClass struct { // the time of allocation. // // Changing the spec automatically increments the metadata.generation number. + // +optional Spec DeviceClassSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2097,8 +2417,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Selectors []DeviceSelector `json:"selectors,omitempty" protobuf:"bytes,1,opt,name=selectors"` // Config defines configuration parameters that apply to each device that is claimed via this class. @@ -2109,8 +2429,8 @@ type DeviceClassSpec struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxItems=32 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxItems=32 Config []DeviceClassConfiguration `json:"config,omitempty" protobuf:"bytes,2,opt,name=config"` // SuitableNodes is tombstoned since Kubernetes 1.32 where @@ -2127,17 +2447,16 @@ type DeviceClassSpec struct { // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. // - // This is a beta field. // +optional // +featureGate=DRAExtendedResource - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-extended-resource-name + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-extended-resource-name ExtendedResourceName *string `json:"extendedResourceName,omitempty" protobuf:"bytes,4,opt,name=extendedResourceName"` } // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfiguration struct { - DeviceConfiguration `json:",inline" protobuf:"bytes,1,opt,name=deviceConfiguration"` + DeviceConfiguration `json:"" protobuf:"bytes,1,opt,name=deviceConfiguration"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -2145,7 +2464,7 @@ type DeviceClassConfiguration struct { // DeviceClassList is a collection of classes. type DeviceClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2163,7 +2482,7 @@ type DeviceClassList struct { // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimTemplate struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2173,6 +2492,7 @@ type ResourceClaimTemplate struct { // This field is immutable. A ResourceClaim will get created by the // control plane for a Pod when needed and then not get updated // anymore. + // +optional Spec ResourceClaimTemplateSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2182,11 +2502,13 @@ type ResourceClaimTemplateSpec struct { // when creating it. No other fields are allowed and will be rejected during // validation. // +optional + // +k8s:opaqueType metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec for the ResourceClaim. The entire content is copied unchanged // into the ResourceClaim that gets created from this template. The // same fields as in a ResourceClaim are also valid here. + // +optional Spec ResourceClaimSpec `json:"spec" protobuf:"bytes,2,name=spec"` } @@ -2195,7 +2517,7 @@ type ResourceClaimTemplateSpec struct { // ResourceClaimTemplateList is a collection of claim templates. type ResourceClaimTemplateList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -2257,8 +2579,8 @@ type AllocatedDeviceStatus struct { // // +optional // +featureGate=DRAConsumableCapacity - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:format=k8s-uuid + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:format=k8s-uuid ShareID *string `json:"shareID,omitempty" protobuf:"bytes,7,opt,name=shareID"` // Conditions contains the latest observation of the device's state. @@ -2270,6 +2592,9 @@ type AllocatedDeviceStatus struct { // +optional // +listType=map // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions" protobuf:"bytes,4,opt,name=conditions"` // Data contains arbitrary driver-specific data. @@ -2282,7 +2607,7 @@ type AllocatedDeviceStatus struct { // NetworkData contains network-related information specific to the device. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional NetworkData *NetworkDeviceData `json:"networkData,omitempty" protobuf:"bytes,6,opt,name=networkData"` } @@ -2297,8 +2622,8 @@ type NetworkDeviceData struct { // Must not be longer than 256 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=256 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=256 InterfaceName string `json:"interfaceName,omitempty" protobuf:"bytes,1,opt,name=interfaceName"` // IPs lists the network addresses assigned to the device's network interface. @@ -2309,10 +2634,10 @@ type NetworkDeviceData struct { // // +optional // +listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:optional // +k8s:listType=atomic - // +k8s:alpha(since: "1.36")=+k8s:unique=set - // +k8s:alpha(since: "1.36")=+k8s:maxItems=16 + // +k8s:beta(since: "1.37")=+k8s:unique=set + // +k8s:beta(since: "1.37")=+k8s:maxItems=16 IPs []string `json:"ips,omitempty" protobuf:"bytes,2,opt,name=ips"` // HardwareAddress represents the hardware address (e.g. MAC Address) of the device's network interface. @@ -2320,7 +2645,7 @@ type NetworkDeviceData struct { // Must not be longer than 128 bytes. // // +optional - // +k8s:alpha(since: "1.36")=+k8s:optional - // +k8s:alpha(since: "1.36")=+k8s:maxBytes=128 + // +k8s:beta(since: "1.37")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:maxBytes=128 HardwareAddress string `json:"hardwareAddress,omitempty" protobuf:"bytes,3,opt,name=hardwareAddress"` } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/resource/v1beta2/types_swagger_doc_generated.go index 122170ec2..3f0c9176b 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/types_swagger_doc_generated.go @@ -55,7 +55,7 @@ func (AllocationResult) SwaggerDoc() map[string]string { var map_CELDeviceSelector = map[string]string{ "": "CELDeviceSelector contains a CEL expression for selecting a device.", - "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\".\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", + "expression": "Expression is a CEL expression which evaluates a single device. It must evaluate to true when the device under consideration satisfies the desired criteria, and false when it does not. Any other result is an error and causes allocation of devices to abort.\n\nThe expression's input is an object named \"device\", which carries the following properties:\n - driver (string): the name of the driver which defines this device.\n - attributes (map[string]object): the device's attributes, grouped by prefix\n (e.g. device.attributes[\"dra.example.com\"] evaluates to an object with all\n of the attributes which were prefixed by \"dra.example.com\").\n - capacity (map[string]object): the device's capacities, grouped by prefix.\n - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device\n (v1.34+ with the DRAConsumableCapacity feature enabled).\n\nExample: Consider a device with driver=\"dra.example.com\", which exposes two attributes named \"model\" and \"ext.example.com/family\" and which exposes one capacity named \"modules\". This input to this expression would have the following fields:\n\n device.driver\n device.attributes[\"dra.example.com\"].model\n device.attributes[\"ext.example.com\"].family\n device.capacity[\"dra.example.com\"].modules\n\nThe device.driver field can be used to check for a specific driver, either as a high-level precondition (i.e. you only want to consider devices from this driver) or as part of a multi-clause expression that is meant to consider devices from different drivers.\n\nThe value type of each attribute is defined by the device definition, and users who write these expressions must consult the documentation for their specific drivers. The value type of each capacity is Quantity.\n\nIf an unknown prefix is used as a lookup in either device.attributes or device.capacity, an empty map will be returned. Any reference to an unknown field will cause an evaluation error and allocation to abort.\n\nA robust expression should check for the existence of attributes before referencing them.\n\nCommon errors: - \"no such key\": Use optional chaining (.? followed by orValue())\n or guarding the check with has() for optional fields.\n See CEL Optional Types for details:\n https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes\n\nFor more CEL expression syntax and examples, see: https://kubernetes.io/docs/reference/using-api/cel/\n\nFor ease of use, the cel.bind() function is enabled, and can be used to simplify expressions that access multiple attributes with the same domain. For example:\n\n cel.bind(dra, device.attributes[\"dra.example.com\"], dra.someBool && dra.anotherBool)\n\nWhen the DRAListTypeAttributes feature gate is enabled, the includes() helper is available and it can work for both scalar and list-type attributes. It was introduced to support smooth migration from scalar attributes to list-type attributes while keeping CEL expressions simple. For example:\n\n device.attributes[\"dra.example.com\"].models.includes(\"some-model\")\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps.", } func (CELDeviceSelector) SwaggerDoc() map[string]string { @@ -74,7 +74,7 @@ func (CapacityRequestPolicy) SwaggerDoc() map[string]string { } var map_CapacityRequestPolicyRange = map[string]string{ - "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", + "": "CapacityRequestPolicyRange defines a valid range for consumable capacity values.\n\nIf the DRAFractionalCapacityRange feature gate is enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. its value is not an integer), milli-unit arithmetic is used instead, supporting values with up to 3 decimal places (e.g. 100m = 0.1). The largest supported value then is 1000 times smaller compared to using 64-bit integers. Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value().\n\n - If the requested amount is less than Min, it is rounded up to the Min value.\n - If Step is set and the requested amount is between Min and Max but not aligned with Step,\n it will be rounded up to the next value equal to Min + (n * Step).\n - If Step is not set, the requested amount is used as-is if it falls within the range Min to Max (if set).\n - If the requested or rounded amount exceeds Max (if set), the request does not satisfy the policy,\n and the device cannot be allocated.", "min": "Min specifies the minimum capacity allowed for a consumption request.\n\nMin must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum.", "max": "Max defines the upper limit for capacity that can be requested.\n\nMax must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum.", "step": "Step defines the step size between valid capacity amounts within the range.\n\nMax (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value.", @@ -113,20 +113,20 @@ func (CounterSet) SwaggerDoc() map[string]string { } var map_Device = map[string]string{ - "": "Device represents one individual hardware instance that can be selected based on its attributes. Besides the name, exactly one field must be set.", - "name": "Name is unique identifier among all devices managed by the driver in the pool. It must be a DNS label.", - "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", - "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", - "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", - "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is set to \"True\", a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", - "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", - "nodeAllocatableResourceMappings": "NodeAllocatableResourceMappings defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", + "": "Device represents one individual hardware instance that can be selected based on its attributes. Besides the name, exactly one field must be set.", + "name": "Name is unique identifier among all devices managed by the driver in the pool. It must be a DNS label.", + "attributes": "Attributes defines the set of attributes for this device. The name of each attribute must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "capacity": "Capacity defines the set of capacities for this device. The name of each capacity must be unique in that set.\n\nThe maximum number of attributes and capacities combined is 32.", + "consumesCounters": "ConsumesCounters defines a list of references to sharedCounters and the set of counters that the device will consume from those counter sets.\n\nThere can only be a single entry per counterSet.\n\nThe maximum number of device counter consumptions per device is 2.", + "nodeName": "NodeName identifies the node where the device is available.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "nodeSelector": "NodeSelector defines the nodes where the device is available.\n\nMust use exactly one term.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "allNodes": "AllNodes indicates that all nodes have access to the device.\n\nMust only be set if Spec.PerDeviceNodeSelection is set to true. At most one of NodeName, NodeSelector and AllNodes can be set.", + "taints": "If specified, these are the driver-defined taints.\n\nThe maximum number of taints is 16. If taints are set for any device in a ResourceSlice, then the maximum number of allowed devices per ResourceSlice is 64 instead of 128.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "bindsToNode": "BindsToNode indicates if the usage of an allocation involving this device has to be limited to exactly the node that was chosen when allocating the claim. If set to true, the scheduler will set the ResourceClaim.Status.Allocation.NodeSelector to match the node where the allocation was made.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingConditions": "BindingConditions defines the conditions for proceeding with binding. All of these conditions must be set in the per-device status conditions with a value of True to proceed with binding the pod to the node while scheduling the pod.\n\nThe maximum number of binding conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "bindingFailureConditions": "BindingFailureConditions defines the conditions for binding failure. They may be set in the per-device status conditions. If any is set to \"True\", a binding failure occurred.\n\nThe maximum number of binding failure conditions is 4.\n\nThe conditions must be a valid condition type string.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", + "allowMultipleAllocations": "AllowMultipleAllocations marks whether the device is allowed to be allocated to multiple DeviceRequests.\n\nIf AllowMultipleAllocations is set to true, the device can be allocated more than once, and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not.", + "nodeAllocatableResources": "NodeAllocatableResources defines the mapping of node resources that are managed by the DRA driver exposing this device. This includes resources currently reported in v1.Node `status.allocatable` that are not extended resources (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). Examples include \"cpu\", \"memory\", \"ephemeral-storage\", and hugepages. In addition to standard requests made through the Pod `spec`, these resources can also be requested through claims and allocated by the DRA driver. For example, a CPU DRA driver might allocate exclusive CPUs or auxiliary node memory dependencies of an accelerator device. The keys of this map are the node-allocatable resource names (e.g., \"cpu\", \"memory\"). Extended resource names are not permitted as keys.", } func (Device) SwaggerDoc() map[string]string { @@ -231,7 +231,7 @@ var map_DeviceClassSpec = map[string]string{ "": "DeviceClassSpec is used in a [DeviceClass] to define what can be allocated and how to configure it.", "selectors": "Each selector must be satisfied by a device which is claimed via this class.", "config": "Config defines configuration parameters that apply to each device that is claimed via this class. Some classses may potentially be satisfied by multiple drivers, so each instance of a vendor configuration applies to exactly one driver.\n\nThey are passed to the driver, but are not considered while allocating the claim.", - "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.\n\nThis is a beta field.", + "extendedResourceName": "ExtendedResourceName is the extended resource name for the devices of this class. The devices of this class can be used to satisfy a pod's extended resource requests. It has the same format as the name of a pod's extended resource. It should be unique among all the device classes in a cluster. If two device classes have the same name, then the class created later is picked to satisfy a pod's extended resource requests. If two classes are created at the same time, then the name of the class lexicographically sorted first is picked.", } func (DeviceClassSpec) SwaggerDoc() map[string]string { @@ -259,15 +259,26 @@ func (DeviceConstraint) SwaggerDoc() map[string]string { } var map_DeviceCounterConsumption = map[string]string{ - "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", - "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", - "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "": "DeviceCounterConsumption defines a set of counters that a device will consume from a CounterSet.", + "counterSet": "CounterSet is the name of the set from which the counters defined will be consumed.", + "counters": "Counters defines the counters that will be consumed by the device.\n\nThe maximum number of counters is 32.", + "compatibilityGroups": "CompatibilityGroups is a list of opaque group names for this counter set consumption.\n\nDevices that consume counters from the same counter set may only be allocated at the same time (\"co-allocated\") if they all share at least one common group: the intersection of the CompatibilityGroups of all co-allocated devices on that counter set must be non-empty. Devices that consume from different counter sets are never compared via this field.\n\nAn unset field, an explicit nil, and an empty list are equivalent and mean \"no groups\": such a device is only co-allocatable with sibling devices on the same counter set that also have no groups, and is never co-allocatable with a device that declares one or more groups.\n\nGroup names are opaque and meaningful only within the publishing driver's pool.\n\nThe maximum number of groups is 2, and the names must be unique.", } func (DeviceCounterConsumption) SwaggerDoc() map[string]string { return map_DeviceCounterConsumption } +var map_DeviceDerivedAttribute = map[string]string{ + "": "DeviceDerivedAttribute defines a derived attribute computed via CEL.", + "name": "Name is the identifier for this derived attribute, used in constraints.\n\nIt must be a DNS subdomain followed by a slash (\"/\") followed by a C identifier (e.g. \"example.com/numaNode\" or \"derived/numaNode\").\n\nIf the chosen name matches an existing physical attribute from a driver, the derived attribute's expression will shadow the physical attribute, and its evaluated value will be used in constraints instead. When the goal is to define a derived attribute that is only used within the ResourceClaim and not meant to shadow an existing attribute, use a domain prefix that no DRA driver should be using (e.g. \"derived/myAttribute\").\n\nIt is not valid to define a derived attribute that isn't used in at least one constraint.", + "expression": "Expression is a CEL expression evaluated against each candidate device. The expression must evaluate to a primitive scalar (string, integer, boolean, or semver) or a list of these scalars ([]string, []int64, []bool, []semver) to act as a virtual grouping key. Any other return type is an error and causes CEL evaluation for the device to fail.\n\nThe expression's input is an object named \"device\", which carries the same properties as in a CELDeviceSelector.\n\nWhen pod scheduling encounters CEL runtime errors (such as looking up an attribute that isn't defined) for some devices, it will abort allocation and fail scheduling for the Pod. Surfacing evaluation errors immediately prevents silent topology matching failures that are extremely hard to detect. A robust expression should, for example, check for the existence of attributes before referencing them to avoid runtime evaluation errors.\n\nThe expression gets evaluated after a device has passed the other selector expressions for the request in which this expression is used. This allows writing expressions that are tailored towards the specific devices being requested (for example, by assuming the device is from a certain vendor and skipping those checks).\n\nThe length of the expression must be smaller or equal to 10 Ki. The cost of evaluating it is also limited based on the estimated number of logical steps; the combined cost of all derived attributes in a claim is capped by a shared CEL cost budget.", +} + +func (DeviceDerivedAttribute) SwaggerDoc() map[string]string { + return map_DeviceDerivedAttribute +} + var map_DeviceRequest = map[string]string{ "": "DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices. With FirstAvailable it is also possible to provide a prioritized list of requests.", "name": "Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.\n\nReferences using the name in the DeviceRequest will uniquely identify a request when the Exactly field is set. When the FirstAvailable field is set, a reference to the name of the DeviceRequest will match whatever subrequest is chosen by the scheduler.\n\nMust be a DNS label.", @@ -291,6 +302,7 @@ var map_DeviceRequestAllocationResult = map[string]string{ "bindingFailureConditions": "BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation.\n\nThis is a beta field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates.", "shareID": "ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device.", "consumedCapacity": "ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device’s requestPolicy if applicable (i.e., may not be less than the requested amount).\n\nThe total consumed capacity for each device must not exceed the DeviceCapacity's Value.\n\nThis field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for this allocated device when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. It is a copy of the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated.", } func (DeviceRequestAllocationResult) SwaggerDoc() map[string]string { @@ -307,14 +319,15 @@ func (DeviceSelector) SwaggerDoc() map[string]string { } var map_DeviceSubRequest = map[string]string{ - "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to ExactDeviceRequest, but doesn't expose the AdminAccess field as that one is only supported when requesting a specific device.", - "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "DeviceSubRequest describes a request for device provided in the claim.spec.devices.requests[].firstAvailable array. Each is typically a request for a single resource like a device, but can also ask for several identical devices.\n\nDeviceSubRequest is similar to ExactDeviceRequest, but doesn't expose the AdminAccess field as that one is only supported when requesting a specific device.", + "name": "Name can be used to reference this subrequest in the list of constraints or the list of configurations for the claim. References must use the format
/.\n\nMust be a DNS label.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this subrequest.\n\nA class is required. Which classes are available depends on the cluster.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this subrequest. All selectors must be satisfied for a device to be considered.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this subrequest. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This subrequest is for all of the matching devices in a pool.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other subrequests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (DeviceSubRequest) SwaggerDoc() map[string]string { @@ -398,14 +411,15 @@ func (DeviceToleration) SwaggerDoc() map[string]string { } var map_ExactDeviceRequest = map[string]string{ - "": "ExactDeviceRequest is a request for one or more identical devices.", - "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA DeviceClassName is required.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", - "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.", - "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", - "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", - "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nThis is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.", - "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", - "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "": "ExactDeviceRequest is a request for one or more identical devices.", + "deviceClassName": "DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.\n\nA DeviceClassName is required.\n\nAdministrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.", + "selectors": "Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.", + "allocationMode": "AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:\n\n- ExactCount: This request is for a specific number of devices.\n This is the default. The exact number is provided in the\n count field.\n\n- All: This request is for all of the matching devices in a pool.\n At least one device must exist on the node for the allocation to succeed.\n Allocation will fail if some devices are already allocated,\n unless adminAccess is requested.\n\nIf AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.\n\nMore modes may get added in the future. Clients must refuse to handle requests with unknown modes.", + "count": "Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.", + "adminAccess": "AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device. They ignore all ordinary claims to the device with respect to access modes and any resource allocations.\n\nThis is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.", + "tolerations": "If specified, the request's tolerations.\n\nTolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.\n\nIn addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.\n\nThe maximum number of tolerations is 16.\n\nThis is a beta field and requires enabling the DRADeviceTaints feature gate.", + "capacity": "Capacity define resource requirements against each capacity.\n\nIf this field is unset and the device supports multiple allocations, the default value will be applied to each capacity according to requestPolicy. For the capacity that has no requestPolicy, default is the full capacity value.\n\nApplies to each device allocation. If Count > 1, the request fails if there aren't enough devices that meet the requirements. If AllocationMode is set to All, the request fails if there are devices that otherwise match the request, and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request.", + "derivedAttributes": "DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.\n\nDerived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.\n\nEvery derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.\n\nThe maximum number of derived attributes is 32.\n\nThis is an alpha field and requires enabling the DRADerivedAttributes feature gate.", } func (ExactDeviceRequest) SwaggerDoc() map[string]string { @@ -423,14 +437,35 @@ func (NetworkDeviceData) SwaggerDoc() map[string]string { return map_NetworkDeviceData } -var map_NodeAllocatableResourceMapping = map[string]string{ - "": "NodeAllocatableResourceMapping defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource.", - "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. If `allocationMultiplier` is also set, it is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\", and `allocationMultiplier` should be omitted or set to \"1\".", - "allocationMultiplier": "AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim.\n\t a. A DRA driver representing each CPU core as a device would have\n {ResourceName: \"cpu\", allocationMultiplier: \"2\"} in its\n `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim,\n\t\t 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity.\n b. A GPU device that needs additional node memory per GPU allocation would\n have {ResourceName: \"memory\", allocationMultiplier: \"2Gi\"}. Each allocated\n\t\t GPU device instance of this type will account for 2Gi of memory.\n\n2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed.\n\t The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`.\n For example, if a Device's capacity \"dra.example.com/cores\" is consumed,\n and each \"core\" provides 2 \"cpu\"s, the mapping would be:\n {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", allocationMultiplier: \"2\"}.\n If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", +var map_NodeAllocatableMapping = map[string]string{ + "": "NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim.", + "capacityKey": "CapacityKey references a capacity name defined as a key in the `spec.devices[*].capacity` map. When this field is set, the value associated with this key in the `status.allocation.devices.results[*].consumedCapacity` map (for a specific claim allocation) determines the base quantity for the node allocatable resource. `capacityMultiplier` must also be set and is multiplied with the base quantity. For example, if `spec.devices[*].capacity` has an entry \"dra.example.com/memory\": \"128Gi\", and this field is set to \"dra.example.com/memory\", then for a claim allocation that consumes { \"dra.example.com/memory\": \"4Gi\" } the base quantity for the node allocatable resource mapping will be \"4Gi\". The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`.", + "capacityMultiplier": "CapacityMultiplier is used as a multiplier for the allocated capacity consumed. It is only valid if `capacityKey` is set. The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. For example, if a Device's capacity \"dra.example.com/cores\" is consumed, and each \"core\" provides 2 \"cpu\"s, the mapping would be: {ResourceName: \"cpu\", capacityKey: \"dra.example.com/cores\", capacityMultiplier: \"2\"}. If a claim consumes 8 \"dra.example.com/cores\", the CPU footprint is 8 * 2 = 16.", + "deviceMultiplier": "DeviceMultiplier is used as a multiplier for the allocated device count in the claim. The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. For example, a DRA driver representing each cache complex (CCX) as a device would have {ResourceName: \"cpu\", deviceMultiplier: \"8\"} in its `nodeAllocatableResources`. If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. It is only valid when `capacityKey` and `capacityMultiplier` are not set.", +} + +func (NodeAllocatableMapping) SwaggerDoc() map[string]string { + return map_NodeAllocatableMapping +} + +var map_NodeAllocatableOverhead = map[string]string{ + "": "NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers.", + "perPod": "PerPod is overhead applied once per pod referencing the claim on this node. This is a flat overhead incurred for every pod referencing the claim.", + "perContainer": "PerContainer is applied per container reference to the claim. This models overhead scaling linearly with the number of containers actively using the device. When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing the claim is computed as: Quantity = PerPod + (PerContainer * NumReferences) Kubelet accounts for this overhead in cgroups: - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once.", +} + +func (NodeAllocatableOverhead) SwaggerDoc() map[string]string { + return map_NodeAllocatableOverhead +} + +var map_NodeAllocatableResource = map[string]string{ + "": "NodeAllocatableResource defines the translation between the DRA device/capacity units requested to the corresponding quantity of the node allocatable resource. At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration.", + "mapping": "Mapping is used when the device directly models a node allocatable resource like standard CPU or memory (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance on the node. To prevent node cgroup isolation friction, the scheduler explicitly blocks sharing mapped device claims across multiple pods.", + "overhead": "Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted for individually for each pod referencing the claim. Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping is specified for the same resource. Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), any overhead specified for the same resource will be subtracted from the node's general allocatable capacity and not from the per-socket capacity pool in Mapping.", } -func (NodeAllocatableResourceMapping) SwaggerDoc() map[string]string { - return map_NodeAllocatableResourceMapping +func (NodeAllocatableResource) SwaggerDoc() map[string]string { + return map_NodeAllocatableResource } var map_OpaqueDeviceConfiguration = map[string]string{ @@ -528,7 +563,7 @@ func (ResourceClaimTemplateSpec) SwaggerDoc() map[string]string { var map_ResourcePool = map[string]string{ "": "ResourcePool describes the pool that ResourceSlices belong to.", - "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", + "name": "Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required. A field selector can be used to list only ResourceSlice objects belonging to a certain pool.\n\nIt must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable.", "generation": "Generation tracks the change in a pool over time. Whenever a driver changes something about one or more of the resources in a pool, it must change the generation in all ResourceSlices which are part of that pool. Consumers of ResourceSlices should only consider resources from the pool with the highest generation number. The generation may be reset by drivers, which should be fine for consumers, assuming that all ResourceSlices in a pool are updated to match or deleted.\n\nCombined with ResourceSliceCount, this mechanism enables consumers to detect pools which are comprised of multiple ResourceSlices and are in an incomplete state.", "resourceSliceCount": "ResourceSliceCount is the total number of ResourceSlices in the pool at this generation number. Must be greater than zero.\n\nConsumers can use this to check whether they have seen all ResourceSlices belonging to the same pool.", } @@ -567,6 +602,8 @@ var map_ResourceSliceSpec = map[string]string{ "devices": "Devices lists some or all of the devices in this pool.\n\nMust not have more than 128 entries. If any device uses taints or consumes counters the limit is 64.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.", "perDeviceNodeSelection": "PerDeviceNodeSelection defines whether the access from nodes to resources in the pool is set on the ResourceSlice level or on each device. If it is set to true, every device defined the ResourceSlice must specify this individually.\n\nExactly one of NodeName, NodeSelector, AllNodes, and PerDeviceNodeSelection must be set.", "sharedCounters": "SharedCounters defines a list of counter sets, each of which has a name and a list of counters available.\n\nThe names of the counter sets must be unique in the ResourcePool.\n\nOnly one of Devices and SharedCounters can be set in a ResourceSlice.\n\nThe maximum number of counter sets is 8.", + "partitionTypeAttribute": "PartitionTypeAttribute names a string device attribute (by fully qualified name, e.g. \"gpu.example.com/profile\") whose value labels each device with its partition type, such as \"Full\" or \"Half\" for a MIG-style GPU.\n\nWhen set, every partitionable device in the slice must carry the attribute and devices sharing a value must share the same ConsumesCounters cost.", + "skipNodeOperations": "SkipNodeOperations lists node-local resource operations (gRPC calls) that will be skipped for the devices in this slice when determining whether operations are necessary on the node. If all allocated devices for a driver in a claim skip an operation, that gRPC call will be skipped. Valid values are:\n\n- \"NodePrepareResources\": NodePrepareResources gRPC calls are skipped. This\n value cannot be specified unless \"NodeUnprepareResources\" is also listed\n (or \"*\" is specified).\n- \"NodeUnprepareResources\": NodeUnprepareResources gRPC calls are skipped. - \"*\": All node-local resource operations are skipped.\n\nOther values may be added in the future. The kubelet must ignore unknown values.", } func (ResourceSliceSpec) SwaggerDoc() map[string]string { diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.deepcopy.go index 820ad2af6..5e87f13ca 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.deepcopy.go @@ -302,9 +302,9 @@ func (in *Device) DeepCopyInto(out *Device) { *out = new(bool) **out = **in } - if in.NodeAllocatableResourceMappings != nil { - in, out := &in.NodeAllocatableResourceMappings, &out.NodeAllocatableResourceMappings - *out = make(map[corev1.ResourceName]NodeAllocatableResourceMapping, len(*in)) + if in.NodeAllocatableResources != nil { + in, out := &in.NodeAllocatableResources, &out.NodeAllocatableResources + *out = make(map[corev1.ResourceName]NodeAllocatableResource, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -685,6 +685,11 @@ func (in *DeviceCounterConsumption) DeepCopyInto(out *DeviceCounterConsumption) (*out)[key] = *val.DeepCopy() } } + if in.CompatibilityGroups != nil { + in, out := &in.CompatibilityGroups, &out.CompatibilityGroups + *out = make([]string, len(*in)) + copy(*out, *in) + } return } @@ -698,6 +703,22 @@ func (in *DeviceCounterConsumption) DeepCopy() *DeviceCounterConsumption { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DeviceDerivedAttribute) DeepCopyInto(out *DeviceDerivedAttribute) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeviceDerivedAttribute. +func (in *DeviceDerivedAttribute) DeepCopy() *DeviceDerivedAttribute { + if in == nil { + return nil + } + out := new(DeviceDerivedAttribute) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeviceRequest) DeepCopyInto(out *DeviceRequest) { *out = *in @@ -763,6 +784,11 @@ func (in *DeviceRequestAllocationResult) DeepCopyInto(out *DeviceRequestAllocati (*out)[key] = val.DeepCopy() } } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } @@ -819,6 +845,11 @@ func (in *DeviceSubRequest) DeepCopyInto(out *DeviceSubRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -1037,6 +1068,11 @@ func (in *ExactDeviceRequest) DeepCopyInto(out *ExactDeviceRequest) { *out = new(CapacityRequirements) (*in).DeepCopyInto(*out) } + if in.DerivedAttributes != nil { + in, out := &in.DerivedAttributes, &out.DerivedAttributes + *out = make([]DeviceDerivedAttribute, len(*in)) + copy(*out, *in) + } return } @@ -1072,27 +1108,84 @@ func (in *NetworkDeviceData) DeepCopy() *NetworkDeviceData { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NodeAllocatableResourceMapping) DeepCopyInto(out *NodeAllocatableResourceMapping) { +func (in *NodeAllocatableMapping) DeepCopyInto(out *NodeAllocatableMapping) { *out = *in if in.CapacityKey != nil { in, out := &in.CapacityKey, &out.CapacityKey *out = new(QualifiedName) **out = **in } - if in.AllocationMultiplier != nil { - in, out := &in.AllocationMultiplier, &out.AllocationMultiplier + if in.CapacityMultiplier != nil { + in, out := &in.CapacityMultiplier, &out.CapacityMultiplier + x := (*in).DeepCopy() + *out = &x + } + if in.DeviceMultiplier != nil { + in, out := &in.DeviceMultiplier, &out.DeviceMultiplier x := (*in).DeepCopy() *out = &x } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResourceMapping. -func (in *NodeAllocatableResourceMapping) DeepCopy() *NodeAllocatableResourceMapping { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableMapping. +func (in *NodeAllocatableMapping) DeepCopy() *NodeAllocatableMapping { if in == nil { return nil } - out := new(NodeAllocatableResourceMapping) + out := new(NodeAllocatableMapping) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableOverhead) DeepCopyInto(out *NodeAllocatableOverhead) { + *out = *in + if in.PerPod != nil { + in, out := &in.PerPod, &out.PerPod + x := (*in).DeepCopy() + *out = &x + } + if in.PerContainer != nil { + in, out := &in.PerContainer, &out.PerContainer + x := (*in).DeepCopy() + *out = &x + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableOverhead. +func (in *NodeAllocatableOverhead) DeepCopy() *NodeAllocatableOverhead { + if in == nil { + return nil + } + out := new(NodeAllocatableOverhead) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *NodeAllocatableResource) DeepCopyInto(out *NodeAllocatableResource) { + *out = *in + if in.Mapping != nil { + in, out := &in.Mapping, &out.Mapping + *out = new(NodeAllocatableMapping) + (*in).DeepCopyInto(*out) + } + if in.Overhead != nil { + in, out := &in.Overhead, &out.Overhead + *out = new(NodeAllocatableOverhead) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NodeAllocatableResource. +func (in *NodeAllocatableResource) DeepCopy() *NodeAllocatableResource { + if in == nil { + return nil + } + out := new(NodeAllocatableResource) in.DeepCopyInto(out) return out } @@ -1433,6 +1526,16 @@ func (in *ResourceSliceSpec) DeepCopyInto(out *ResourceSliceSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.PartitionTypeAttribute != nil { + in, out := &in.PartitionTypeAttribute, &out.PartitionTypeAttribute + *out = new(FullyQualifiedName) + **out = **in + } + if in.SkipNodeOperations != nil { + in, out := &in.SkipNodeOperations, &out.SkipNodeOperations + *out = make([]SkipNodeOperation, len(*in)) + copy(*out, *in) + } return } diff --git a/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.model_name.go index ce388ffd2..7135589ce 100644 --- a/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/resource/v1beta2/zz_generated.model_name.go @@ -131,6 +131,11 @@ func (in DeviceCounterConsumption) OpenAPIModelName() string { return "io.k8s.api.resource.v1beta2.DeviceCounterConsumption" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DeviceDerivedAttribute) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta2.DeviceDerivedAttribute" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in DeviceRequest) OpenAPIModelName() string { return "io.k8s.api.resource.v1beta2.DeviceRequest" @@ -197,8 +202,18 @@ func (in NetworkDeviceData) OpenAPIModelName() string { } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in NodeAllocatableResourceMapping) OpenAPIModelName() string { - return "io.k8s.api.resource.v1beta2.NodeAllocatableResourceMapping" +func (in NodeAllocatableMapping) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta2.NodeAllocatableMapping" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableOverhead) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta2.NodeAllocatableOverhead" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in NodeAllocatableResource) OpenAPIModelName() string { + return "io.k8s.api.resource.v1beta2.NodeAllocatableResource" } // OpenAPIModelName returns the OpenAPI model name for this type. diff --git a/constraint/vendor/k8s.io/api/scheduling/v1/generated.proto b/constraint/vendor/k8s.io/api/scheduling/v1/generated.proto index 6be7204de..20eb5907d 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/scheduling/v1/generated.proto @@ -32,7 +32,7 @@ option go_package = "k8s.io/api/scheduling/v1"; // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. message PriorityClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; diff --git a/constraint/vendor/k8s.io/api/scheduling/v1/types.go b/constraint/vendor/k8s.io/api/scheduling/v1/types.go index 655b5eb15..f1f259fee 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1/types.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1/types.go @@ -29,8 +29,8 @@ import ( // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. type PriorityClass struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -65,7 +65,7 @@ type PriorityClass struct { // PriorityClassList is a collection of priority classes. type PriorityClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional diff --git a/constraint/vendor/k8s.io/api/scheduling/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/scheduling/v1/types_swagger_doc_generated.go index f167e1970..8913d6002 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_PriorityClass = map[string]string{ "": "PriorityClass defines mapping from a priority class name to the priority integer value. The value can be any valid integer.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "value": "value represents the integer value of this priority class. This is the actual priority that pods receive when they have the name of this class in their pod spec.", "globalDefault": "globalDefault specifies whether this PriorityClass should be considered as the default priority for pods that do not have any priority class. Only one PriorityClass can be marked as `globalDefault`. However, if more than one PriorityClasses exists with their `globalDefault` field set to true, the smallest value of such global default PriorityClasses will be used as the default priority.", "description": "description is an arbitrary string that usually provides guidelines on when this priority class should be used.", diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.proto b/constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.proto deleted file mode 100644 index 73b3308e3..000000000 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/generated.proto +++ /dev/null @@ -1,550 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -// This file was autogenerated by go-to-protobuf. Do not edit it manually! - -syntax = "proto2"; - -package k8s.io.api.scheduling.v1alpha2; - -import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; - -// Package-wide variables from generator "generated". -option go_package = "k8s.io/api/scheduling/v1alpha2"; - -// BasicSchedulingPolicy indicates that standard Kubernetes -// scheduling behavior should be used. -message BasicSchedulingPolicy { -} - -// GangSchedulingPolicy defines the parameters for gang scheduling. -message GangSchedulingPolicy { - // MinCount is the minimum number of pods that must be schedulable or scheduled - // at the same time for the scheduler to admit the entire group. - // It must be a positive integer. - // - // +required - // +k8s:required - // +k8s:minimum=1 - optional int32 minCount = 1; -} - -// PodGroup represents a runtime instance of pods grouped together. -// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from -// Workload.podGroupTemplates. -// PodGroup API enablement is toggled by the GenericWorkload feature gate. -message PodGroup { - // Standard object's metadata. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - - // Spec defines the desired state of the PodGroup. - // - // +required - optional PodGroupSpec spec = 2; - - // Status represents the current observed state of the PodGroup. - // - // +optional - optional PodGroupStatus status = 3; -} - -// PodGroupList contains a list of PodGroup resources. -message PodGroupList { - // Standard list metadata. - // - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; - - // Items is the list of PodGroups. - repeated PodGroup items = 2; -} - -// PodGroupResourceClaim references exactly one ResourceClaim, either directly -// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim -// for the PodGroup. -// -// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. -// Pods that need access to the ResourceClaim define a matching reference in its -// own Spec.ResourceClaims. The Pod's claim must match all fields of the -// PodGroup's claim exactly. -message PodGroupResourceClaim { - // Name uniquely identifies this resource claim inside the PodGroup. - // This must be a DNS_LABEL. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - optional string name = 1; - - // ResourceClaimName is the name of a ResourceClaim object in the same - // namespace as this PodGroup. The ResourceClaim will be reserved for the - // PodGroup instead of its individual pods. - // - // Exactly one of ResourceClaimName and ResourceClaimTemplateName must - // be set. - // - // +optional - // +k8s:optional - // +k8s:unionMember - // +k8s:format=k8s-long-name - optional string resourceClaimName = 2; - - // ResourceClaimTemplateName is the name of a ResourceClaimTemplate - // object in the same namespace as this PodGroup. - // - // The template will be used to create a new ResourceClaim, which will - // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim - // will also be deleted. The PodGroup name and resource name, along with a - // generated component, will be used to form a unique name for the - // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. - // - // This field is immutable and no changes will be made to the - // corresponding ResourceClaim by the control plane after creating the - // ResourceClaim. - // - // Exactly one of ResourceClaimName and ResourceClaimTemplateName must - // be set. - // - // +optional - // +k8s:optional - // +k8s:unionMember - // +k8s:format=k8s-long-name - optional string resourceClaimTemplateName = 3; -} - -// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each -// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the -// generated name for the corresponding ResourceClaim. -message PodGroupResourceClaimStatus { - // Name uniquely identifies this resource claim inside the PodGroup. This - // must match the name of an entry in podgroup.spec.resourceClaims, which - // implies that the string must be a DNS_LABEL. - // - // +required - optional string name = 1; - - // ResourceClaimName is the name of the ResourceClaim that was generated for - // the PodGroup in the namespace of the PodGroup. If this is unset, then - // generating a ResourceClaim was not necessary. The - // podgroup.spec.resourceClaims entry can be ignored in this case. - // - // +optional - // +k8s:optional - // +k8s:format=k8s-long-name - optional string resourceClaimName = 2; -} - -// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. -message PodGroupSchedulingConstraints { - // Topology defines the topology constraints for the pod group. - // Currently only a single topology constraint can be specified. This may change in the future. - // - // +optional - // +k8s:optional - // +k8s:maxItems=1 - // +listType=atomic - // +k8s:listType=atomic - repeated TopologyConstraint topology = 1; -} - -// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. -// Exactly one policy must be set. -// +union -message PodGroupSchedulingPolicy { - // Basic specifies that the pods in this group should be scheduled using - // standard Kubernetes scheduling behavior. - // - // +optional - // +k8s:optional - // +k8s:unionMember - optional BasicSchedulingPolicy basic = 1; - - // Gang specifies that the pods in this group should be scheduled using - // all-or-nothing semantics. - // - // +optional - // +k8s:optional - // +k8s:unionMember - optional GangSchedulingPolicy gang = 2; -} - -// PodGroupSpec defines the desired state of a PodGroup. -message PodGroupSpec { - // PodGroupTemplateRef references an optional PodGroup template within other object - // (e.g. Workload) that was used to create the PodGroup. This field is immutable. - // - // +optional - // +k8s:optional - // +k8s:immutable - optional PodGroupTemplateReference podGroupTemplateRef = 1; - - // SchedulingPolicy defines the scheduling policy for this instance of the PodGroup. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // This field is immutable. - // - // +required - // +k8s:immutable - optional PodGroupSchedulingPolicy schedulingPolicy = 2; - - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // This field is immutable. - // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. - // - // +featureGate=TopologyAwareWorkloadScheduling - // +optional - // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable - optional PodGroupSchedulingConstraints schedulingConstraints = 3; - - // ResourceClaims defines which ResourceClaims may be shared among Pods in - // the group. Pods consume the devices allocated to a PodGroup's claim by - // defining a claim in its own Spec.ResourceClaims that matches the - // PodGroup's claim exactly. The claim must have the same name and refer to - // the same ResourceClaim or ResourceClaimTemplate. - // - // This is an alpha-level field and requires that the - // DRAWorkloadResourceClaims feature gate is enabled. - // - // This field is immutable. - // - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +k8s:immutable - // +featureGate=DRAWorkloadResourceClaims - repeated PodGroupResourceClaim resourceClaims = 4; - - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // One of Pod, PodGroup. Defaults to Pod if unset. - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - // +default="Pod" - optional string disruptionMode = 5; - - // PriorityClassName defines the priority that should be considered when scheduling this pod group. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate - // (i.e. if no priority class is specified, admission control can set this to the global default - // priority class if it exists. Otherwise, the pod group's priority will be zero). - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:format=k8s-long-name - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - optional string priorityClassName = 6; - - // Priority is the value of priority of this pod group. Various system components - // use this field to find the priority of the pod group. When Priority Admission - // Controller is enabled, it prevents users from setting this field. The admission - // controller populates this field from PriorityClassName. - // The higher the value, the higher the priority. - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:maximum=1000000000 # HighestUserDefinablePriority - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:minimum=-2147483648 - optional int32 priority = 7; -} - -// PodGroupStatus represents information about the status of a pod group. -message PodGroupStatus { - // Conditions represent the latest observations of the PodGroup's state. - // - // Known condition types: - // - "PodGroupScheduled": Indicates whether the scheduling requirement has been satisfied. - // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated - // due to disruption such as preemption. - // - // Known reasons for the PodGroupScheduled condition: - // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, - // affinity/anti-affinity rules, or insufficient capacity for the gang. - // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error - // that happened during scheduling, for example due to nodeAffinity parsing errors. - // - // Known reasons for the DisruptionTarget condition: - // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for - // higher-priority PodGroups or Pods. - // - // +optional - // +patchMergeKey=type - // +patchStrategy=merge - // +listType=map - // +listMapKey=type - repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; - - // Status of resource claims. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +featureGate=DRAWorkloadResourceClaims - repeated PodGroupResourceClaimStatus resourceClaimStatuses = 2; -} - -// PodGroupTemplate represents a template for a set of pods with a scheduling policy. -message PodGroupTemplate { - // Name is a unique identifier for the PodGroupTemplate within the Workload. - // It must be a DNS label. This field is immutable. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - optional string name = 1; - - // SchedulingPolicy defines the scheduling policy for this PodGroupTemplate. - // - // +required - optional PodGroupSchedulingPolicy schedulingPolicy = 2; - - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. - // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. - // - // +featureGate=TopologyAwareWorkloadScheduling - // +optional - // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional - optional PodGroupSchedulingConstraints schedulingConstraints = 3; - - // ResourceClaims defines which ResourceClaims may be shared among Pods in - // the group. Pods consume the devices allocated to a PodGroup's claim by - // defining a claim in its own Spec.ResourceClaims that matches the - // PodGroup's claim exactly. The claim must have the same name and refer to - // the same ResourceClaim or ResourceClaimTemplate. - // - // This is an alpha-level field and requires that the - // DRAWorkloadResourceClaims feature gate is enabled. - // - // This field is immutable. - // - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +k8s:immutable - // +featureGate=DRAWorkloadResourceClaims - repeated PodGroupResourceClaim resourceClaims = 4; - - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. - // One of Pod, PodGroup. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - optional string disruptionMode = 5; - - // PriorityClassName indicates the priority that should be considered when scheduling - // a pod group created from this template. If no priority class is specified, admission - // control can set this to the global default priority class if it exists. Otherwise, - // pod groups created from this template will have the priority set to zero. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:format=k8s-long-name - optional string priorityClassName = 6; - - // Priority is the value of priority of pod groups created from this template. Various - // system components use this field to find the priority of the pod group. When - // Priority Admission Controller is enabled, it prevents users from setting this field. - // The admission controller populates this field from PriorityClassName. - // The higher the value, the higher the priority. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:maximum=1000000000 # HighestUserDefinablePriority - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:minimum=-2147483648 - optional int32 priority = 7; -} - -// PodGroupTemplateReference references a PodGroup template defined in some object (e.g. Workload). -// Exactly one reference must be set. -// +union -message PodGroupTemplateReference { - // Workload references the PodGroupTemplate within the Workload object that was used to create - // the PodGroup. - // - // +optional - // +k8s:optional - // +k8s:unionMember - optional WorkloadPodGroupTemplateReference workload = 1; -} - -// TopologyConstraint defines a topology constraint for a PodGroup. -message TopologyConstraint { - // Key specifies the key of the node label representing the topology domain. - // All pods within the PodGroup must be colocated within the same domain instance. - // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. - // Examples: "topology.kubernetes.io/rack" - // - // +required - // +k8s:required - // +k8s:format=k8s-label-key - optional string key = 1; -} - -// TypedLocalObjectReference allows to reference typed object inside the same namespace. -message TypedLocalObjectReference { - // APIGroup is the group for the resource being referenced. - // If APIGroup is empty, the specified Kind must be in the core API group. - // For any other third-party types, setting APIGroup is required. - // It must be a DNS subdomain. - // - // +optional - // +k8s:optional - // +k8s:format=k8s-long-name - optional string apiGroup = 1; - - // Kind is the type of resource being referenced. - // It must be a path segment name. - // - // +required - // +k8s:required - // +k8s:format=k8s-path-segment-name - optional string kind = 2; - - // Name is the name of resource being referenced. - // It must be a path segment name. - // - // +required - // +k8s:required - // +k8s:format=k8s-path-segment-name - optional string name = 3; -} - -// Workload allows for expressing scheduling constraints that should be used -// when managing the lifecycle of workloads from the scheduling perspective, -// including scheduling, preemption, eviction and other phases. -// Workload API enablement is toggled by the GenericWorkload feature gate. -message Workload { - // Standard object's metadata. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - // - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - - // Spec defines the desired behavior of a Workload. - // - // +required - optional WorkloadSpec spec = 2; -} - -// WorkloadList contains a list of Workload resources. -message WorkloadList { - // Standard list metadata. - // - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; - - // Items is the list of Workloads. - repeated Workload items = 2; -} - -// WorkloadPodGroupTemplateReference references the PodGroupTemplate within the Workload object. -message WorkloadPodGroupTemplateReference { - // WorkloadName defines the name of the Workload object. - // - // +required - // +k8s:required - // +k8s:format=k8s-long-name - optional string workloadName = 1; - - // PodGroupTemplateName defines the PodGroupTemplate name within the Workload object. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - optional string podGroupTemplateName = 2; -} - -// WorkloadSpec defines the desired state of a Workload. -message WorkloadSpec { - // ControllerRef is an optional reference to the controlling object, such as a - // Deployment or Job. This field is intended for use by tools like CLIs - // to provide a link back to the original workload definition. - // This field is immutable. - // - // +optional - // +k8s:optional - // +k8s:immutable - optional TypedLocalObjectReference controllerRef = 1; - - // PodGroupTemplates is the list of templates that make up the Workload. - // The maximum number of templates is 8. This field is immutable. - // - // +required - // +listType=map - // +listMapKey=name - // +k8s:required - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=8 - // +k8s:immutable - repeated PodGroupTemplate podGroupTemplates = 2; -} - diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types.go deleted file mode 100644 index 1f84f2c43..000000000 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types.go +++ /dev/null @@ -1,601 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Workload allows for expressing scheduling constraints that should be used -// when managing the lifecycle of workloads from the scheduling perspective, -// including scheduling, preemption, eviction and other phases. -// Workload API enablement is toggled by the GenericWorkload feature gate. -type Workload struct { - metav1.TypeMeta `json:",inline"` - // 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" protobuf:"bytes,1,opt,name=metadata"` - - // Spec defines the desired behavior of a Workload. - // - // +required - Spec WorkloadSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// WorkloadList contains a list of Workload resources. -type WorkloadList struct { - metav1.TypeMeta `json:",inline"` - // Standard list metadata. - // - // +optional - metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - - // Items is the list of Workloads. - Items []Workload `json:"items" protobuf:"bytes,2,rep,name=items"` -} - -// WorkloadMaxPodGroupTemplates is the maximum number of pod group templates per Workload. -const WorkloadMaxPodGroupTemplates = 8 - -// WorkloadSpec defines the desired state of a Workload. -type WorkloadSpec struct { - // ControllerRef is an optional reference to the controlling object, such as a - // Deployment or Job. This field is intended for use by tools like CLIs - // to provide a link back to the original workload definition. - // This field is immutable. - // - // +optional - // +k8s:optional - // +k8s:immutable - ControllerRef *TypedLocalObjectReference `json:"controllerRef,omitempty" protobuf:"bytes,1,opt,name=controllerRef"` - - // PodGroupTemplates is the list of templates that make up the Workload. - // The maximum number of templates is 8. This field is immutable. - // - // +required - // +listType=map - // +listMapKey=name - // +k8s:required - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=8 - // +k8s:immutable - PodGroupTemplates []PodGroupTemplate `json:"podGroupTemplates" protobuf:"bytes,2,rep,name=podGroupTemplates"` -} - -// TypedLocalObjectReference allows to reference typed object inside the same namespace. -type TypedLocalObjectReference struct { - // APIGroup is the group for the resource being referenced. - // If APIGroup is empty, the specified Kind must be in the core API group. - // For any other third-party types, setting APIGroup is required. - // It must be a DNS subdomain. - // - // +optional - // +k8s:optional - // +k8s:format=k8s-long-name - APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,1,opt,name=apiGroup"` - // Kind is the type of resource being referenced. - // It must be a path segment name. - // - // +required - // +k8s:required - // +k8s:format=k8s-path-segment-name - Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Name is the name of resource being referenced. - // It must be a path segment name. - // - // +required - // +k8s:required - // +k8s:format=k8s-path-segment-name - Name string `json:"name" protobuf:"bytes,3,opt,name=name"` -} - -// MaxPodGroupResourceClaims is the maximum number of resource claims for a -// PodGroup or a Workload's PodGroupTemplate. -const MaxPodGroupResourceClaims = 4 - -// PodGroupTemplate represents a template for a set of pods with a scheduling policy. -type PodGroupTemplate struct { - // Name is a unique identifier for the PodGroupTemplate within the Workload. - // It must be a DNS label. This field is immutable. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - Name string `json:"name" protobuf:"bytes,1,opt,name=name"` - - // SchedulingPolicy defines the scheduling policy for this PodGroupTemplate. - // - // +required - SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` - - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. - // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. - // - // +featureGate=TopologyAwareWorkloadScheduling - // +optional - // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional - SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints" protobuf:"bytes,3,opt,name=schedulingConstraints"` - - // ResourceClaims defines which ResourceClaims may be shared among Pods in - // the group. Pods consume the devices allocated to a PodGroup's claim by - // defining a claim in its own Spec.ResourceClaims that matches the - // PodGroup's claim exactly. The claim must have the same name and refer to - // the same ResourceClaim or ResourceClaimTemplate. - // - // This is an alpha-level field and requires that the - // DRAWorkloadResourceClaims feature gate is enabled. - // - // This field is immutable. - // - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +k8s:immutable - // +featureGate=DRAWorkloadResourceClaims - ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,4,rep,name=resourceClaims"` - - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. - // One of Pod, PodGroup. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,5,opt,name=disruptionMode,casttype=DisruptionMode"` - - // PriorityClassName indicates the priority that should be considered when scheduling - // a pod group created from this template. If no priority class is specified, admission - // control can set this to the global default priority class if it exists. Otherwise, - // pod groups created from this template will have the priority set to zero. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:format=k8s-long-name - PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,6,opt,name=priorityClassName"` - - // Priority is the value of priority of pod groups created from this template. Various - // system components use this field to find the priority of the pod group. When - // Priority Admission Controller is enabled, it prevents users from setting this field. - // The admission controller populates this field from PriorityClassName. - // The higher the value, the higher the priority. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:maximum=1000000000 # HighestUserDefinablePriority - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:minimum=-2147483648 - Priority *int32 `json:"priority,omitempty" protobuf:"varint,7,opt,name=priority"` -} - -// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. -// Exactly one policy must be set. -// +union -type PodGroupSchedulingPolicy struct { - // Basic specifies that the pods in this group should be scheduled using - // standard Kubernetes scheduling behavior. - // - // +optional - // +k8s:optional - // +k8s:unionMember - Basic *BasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` - - // Gang specifies that the pods in this group should be scheduled using - // all-or-nothing semantics. - // - // +optional - // +k8s:optional - // +k8s:unionMember - Gang *GangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` -} - -// BasicSchedulingPolicy indicates that standard Kubernetes -// scheduling behavior should be used. -type BasicSchedulingPolicy struct { - // This is intentionally empty. Its presence indicates that the basic - // scheduling policy should be applied. In the future, new fields may appear, - // describing such constraints on a pod group level without "all or nothing" - // (gang) scheduling. -} - -// GangSchedulingPolicy defines the parameters for gang scheduling. -type GangSchedulingPolicy struct { - // MinCount is the minimum number of pods that must be schedulable or scheduled - // at the same time for the scheduler to admit the entire group. - // It must be a positive integer. - // - // +required - // +k8s:required - // +k8s:minimum=1 - MinCount int32 `json:"minCount" protobuf:"varint,1,opt,name=minCount"` -} - -// PodGroupResourceClaim references exactly one ResourceClaim, either directly -// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim -// for the PodGroup. -// -// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. -// Pods that need access to the ResourceClaim define a matching reference in its -// own Spec.ResourceClaims. The Pod's claim must match all fields of the -// PodGroup's claim exactly. -type PodGroupResourceClaim struct { - // Name uniquely identifies this resource claim inside the PodGroup. - // This must be a DNS_LABEL. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - Name string `json:"name" protobuf:"bytes,1,opt,name=name"` - - // ResourceClaimName is the name of a ResourceClaim object in the same - // namespace as this PodGroup. The ResourceClaim will be reserved for the - // PodGroup instead of its individual pods. - // - // Exactly one of ResourceClaimName and ResourceClaimTemplateName must - // be set. - // - // +optional - // +k8s:optional - // +k8s:unionMember - // +k8s:format=k8s-long-name - ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` - - // ResourceClaimTemplateName is the name of a ResourceClaimTemplate - // object in the same namespace as this PodGroup. - // - // The template will be used to create a new ResourceClaim, which will - // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim - // will also be deleted. The PodGroup name and resource name, along with a - // generated component, will be used to form a unique name for the - // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. - // - // This field is immutable and no changes will be made to the - // corresponding ResourceClaim by the control plane after creating the - // ResourceClaim. - // - // Exactly one of ResourceClaimName and ResourceClaimTemplateName must - // be set. - // - // +optional - // +k8s:optional - // +k8s:unionMember - // +k8s:format=k8s-long-name - ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty" protobuf:"bytes,3,opt,name=resourceClaimTemplateName"` -} - -// DisruptionMode describes the mode in which a PodGroup can be disrupted (e.g. preempted). -// +enum -// +k8s:enum -type DisruptionMode string - -const ( - // DisruptionModePod means that individual pods can be disrupted or preempted independently. - // It doesn't depend on exact set of pods currently running in this PodGroup. - DisruptionModePod DisruptionMode = "Pod" - // DisruptionModePodGroup means that the whole PodGroup needs to be disrupted - // or preempted together. - DisruptionModePodGroup DisruptionMode = "PodGroup" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:supportsSubresource="/status" - -// PodGroup represents a runtime instance of pods grouped together. -// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from -// Workload.podGroupTemplates. -// PodGroup API enablement is toggled by the GenericWorkload feature gate. -type PodGroup struct { - metav1.TypeMeta `json:",inline"` - // 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" protobuf:"bytes,1,opt,name=metadata"` - - // Spec defines the desired state of the PodGroup. - // - // +required - Spec PodGroupSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` - - // Status represents the current observed state of the PodGroup. - // - // +optional - Status PodGroupStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// PodGroupList contains a list of PodGroup resources. -type PodGroupList struct { - metav1.TypeMeta `json:",inline"` - // Standard list metadata. - // - // +optional - metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - - // Items is the list of PodGroups. - Items []PodGroup `json:"items" protobuf:"bytes,2,rep,name=items"` -} - -// PodGroupSpec defines the desired state of a PodGroup. -type PodGroupSpec struct { - // PodGroupTemplateRef references an optional PodGroup template within other object - // (e.g. Workload) that was used to create the PodGroup. This field is immutable. - // - // +optional - // +k8s:optional - // +k8s:immutable - PodGroupTemplateRef *PodGroupTemplateReference `json:"podGroupTemplateRef" protobuf:"bytes,1,opt,name=podGroupTemplateRef"` - - // SchedulingPolicy defines the scheduling policy for this instance of the PodGroup. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // This field is immutable. - // - // +required - // +k8s:immutable - SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` - - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // This field is immutable. - // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. - // - // +featureGate=TopologyAwareWorkloadScheduling - // +optional - // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional - // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable - SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,3,opt,name=schedulingConstraints"` - - // ResourceClaims defines which ResourceClaims may be shared among Pods in - // the group. Pods consume the devices allocated to a PodGroup's claim by - // defining a claim in its own Spec.ResourceClaims that matches the - // PodGroup's claim exactly. The claim must have the same name and refer to - // the same ResourceClaim or ResourceClaimTemplate. - // - // This is an alpha-level field and requires that the - // DRAWorkloadResourceClaims feature gate is enabled. - // - // This field is immutable. - // - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +k8s:immutable - // +featureGate=DRAWorkloadResourceClaims - ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,4,rep,name=resourceClaims"` - - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // One of Pod, PodGroup. Defaults to Pod if unset. - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - // +default="Pod" - DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,5,opt,name=disruptionMode,casttype=DisruptionMode"` - - // PriorityClassName defines the priority that should be considered when scheduling this pod group. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate - // (i.e. if no priority class is specified, admission control can set this to the global default - // priority class if it exists. Otherwise, the pod group's priority will be zero). - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:format=k8s-long-name - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,6,opt,name=priorityClassName"` - - // Priority is the value of priority of this pod group. Various system components - // use this field to find the priority of the pod group. When Priority Admission - // Controller is enabled, it prevents users from setting this field. The admission - // controller populates this field from PriorityClassName. - // The higher the value, the higher the priority. - // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - // - // +featureGate=WorkloadAwarePreemption - // +optional - // +k8s:ifDisabled("WorkloadAwarePreemption")=+k8s:forbidden - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:optional - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:immutable - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:maximum=1000000000 # HighestUserDefinablePriority - // +k8s:ifEnabled("WorkloadAwarePreemption")=+k8s:minimum=-2147483648 - Priority *int32 `json:"priority,omitempty" protobuf:"varint,7,opt,name=priority"` -} - -// PodGroupStatus represents information about the status of a pod group. -type PodGroupStatus struct { - // Conditions represent the latest observations of the PodGroup's state. - // - // Known condition types: - // - "PodGroupScheduled": Indicates whether the scheduling requirement has been satisfied. - // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated - // due to disruption such as preemption. - // - // Known reasons for the PodGroupScheduled condition: - // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, - // affinity/anti-affinity rules, or insufficient capacity for the gang. - // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error - // that happened during scheduling, for example due to nodeAffinity parsing errors. - // - // Known reasons for the DisruptionTarget condition: - // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for - // higher-priority PodGroups or Pods. - // - // +optional - // +patchMergeKey=type - // +patchStrategy=merge - // +listType=map - // +listMapKey=type - Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` - - // Status of resource claims. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - // +listType=map - // +listMapKey=name - // +k8s:optional - // +k8s:listType=map - // +k8s:listMapKey=name - // +k8s:maxItems=4 - // +featureGate=DRAWorkloadResourceClaims - ResourceClaimStatuses []PodGroupResourceClaimStatus `json:"resourceClaimStatuses,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,2,rep,name=resourceClaimStatuses"` -} - -// Well-known condition types for PodGroups. -const ( - // PodGroupScheduled represents status of the scheduling process for this PodGroup. - PodGroupScheduled string = "PodGroupScheduled" - // DisruptionTarget indicates the PodGroup is about to be terminated due to disruption - // such as preemption. - DisruptionTarget string = "DisruptionTarget" -) - -// Well-known condition reasons for PodGroups. -const ( - // Unschedulable reason in the PodGroupScheduled condition indicates that the PodGroup cannot be scheduled - // due to resource constraints, affinity/anti-affinity rules, or insufficient capacity for the PodGroup. - PodGroupReasonUnschedulable string = "Unschedulable" - // SchedulerError reason in the PodGroupScheduled condition means that some internal error happens - // during scheduling, for example due to nodeAffinity parsing errors. - PodGroupReasonSchedulerError string = "SchedulerError" - // PreemptionByScheduler reason in the DisruptionTarget condition indicates the PodGroup was preempted - // to make room for higher-priority PodGroups or Pods. - PodGroupReasonPreemptionByScheduler string = "PreemptionByScheduler" -) - -// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each -// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the -// generated name for the corresponding ResourceClaim. -type PodGroupResourceClaimStatus struct { - // Name uniquely identifies this resource claim inside the PodGroup. This - // must match the name of an entry in podgroup.spec.resourceClaims, which - // implies that the string must be a DNS_LABEL. - // - // +required - Name string `json:"name" protobuf:"bytes,1,name=name"` - - // ResourceClaimName is the name of the ResourceClaim that was generated for - // the PodGroup in the namespace of the PodGroup. If this is unset, then - // generating a ResourceClaim was not necessary. The - // podgroup.spec.resourceClaims entry can be ignored in this case. - // - // +optional - // +k8s:optional - // +k8s:format=k8s-long-name - ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` -} - -// PodGroupTemplateReference references a PodGroup template defined in some object (e.g. Workload). -// Exactly one reference must be set. -// +union -type PodGroupTemplateReference struct { - // Workload references the PodGroupTemplate within the Workload object that was used to create - // the PodGroup. - // - // +optional - // +k8s:optional - // +k8s:unionMember - Workload *WorkloadPodGroupTemplateReference `json:"workload" protobuf:"bytes,1,opt,name=workload"` -} - -// WorkloadPodGroupTemplateReference references the PodGroupTemplate within the Workload object. -type WorkloadPodGroupTemplateReference struct { - // WorkloadName defines the name of the Workload object. - // - // +required - // +k8s:required - // +k8s:format=k8s-long-name - WorkloadName string `json:"workloadName" protobuf:"bytes,1,opt,name=workloadName"` - - // PodGroupTemplateName defines the PodGroupTemplate name within the Workload object. - // - // +required - // +k8s:required - // +k8s:format=k8s-short-name - PodGroupTemplateName string `json:"podGroupTemplateName" protobuf:"bytes,2,opt,name=podGroupTemplateName"` -} - -// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. -type PodGroupSchedulingConstraints struct { - // Topology defines the topology constraints for the pod group. - // Currently only a single topology constraint can be specified. This may change in the future. - // - // +optional - // +k8s:optional - // +k8s:maxItems=1 - // +listType=atomic - // +k8s:listType=atomic - Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` -} - -// TopologyConstraint defines a topology constraint for a PodGroup. -type TopologyConstraint struct { - // Key specifies the key of the node label representing the topology domain. - // All pods within the PodGroup must be colocated within the same domain instance. - // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. - // Examples: "topology.kubernetes.io/rack" - // - // +required - // +k8s:required - // +k8s:format=k8s-label-key - Key string `json:"key" protobuf:"bytes,1,opt,name=key"` -} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types_swagger_doc_generated.go deleted file mode 100644 index 2dc06b1c6..000000000 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/types_swagger_doc_generated.go +++ /dev/null @@ -1,217 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha2 - -// This file contains a collection of methods that can be used from go-restful to -// generate Swagger API documentation for its models. Please read this PR for more -// information on the implementation: https://github.com/emicklei/go-restful/pull/215 -// -// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if -// they are on one line! For multiple line or blocks that you want to ignore use ---. -// Any context after a --- is ignored. -// -// Those methods can be generated by using hack/update-codegen.sh - -// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. -var map_BasicSchedulingPolicy = map[string]string{ - "": "BasicSchedulingPolicy indicates that standard Kubernetes scheduling behavior should be used.", -} - -func (BasicSchedulingPolicy) SwaggerDoc() map[string]string { - return map_BasicSchedulingPolicy -} - -var map_GangSchedulingPolicy = map[string]string{ - "": "GangSchedulingPolicy defines the parameters for gang scheduling.", - "minCount": "MinCount is the minimum number of pods that must be schedulable or scheduled at the same time for the scheduler to admit the entire group. It must be a positive integer.", -} - -func (GangSchedulingPolicy) SwaggerDoc() map[string]string { - return map_GangSchedulingPolicy -} - -var map_PodGroup = map[string]string{ - "": "PodGroup represents a runtime instance of pods grouped together. PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from Workload.podGroupTemplates. PodGroup API enablement is toggled by the GenericWorkload feature gate.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "spec": "Spec defines the desired state of the PodGroup.", - "status": "Status represents the current observed state of the PodGroup.", -} - -func (PodGroup) SwaggerDoc() map[string]string { - return map_PodGroup -} - -var map_PodGroupList = map[string]string{ - "": "PodGroupList contains a list of PodGroup resources.", - "metadata": "Standard list metadata.", - "items": "Items is the list of PodGroups.", -} - -func (PodGroupList) SwaggerDoc() map[string]string { - return map_PodGroupList -} - -var map_PodGroupResourceClaim = map[string]string{ - "": "PodGroupResourceClaim references exactly one ResourceClaim, either directly or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim for the PodGroup.\n\nIt adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. Pods that need access to the ResourceClaim define a matching reference in its own Spec.ResourceClaims. The Pod's claim must match all fields of the PodGroup's claim exactly.", - "name": "Name uniquely identifies this resource claim inside the PodGroup. This must be a DNS_LABEL.", - "resourceClaimName": "ResourceClaimName is the name of a ResourceClaim object in the same namespace as this PodGroup. The ResourceClaim will be reserved for the PodGroup instead of its individual pods.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", - "resourceClaimTemplateName": "ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this PodGroup.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim will also be deleted. The PodGroup name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", -} - -func (PodGroupResourceClaim) SwaggerDoc() map[string]string { - return map_PodGroupResourceClaim -} - -var map_PodGroupResourceClaimStatus = map[string]string{ - "": "PodGroupResourceClaimStatus is stored in the PodGroupStatus for each PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the generated name for the corresponding ResourceClaim.", - "name": "Name uniquely identifies this resource claim inside the PodGroup. This must match the name of an entry in podgroup.spec.resourceClaims, which implies that the string must be a DNS_LABEL.", - "resourceClaimName": "ResourceClaimName is the name of the ResourceClaim that was generated for the PodGroup in the namespace of the PodGroup. If this is unset, then generating a ResourceClaim was not necessary. The podgroup.spec.resourceClaims entry can be ignored in this case.", -} - -func (PodGroupResourceClaimStatus) SwaggerDoc() map[string]string { - return map_PodGroupResourceClaimStatus -} - -var map_PodGroupSchedulingConstraints = map[string]string{ - "": "PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup.", - "topology": "Topology defines the topology constraints for the pod group. Currently only a single topology constraint can be specified. This may change in the future.", -} - -func (PodGroupSchedulingConstraints) SwaggerDoc() map[string]string { - return map_PodGroupSchedulingConstraints -} - -var map_PodGroupSchedulingPolicy = map[string]string{ - "": "PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. Exactly one policy must be set.", - "basic": "Basic specifies that the pods in this group should be scheduled using standard Kubernetes scheduling behavior.", - "gang": "Gang specifies that the pods in this group should be scheduled using all-or-nothing semantics.", -} - -func (PodGroupSchedulingPolicy) SwaggerDoc() map[string]string { - return map_PodGroupSchedulingPolicy -} - -var map_PodGroupSpec = map[string]string{ - "": "PodGroupSpec defines the desired state of a PodGroup.", - "podGroupTemplateRef": "PodGroupTemplateRef references an optional PodGroup template within other object (e.g. Workload) that was used to create the PodGroup. This field is immutable.", - "schedulingPolicy": "SchedulingPolicy defines the scheduling policy for this instance of the PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate. This field is immutable.", - "schedulingConstraints": "SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate. This field is immutable. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled.", - "resourceClaims": "ResourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is an alpha-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", - "disruptionMode": "DisruptionMode defines the mode in which a given PodGroup can be disrupted. Controllers are expected to fill this field by copying it from a PodGroupTemplate. One of Pod, PodGroup. Defaults to Pod if unset. This field is immutable. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", - "priorityClassName": "PriorityClassName defines the priority that should be considered when scheduling this pod group. Controllers are expected to fill this field by copying it from a PodGroupTemplate. Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate (i.e. if no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, the pod group's priority will be zero). This field is immutable. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", - "priority": "Priority is the value of priority of this pod group. Various system components use this field to find the priority of the pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", -} - -func (PodGroupSpec) SwaggerDoc() map[string]string { - return map_PodGroupSpec -} - -var map_PodGroupStatus = map[string]string{ - "": "PodGroupStatus represents information about the status of a pod group.", - "conditions": "Conditions represent the latest observations of the PodGroup's state.\n\nKnown condition types: - \"PodGroupScheduled\": Indicates whether the scheduling requirement has been satisfied. - \"DisruptionTarget\": Indicates whether the PodGroup is about to be terminated\n due to disruption such as preemption.\n\nKnown reasons for the PodGroupScheduled condition: - \"Unschedulable\": The PodGroup cannot be scheduled due to resource constraints,\n affinity/anti-affinity rules, or insufficient capacity for the gang.\n- \"SchedulerError\": The PodGroup cannot be scheduled due to some internal error\n that happened during scheduling, for example due to nodeAffinity parsing errors.\n\nKnown reasons for the DisruptionTarget condition: - \"PreemptionByScheduler\": The PodGroup was preempted by the scheduler to make room for\n higher-priority PodGroups or Pods.", - "resourceClaimStatuses": "Status of resource claims.", -} - -func (PodGroupStatus) SwaggerDoc() map[string]string { - return map_PodGroupStatus -} - -var map_PodGroupTemplate = map[string]string{ - "": "PodGroupTemplate represents a template for a set of pods with a scheduling policy.", - "name": "Name is a unique identifier for the PodGroupTemplate within the Workload. It must be a DNS label. This field is immutable.", - "schedulingPolicy": "SchedulingPolicy defines the scheduling policy for this PodGroupTemplate.", - "schedulingConstraints": "SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled.", - "resourceClaims": "ResourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is an alpha-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", - "disruptionMode": "DisruptionMode defines the mode in which a given PodGroup can be disrupted. One of Pod, PodGroup. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", - "priorityClassName": "PriorityClassName indicates the priority that should be considered when scheduling a pod group created from this template. If no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, pod groups created from this template will have the priority set to zero. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", - "priority": "Priority is the value of priority of pod groups created from this template. Various system components use this field to find the priority of the pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is available only when the WorkloadAwarePreemption feature gate is enabled.", -} - -func (PodGroupTemplate) SwaggerDoc() map[string]string { - return map_PodGroupTemplate -} - -var map_PodGroupTemplateReference = map[string]string{ - "": "PodGroupTemplateReference references a PodGroup template defined in some object (e.g. Workload). Exactly one reference must be set.", - "workload": "Workload references the PodGroupTemplate within the Workload object that was used to create the PodGroup.", -} - -func (PodGroupTemplateReference) SwaggerDoc() map[string]string { - return map_PodGroupTemplateReference -} - -var map_TopologyConstraint = map[string]string{ - "": "TopologyConstraint defines a topology constraint for a PodGroup.", - "key": "Key specifies the key of the node label representing the topology domain. All pods within the PodGroup must be colocated within the same domain instance. Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. Examples: \"topology.kubernetes.io/rack\"", -} - -func (TopologyConstraint) SwaggerDoc() map[string]string { - return map_TopologyConstraint -} - -var map_TypedLocalObjectReference = map[string]string{ - "": "TypedLocalObjectReference allows to reference typed object inside the same namespace.", - "apiGroup": "APIGroup is the group for the resource being referenced. If APIGroup is empty, the specified Kind must be in the core API group. For any other third-party types, setting APIGroup is required. It must be a DNS subdomain.", - "kind": "Kind is the type of resource being referenced. It must be a path segment name.", - "name": "Name is the name of resource being referenced. It must be a path segment name.", -} - -func (TypedLocalObjectReference) SwaggerDoc() map[string]string { - return map_TypedLocalObjectReference -} - -var map_Workload = map[string]string{ - "": "Workload allows for expressing scheduling constraints that should be used when managing the lifecycle of workloads from the scheduling perspective, including scheduling, preemption, eviction and other phases. Workload API enablement is toggled by the GenericWorkload feature gate.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "spec": "Spec defines the desired behavior of a Workload.", -} - -func (Workload) SwaggerDoc() map[string]string { - return map_Workload -} - -var map_WorkloadList = map[string]string{ - "": "WorkloadList contains a list of Workload resources.", - "metadata": "Standard list metadata.", - "items": "Items is the list of Workloads.", -} - -func (WorkloadList) SwaggerDoc() map[string]string { - return map_WorkloadList -} - -var map_WorkloadPodGroupTemplateReference = map[string]string{ - "": "WorkloadPodGroupTemplateReference references the PodGroupTemplate within the Workload object.", - "workloadName": "WorkloadName defines the name of the Workload object.", - "podGroupTemplateName": "PodGroupTemplateName defines the PodGroupTemplate name within the Workload object.", -} - -func (WorkloadPodGroupTemplateReference) SwaggerDoc() map[string]string { - return map_WorkloadPodGroupTemplateReference -} - -var map_WorkloadSpec = map[string]string{ - "": "WorkloadSpec defines the desired state of a Workload.", - "controllerRef": "ControllerRef is an optional reference to the controlling object, such as a Deployment or Job. This field is intended for use by tools like CLIs to provide a link back to the original workload definition. This field is immutable.", - "podGroupTemplates": "PodGroupTemplates is the list of templates that make up the Workload. The maximum number of templates is 8. This field is immutable.", -} - -func (WorkloadSpec) SwaggerDoc() map[string]string { - return map_WorkloadSpec -} - -// AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.deepcopy.go deleted file mode 100644 index 901bb0a3a..000000000 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.deepcopy.go +++ /dev/null @@ -1,484 +0,0 @@ -//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 deepcopy-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BasicSchedulingPolicy) DeepCopyInto(out *BasicSchedulingPolicy) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicSchedulingPolicy. -func (in *BasicSchedulingPolicy) DeepCopy() *BasicSchedulingPolicy { - if in == nil { - return nil - } - out := new(BasicSchedulingPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GangSchedulingPolicy) DeepCopyInto(out *GangSchedulingPolicy) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GangSchedulingPolicy. -func (in *GangSchedulingPolicy) DeepCopy() *GangSchedulingPolicy { - if in == nil { - return nil - } - out := new(GangSchedulingPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroup) DeepCopyInto(out *PodGroup) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroup. -func (in *PodGroup) DeepCopy() *PodGroup { - if in == nil { - return nil - } - out := new(PodGroup) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PodGroup) 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 *PodGroupList) DeepCopyInto(out *PodGroupList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]PodGroup, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupList. -func (in *PodGroupList) DeepCopy() *PodGroupList { - if in == nil { - return nil - } - out := new(PodGroupList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PodGroupList) 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 *PodGroupResourceClaim) DeepCopyInto(out *PodGroupResourceClaim) { - *out = *in - if in.ResourceClaimName != nil { - in, out := &in.ResourceClaimName, &out.ResourceClaimName - *out = new(string) - **out = **in - } - if in.ResourceClaimTemplateName != nil { - in, out := &in.ResourceClaimTemplateName, &out.ResourceClaimTemplateName - *out = new(string) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaim. -func (in *PodGroupResourceClaim) DeepCopy() *PodGroupResourceClaim { - if in == nil { - return nil - } - out := new(PodGroupResourceClaim) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupResourceClaimStatus) DeepCopyInto(out *PodGroupResourceClaimStatus) { - *out = *in - if in.ResourceClaimName != nil { - in, out := &in.ResourceClaimName, &out.ResourceClaimName - *out = new(string) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaimStatus. -func (in *PodGroupResourceClaimStatus) DeepCopy() *PodGroupResourceClaimStatus { - if in == nil { - return nil - } - out := new(PodGroupResourceClaimStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupSchedulingConstraints) DeepCopyInto(out *PodGroupSchedulingConstraints) { - *out = *in - if in.Topology != nil { - in, out := &in.Topology, &out.Topology - *out = make([]TopologyConstraint, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingConstraints. -func (in *PodGroupSchedulingConstraints) DeepCopy() *PodGroupSchedulingConstraints { - if in == nil { - return nil - } - out := new(PodGroupSchedulingConstraints) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupSchedulingPolicy) DeepCopyInto(out *PodGroupSchedulingPolicy) { - *out = *in - if in.Basic != nil { - in, out := &in.Basic, &out.Basic - *out = new(BasicSchedulingPolicy) - **out = **in - } - if in.Gang != nil { - in, out := &in.Gang, &out.Gang - *out = new(GangSchedulingPolicy) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingPolicy. -func (in *PodGroupSchedulingPolicy) DeepCopy() *PodGroupSchedulingPolicy { - if in == nil { - return nil - } - out := new(PodGroupSchedulingPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupSpec) DeepCopyInto(out *PodGroupSpec) { - *out = *in - if in.PodGroupTemplateRef != nil { - in, out := &in.PodGroupTemplateRef, &out.PodGroupTemplateRef - *out = new(PodGroupTemplateReference) - (*in).DeepCopyInto(*out) - } - in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) - if in.SchedulingConstraints != nil { - in, out := &in.SchedulingConstraints, &out.SchedulingConstraints - *out = new(PodGroupSchedulingConstraints) - (*in).DeepCopyInto(*out) - } - if in.ResourceClaims != nil { - in, out := &in.ResourceClaims, &out.ResourceClaims - *out = make([]PodGroupResourceClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.DisruptionMode != nil { - in, out := &in.DisruptionMode, &out.DisruptionMode - *out = new(DisruptionMode) - **out = **in - } - if in.Priority != nil { - in, out := &in.Priority, &out.Priority - *out = new(int32) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSpec. -func (in *PodGroupSpec) DeepCopy() *PodGroupSpec { - if in == nil { - return nil - } - out := new(PodGroupSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupStatus) DeepCopyInto(out *PodGroupStatus) { - *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.ResourceClaimStatuses != nil { - in, out := &in.ResourceClaimStatuses, &out.ResourceClaimStatuses - *out = make([]PodGroupResourceClaimStatus, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupStatus. -func (in *PodGroupStatus) DeepCopy() *PodGroupStatus { - if in == nil { - return nil - } - out := new(PodGroupStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupTemplate) DeepCopyInto(out *PodGroupTemplate) { - *out = *in - in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) - if in.SchedulingConstraints != nil { - in, out := &in.SchedulingConstraints, &out.SchedulingConstraints - *out = new(PodGroupSchedulingConstraints) - (*in).DeepCopyInto(*out) - } - if in.ResourceClaims != nil { - in, out := &in.ResourceClaims, &out.ResourceClaims - *out = make([]PodGroupResourceClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.DisruptionMode != nil { - in, out := &in.DisruptionMode, &out.DisruptionMode - *out = new(DisruptionMode) - **out = **in - } - if in.Priority != nil { - in, out := &in.Priority, &out.Priority - *out = new(int32) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupTemplate. -func (in *PodGroupTemplate) DeepCopy() *PodGroupTemplate { - if in == nil { - return nil - } - out := new(PodGroupTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodGroupTemplateReference) DeepCopyInto(out *PodGroupTemplateReference) { - *out = *in - if in.Workload != nil { - in, out := &in.Workload, &out.Workload - *out = new(WorkloadPodGroupTemplateReference) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupTemplateReference. -func (in *PodGroupTemplateReference) DeepCopy() *PodGroupTemplateReference { - if in == nil { - return nil - } - out := new(PodGroupTemplateReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TopologyConstraint) DeepCopyInto(out *TopologyConstraint) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TopologyConstraint. -func (in *TopologyConstraint) DeepCopy() *TopologyConstraint { - if in == nil { - return nil - } - out := new(TopologyConstraint) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TypedLocalObjectReference) DeepCopyInto(out *TypedLocalObjectReference) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TypedLocalObjectReference. -func (in *TypedLocalObjectReference) DeepCopy() *TypedLocalObjectReference { - if in == nil { - return nil - } - out := new(TypedLocalObjectReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Workload) DeepCopyInto(out *Workload) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Workload. -func (in *Workload) DeepCopy() *Workload { - if in == nil { - return nil - } - out := new(Workload) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Workload) 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 *WorkloadList) DeepCopyInto(out *WorkloadList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Workload, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadList. -func (in *WorkloadList) DeepCopy() *WorkloadList { - if in == nil { - return nil - } - out := new(WorkloadList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *WorkloadList) 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 *WorkloadPodGroupTemplateReference) DeepCopyInto(out *WorkloadPodGroupTemplateReference) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupTemplateReference. -func (in *WorkloadPodGroupTemplateReference) DeepCopy() *WorkloadPodGroupTemplateReference { - if in == nil { - return nil - } - out := new(WorkloadPodGroupTemplateReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *WorkloadSpec) DeepCopyInto(out *WorkloadSpec) { - *out = *in - if in.ControllerRef != nil { - in, out := &in.ControllerRef, &out.ControllerRef - *out = new(TypedLocalObjectReference) - **out = **in - } - if in.PodGroupTemplates != nil { - in, out := &in.PodGroupTemplates, &out.PodGroupTemplates - *out = make([]PodGroupTemplate, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadSpec. -func (in *WorkloadSpec) DeepCopy() *WorkloadSpec { - if in == nil { - return nil - } - out := new(WorkloadSpec) - in.DeepCopyInto(out) - return out -} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.model_name.go deleted file mode 100644 index 1b7effea9..000000000 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/zz_generated.model_name.go +++ /dev/null @@ -1,112 +0,0 @@ -//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 v1alpha2 - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in BasicSchedulingPolicy) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.BasicSchedulingPolicy" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in GangSchedulingPolicy) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.GangSchedulingPolicy" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroup) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroup" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupList) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupList" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupResourceClaim) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaim" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupResourceClaimStatus) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaimStatus" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupSchedulingConstraints) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingConstraints" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupSchedulingPolicy) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingPolicy" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupSpec) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupSpec" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupStatus) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupStatus" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupTemplate) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupTemplate" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in PodGroupTemplateReference) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.PodGroupTemplateReference" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in TopologyConstraint) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.TopologyConstraint" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in TypedLocalObjectReference) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.TypedLocalObjectReference" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in Workload) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.Workload" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in WorkloadList) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.WorkloadList" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in WorkloadPodGroupTemplateReference) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.WorkloadPodGroupTemplateReference" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in WorkloadSpec) OpenAPIModelName() string { - return "io.k8s.api.scheduling.v1alpha2.WorkloadSpec" -} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/doc.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/doc.go new file mode 100644 index 000000000..d2e7419d6 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/doc.go @@ -0,0 +1,37 @@ +/* +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. +*/ + +// +k8s:deepcopy-gen=package +// +k8s:protobuf-gen=package +// +k8s:openapi-gen=true +// +k8s:openapi-model-package=io.k8s.api.scheduling.v1alpha3 + +// +groupName=scheduling.k8s.io + +// +k8s:validation-gen=* +// +k8s:validation-gen-input=k8s.io/api/scheduling/v1alpha3 +// +k8s:validation-gen-scheme-registry=nil + +// A non-registering copy of the declarative validation is generated in this +// package so out-of-tree consumers can run the same validation the +// kube-apiserver enforces without importing k8s.io/kubernetes/pkg or mutating +// a shared scheme on import. The registered copy lives in +// k8s.io/kubernetes/pkg/apis/scheduling/v1alpha3. +// The `*` selector generates validators for all types, including the +// WorkloadPodGroup* building blocks that are not reachable from a TypeMeta +// root. + +package v1alpha3 diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.pb.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.pb.go new file mode 100644 index 000000000..5c56e7bc9 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.pb.go @@ -0,0 +1,8927 @@ +/* +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 protoc-gen-gogo. DO NOT EDIT. +// source: k8s.io/api/scheduling/v1alpha3/generated.proto + +package v1alpha3 + +import ( + fmt "fmt" + + io "io" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + math_bits "math/bits" + reflect "reflect" + strings "strings" +) + +func (m *AllCompositeDisruptionMode) Reset() { *m = AllCompositeDisruptionMode{} } + +func (m *AllDisruptionMode) Reset() { *m = AllDisruptionMode{} } + +func (m *BasicSchedulingPolicy) Reset() { *m = BasicSchedulingPolicy{} } + +func (m *CompositeBasicSchedulingPolicy) Reset() { *m = CompositeBasicSchedulingPolicy{} } + +func (m *CompositeDisruptionMode) Reset() { *m = CompositeDisruptionMode{} } + +func (m *CompositeGangSchedulingPolicy) Reset() { *m = CompositeGangSchedulingPolicy{} } + +func (m *CompositePodGroup) Reset() { *m = CompositePodGroup{} } + +func (m *CompositePodGroupList) Reset() { *m = CompositePodGroupList{} } + +func (m *CompositePodGroupSchedulingConstraints) Reset() { + *m = CompositePodGroupSchedulingConstraints{} +} + +func (m *CompositePodGroupSchedulingPolicy) Reset() { *m = CompositePodGroupSchedulingPolicy{} } + +func (m *CompositePodGroupSpec) Reset() { *m = CompositePodGroupSpec{} } + +func (m *CompositePodGroupStatus) Reset() { *m = CompositePodGroupStatus{} } + +func (m *CompositePodGroupTemplate) Reset() { *m = CompositePodGroupTemplate{} } + +func (m *DisruptionMode) Reset() { *m = DisruptionMode{} } + +func (m *GangSchedulingPolicy) Reset() { *m = GangSchedulingPolicy{} } + +func (m *PodGroup) Reset() { *m = PodGroup{} } + +func (m *PodGroupList) Reset() { *m = PodGroupList{} } + +func (m *PodGroupResourceClaim) Reset() { *m = PodGroupResourceClaim{} } + +func (m *PodGroupResourceClaimStatus) Reset() { *m = PodGroupResourceClaimStatus{} } + +func (m *PodGroupSchedulingConstraints) Reset() { *m = PodGroupSchedulingConstraints{} } + +func (m *PodGroupSchedulingPolicy) Reset() { *m = PodGroupSchedulingPolicy{} } + +func (m *PodGroupSpec) Reset() { *m = PodGroupSpec{} } + +func (m *PodGroupStatus) Reset() { *m = PodGroupStatus{} } + +func (m *PodGroupTemplate) Reset() { *m = PodGroupTemplate{} } + +func (m *SingleCompositeDisruptionMode) Reset() { *m = SingleCompositeDisruptionMode{} } + +func (m *SingleDisruptionMode) Reset() { *m = SingleDisruptionMode{} } + +func (m *TopologyConstraint) Reset() { *m = TopologyConstraint{} } + +func (m *TypedLocalObjectReference) Reset() { *m = TypedLocalObjectReference{} } + +func (m *Workload) Reset() { *m = Workload{} } + +func (m *WorkloadCompositePodGroupAllDisruptionMode) Reset() { + *m = WorkloadCompositePodGroupAllDisruptionMode{} +} + +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) Reset() { + *m = WorkloadCompositePodGroupBasicSchedulingPolicy{} +} + +func (m *WorkloadCompositePodGroupDisruptionMode) Reset() { + *m = WorkloadCompositePodGroupDisruptionMode{} +} + +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) Reset() { + *m = WorkloadCompositePodGroupGangSchedulingPolicy{} +} + +func (m *WorkloadCompositePodGroupSchedulingConstraints) Reset() { + *m = WorkloadCompositePodGroupSchedulingConstraints{} +} + +func (m *WorkloadCompositePodGroupSchedulingPolicy) Reset() { + *m = WorkloadCompositePodGroupSchedulingPolicy{} +} + +func (m *WorkloadCompositePodGroupSingleDisruptionMode) Reset() { + *m = WorkloadCompositePodGroupSingleDisruptionMode{} +} + +func (m *WorkloadList) Reset() { *m = WorkloadList{} } + +func (m *WorkloadPodGroupAllDisruptionMode) Reset() { *m = WorkloadPodGroupAllDisruptionMode{} } + +func (m *WorkloadPodGroupBasicSchedulingPolicy) Reset() { *m = WorkloadPodGroupBasicSchedulingPolicy{} } + +func (m *WorkloadPodGroupDisruptionMode) Reset() { *m = WorkloadPodGroupDisruptionMode{} } + +func (m *WorkloadPodGroupGangSchedulingPolicy) Reset() { *m = WorkloadPodGroupGangSchedulingPolicy{} } + +func (m *WorkloadPodGroupResourceClaim) Reset() { *m = WorkloadPodGroupResourceClaim{} } + +func (m *WorkloadPodGroupSchedulingConstraints) Reset() { *m = WorkloadPodGroupSchedulingConstraints{} } + +func (m *WorkloadPodGroupSchedulingPolicy) Reset() { *m = WorkloadPodGroupSchedulingPolicy{} } + +func (m *WorkloadPodGroupSingleDisruptionMode) Reset() { *m = WorkloadPodGroupSingleDisruptionMode{} } + +func (m *WorkloadReference) Reset() { *m = WorkloadReference{} } + +func (m *WorkloadSpec) Reset() { *m = WorkloadSpec{} } + +func (m *AllCompositeDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AllCompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AllCompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *AllDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AllDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AllDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *BasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *BasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *CompositeBasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositeBasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeBasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *CompositeDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *CompositeGangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositeGangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeGangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i = encodeVarintGenerated(dAtA, i, uint64(m.MinGroupCount)) + i-- + dAtA[i] = 0x8 + return len(dAtA) - i, nil +} + +func (m *CompositePodGroup) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroup) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroup) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x42 + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x38 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x32 + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.WorkloadRef != nil { + { + size, err := m.WorkloadRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.ParentCompositePodGroupName != nil { + i -= len(*m.ParentCompositePodGroupName) + copy(dAtA[i:], *m.ParentCompositePodGroupName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ParentCompositePodGroupName))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *CompositePodGroupTemplate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositePodGroupTemplate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositePodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CompositePodGroupTemplates) > 0 { + for iNdEx := len(m.CompositePodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CompositePodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + } + if len(m.PodGroupTemplates) > 0 { + for iNdEx := len(m.PodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x3a + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x30 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x2a + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *DisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *GangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i = encodeVarintGenerated(dAtA, i, uint64(m.MinCount)) + i-- + dAtA[i] = 0x8 + return len(dAtA) - i, nil +} + +func (m *PodGroup) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroup) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroup) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupResourceClaim) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupResourceClaim) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResourceClaimTemplateName != nil { + i -= len(*m.ResourceClaimTemplateName) + copy(dAtA[i:], *m.ResourceClaimTemplateName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimTemplateName))) + i-- + dAtA[i] = 0x1a + } + if m.ResourceClaimName != nil { + i -= len(*m.ResourceClaimName) + copy(dAtA[i:], *m.ResourceClaimName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupResourceClaimStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupResourceClaimStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResourceClaimName != nil { + i -= len(*m.ResourceClaimName) + copy(dAtA[i:], *m.ResourceClaimName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *PodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PodGroupSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x4a + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x40 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x3a + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if len(m.ResourceClaims) > 0 { + for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.WorkloadRef != nil { + { + size, err := m.WorkloadRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.ParentCompositePodGroupName != nil { + i -= len(*m.ParentCompositePodGroupName) + copy(dAtA[i:], *m.ParentCompositePodGroupName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ParentCompositePodGroupName))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PodGroupStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ResourceClaimStatuses) > 0 { + for iNdEx := len(m.ResourceClaimStatuses) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaimStatuses[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *PodGroupTemplate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupTemplate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x42 + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x38 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x32 + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if len(m.ResourceClaims) > 0 { + for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *SingleCompositeDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SingleCompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SingleCompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *SingleDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SingleDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SingleDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *TopologyConstraint) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TopologyConstraint) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TopologyConstraint) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *TypedLocalObjectReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TypedLocalObjectReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TypedLocalObjectReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x1a + i -= len(m.Kind) + copy(dAtA[i:], m.Kind) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind))) + i-- + dAtA[i] = 0x12 + i -= len(m.APIGroup) + copy(dAtA[i:], m.APIGroup) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Workload) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Workload) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Workload) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupAllDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupAllDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupAllDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MinGroupCount != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.MinGroupCount)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *WorkloadCompositePodGroupSingleDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadCompositePodGroupSingleDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadCompositePodGroupSingleDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupAllDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupAllDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupAllDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupBasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupBasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupBasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupGangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupGangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupGangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MinCount != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.MinCount)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupResourceClaim) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupResourceClaim) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResourceClaimTemplateName != nil { + i -= len(*m.ResourceClaimTemplateName) + copy(dAtA[i:], *m.ResourceClaimTemplateName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimTemplateName))) + i-- + dAtA[i] = 0x1a + } + if m.ResourceClaimName != nil { + i -= len(*m.ResourceClaimName) + copy(dAtA[i:], *m.ResourceClaimName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *WorkloadPodGroupSingleDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadPodGroupSingleDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadPodGroupSingleDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *WorkloadReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.TemplateName) + copy(dAtA[i:], m.TemplateName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TemplateName))) + i-- + dAtA[i] = 0x12 + i -= len(m.WorkloadName) + copy(dAtA[i:], m.WorkloadName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.WorkloadName))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CompositePodGroupTemplates) > 0 { + for iNdEx := len(m.CompositePodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CompositePodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.PodGroupTemplates) > 0 { + for iNdEx := len(m.PodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.ControllerRef != nil { + { + size, err := m.ControllerRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AllCompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *AllDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *BasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *CompositeBasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *CompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CompositeGangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + n += 1 + sovGenerated(uint64(m.MinGroupCount)) + return n +} + +func (m *CompositePodGroup) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *CompositePodGroupList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CompositePodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CompositePodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CompositePodGroupSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ParentCompositePodGroupName != nil { + l = len(*m.ParentCompositePodGroupName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.WorkloadRef != nil { + l = m.WorkloadRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CompositePodGroupStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CompositePodGroupTemplate) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.PodGroupTemplates) > 0 { + for _, e := range m.PodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.CompositePodGroupTemplates) > 0 { + for _, e := range m.CompositePodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *GangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + n += 1 + sovGenerated(uint64(m.MinCount)) + return n +} + +func (m *PodGroup) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *PodGroupList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupResourceClaim) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.ResourceClaimName != nil { + l = len(*m.ResourceClaimName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.ResourceClaimTemplateName != nil { + l = len(*m.ResourceClaimTemplateName) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupResourceClaimStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.ResourceClaimName != nil { + l = len(*m.ResourceClaimName) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ParentCompositePodGroupName != nil { + l = len(*m.ParentCompositePodGroupName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.WorkloadRef != nil { + l = m.WorkloadRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.ResourceClaims) > 0 { + for _, e := range m.ResourceClaims { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.ResourceClaimStatuses) > 0 { + for _, e := range m.ResourceClaimStatuses { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupTemplate) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.ResourceClaims) > 0 { + for _, e := range m.ResourceClaims { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *SingleCompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *SingleDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *TopologyConstraint) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *TypedLocalObjectReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.APIGroup) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Kind) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *Workload) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *WorkloadCompositePodGroupAllDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadCompositePodGroupDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MinGroupCount != nil { + n += 1 + sovGenerated(uint64(*m.MinGroupCount)) + } + return n +} + +func (m *WorkloadCompositePodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *WorkloadCompositePodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *WorkloadCompositePodGroupSingleDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *WorkloadPodGroupAllDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadPodGroupBasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadPodGroupDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *WorkloadPodGroupGangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MinCount != nil { + n += 1 + sovGenerated(uint64(*m.MinCount)) + } + return n +} + +func (m *WorkloadPodGroupResourceClaim) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.ResourceClaimName != nil { + l = len(*m.ResourceClaimName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.ResourceClaimTemplateName != nil { + l = len(*m.ResourceClaimTemplateName) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *WorkloadPodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *WorkloadPodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *WorkloadPodGroupSingleDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *WorkloadReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.WorkloadName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.TemplateName) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *WorkloadSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ControllerRef != nil { + l = m.ControllerRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.PodGroupTemplates) > 0 { + for _, e := range m.PodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.CompositePodGroupTemplates) > 0 { + for _, e := range m.CompositePodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func sovGenerated(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *AllCompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AllCompositeDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *AllDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AllDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *BasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&BasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *CompositeBasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeBasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *CompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeDisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "SingleCompositeDisruptionMode", "SingleCompositeDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "AllCompositeDisruptionMode", "AllCompositeDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *CompositeGangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeGangSchedulingPolicy{`, + `MinGroupCount:` + fmt.Sprintf("%v", this.MinGroupCount) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroup) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositePodGroup{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CompositePodGroupSpec", "CompositePodGroupSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CompositePodGroupStatus", "CompositePodGroupStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]CompositePodGroup{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "CompositePodGroup", "CompositePodGroup", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&CompositePodGroupList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&CompositePodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositePodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "CompositeBasicSchedulingPolicy", "CompositeBasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "CompositeGangSchedulingPolicy", "CompositeGangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositePodGroupSpec{`, + `ParentCompositePodGroupName:` + valueToStringGenerated(this.ParentCompositePodGroupName) + `,`, + `WorkloadRef:` + strings.Replace(this.WorkloadRef.String(), "WorkloadReference", "WorkloadReference", 1) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "CompositePodGroupSchedulingPolicy", "CompositePodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "CompositePodGroupSchedulingConstraints", "CompositePodGroupSchedulingConstraints", 1) + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "CompositeDisruptionMode", "CompositeDisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + s := strings.Join([]string{`&CompositePodGroupStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupTemplate) String() string { + if this == nil { + return "nil" + } + repeatedStringForPodGroupTemplates := "[]PodGroupTemplate{" + for _, f := range this.PodGroupTemplates { + repeatedStringForPodGroupTemplates += strings.Replace(strings.Replace(f.String(), "PodGroupTemplate", "PodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForPodGroupTemplates += "}" + repeatedStringForCompositePodGroupTemplates := "[]CompositePodGroupTemplate{" + for _, f := range this.CompositePodGroupTemplates { + repeatedStringForCompositePodGroupTemplates += strings.Replace(strings.Replace(f.String(), "CompositePodGroupTemplate", "CompositePodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForCompositePodGroupTemplates += "}" + s := strings.Join([]string{`&CompositePodGroupTemplate{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "CompositePodGroupSchedulingPolicy", "CompositePodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "CompositePodGroupSchedulingConstraints", "CompositePodGroupSchedulingConstraints", 1) + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "CompositeDisruptionMode", "CompositeDisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `PodGroupTemplates:` + repeatedStringForPodGroupTemplates + `,`, + `CompositePodGroupTemplates:` + repeatedStringForCompositePodGroupTemplates + `,`, + `}`, + }, "") + return s +} +func (this *DisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "SingleDisruptionMode", "SingleDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "AllDisruptionMode", "AllDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *GangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GangSchedulingPolicy{`, + `MinCount:` + fmt.Sprintf("%v", this.MinCount) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroup) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroup{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodGroupSpec", "PodGroupSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodGroupStatus", "PodGroupStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]PodGroup{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PodGroup", "PodGroup", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&PodGroupList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupResourceClaim) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupResourceClaim{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + `ResourceClaimTemplateName:` + valueToStringGenerated(this.ResourceClaimTemplateName) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupResourceClaimStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupResourceClaimStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&PodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "BasicSchedulingPolicy", "BasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "GangSchedulingPolicy", "GangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSpec) String() string { + if this == nil { + return "nil" + } + repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" + for _, f := range this.ResourceClaims { + repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaims += "}" + s := strings.Join([]string{`&PodGroupSpec{`, + `ParentCompositePodGroupName:` + valueToStringGenerated(this.ParentCompositePodGroupName) + `,`, + `WorkloadRef:` + strings.Replace(this.WorkloadRef.String(), "WorkloadReference", "WorkloadReference", 1) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, + `ResourceClaims:` + repeatedStringForResourceClaims + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "DisruptionMode", "DisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + repeatedStringForResourceClaimStatuses := "[]PodGroupResourceClaimStatus{" + for _, f := range this.ResourceClaimStatuses { + repeatedStringForResourceClaimStatuses += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaimStatus", "PodGroupResourceClaimStatus", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaimStatuses += "}" + s := strings.Join([]string{`&PodGroupStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `ResourceClaimStatuses:` + repeatedStringForResourceClaimStatuses + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupTemplate) String() string { + if this == nil { + return "nil" + } + repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" + for _, f := range this.ResourceClaims { + repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaims += "}" + s := strings.Join([]string{`&PodGroupTemplate{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, + `ResourceClaims:` + repeatedStringForResourceClaims + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "DisruptionMode", "DisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *SingleCompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SingleCompositeDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *SingleDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SingleDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *TopologyConstraint) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TopologyConstraint{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `}`, + }, "") + return s +} +func (this *TypedLocalObjectReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TypedLocalObjectReference{`, + `APIGroup:` + fmt.Sprintf("%v", this.APIGroup) + `,`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `}`, + }, "") + return s +} +func (this *Workload) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Workload{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "WorkloadSpec", "WorkloadSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupAllDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupAllDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupBasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupBasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupDisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "WorkloadCompositePodGroupSingleDisruptionMode", "WorkloadCompositePodGroupSingleDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "WorkloadCompositePodGroupAllDisruptionMode", "WorkloadCompositePodGroupAllDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupGangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupGangSchedulingPolicy{`, + `MinGroupCount:` + valueToStringGenerated(this.MinGroupCount) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&WorkloadCompositePodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "WorkloadCompositePodGroupBasicSchedulingPolicy", "WorkloadCompositePodGroupBasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "WorkloadCompositePodGroupGangSchedulingPolicy", "WorkloadCompositePodGroupGangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadCompositePodGroupSingleDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadCompositePodGroupSingleDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *WorkloadList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]Workload{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Workload", "Workload", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&WorkloadList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupAllDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupAllDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupBasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupBasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupDisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "WorkloadPodGroupSingleDisruptionMode", "WorkloadPodGroupSingleDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "WorkloadPodGroupAllDisruptionMode", "WorkloadPodGroupAllDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupGangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupGangSchedulingPolicy{`, + `MinCount:` + valueToStringGenerated(this.MinCount) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupResourceClaim) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupResourceClaim{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + `ResourceClaimTemplateName:` + valueToStringGenerated(this.ResourceClaimTemplateName) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&WorkloadPodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "WorkloadPodGroupBasicSchedulingPolicy", "WorkloadPodGroupBasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "WorkloadPodGroupGangSchedulingPolicy", "WorkloadPodGroupGangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadPodGroupSingleDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadPodGroupSingleDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *WorkloadReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadReference{`, + `WorkloadName:` + fmt.Sprintf("%v", this.WorkloadName) + `,`, + `TemplateName:` + fmt.Sprintf("%v", this.TemplateName) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadSpec) String() string { + if this == nil { + return "nil" + } + repeatedStringForPodGroupTemplates := "[]PodGroupTemplate{" + for _, f := range this.PodGroupTemplates { + repeatedStringForPodGroupTemplates += strings.Replace(strings.Replace(f.String(), "PodGroupTemplate", "PodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForPodGroupTemplates += "}" + repeatedStringForCompositePodGroupTemplates := "[]CompositePodGroupTemplate{" + for _, f := range this.CompositePodGroupTemplates { + repeatedStringForCompositePodGroupTemplates += strings.Replace(strings.Replace(f.String(), "CompositePodGroupTemplate", "CompositePodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForCompositePodGroupTemplates += "}" + s := strings.Join([]string{`&WorkloadSpec{`, + `ControllerRef:` + strings.Replace(this.ControllerRef.String(), "TypedLocalObjectReference", "TypedLocalObjectReference", 1) + `,`, + `PodGroupTemplates:` + repeatedStringForPodGroupTemplates + `,`, + `CompositePodGroupTemplates:` + repeatedStringForCompositePodGroupTemplates + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *AllCompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllCompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllCompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AllDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeBasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeBasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeBasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &SingleCompositeDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &AllCompositeDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeGangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeGangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeGangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinGroupCount", wireType) + } + m.MinGroupCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinGroupCount |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroup) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroup: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroup: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, CompositePodGroup{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &CompositeBasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &CompositeGangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ParentCompositePodGroupName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ParentCompositePodGroupName = &s + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WorkloadRef", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.WorkloadRef == nil { + m.WorkloadRef = &WorkloadReference{} + } + if err := m.WorkloadRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &CompositePodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &CompositeDisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupTemplate) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupTemplate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &CompositePodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &CompositeDisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PodGroupTemplates = append(m.PodGroupTemplates, PodGroupTemplate{}) + if err := m.PodGroupTemplates[len(m.PodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompositePodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompositePodGroupTemplates = append(m.CompositePodGroupTemplates, CompositePodGroupTemplate{}) + if err := m.CompositePodGroupTemplates[len(m.CompositePodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &SingleDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &AllDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinCount", wireType) + } + m.MinCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinCount |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroup) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroup: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroup: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, PodGroup{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupResourceClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupResourceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimName = &s + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimTemplateName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimTemplateName = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupResourceClaimStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupResourceClaimStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimName = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &BasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &GangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ParentCompositePodGroupName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ParentCompositePodGroupName = &s + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WorkloadRef", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.WorkloadRef == nil { + m.WorkloadRef = &WorkloadReference{} + } + if err := m.WorkloadRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &PodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) + if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &DisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimStatuses", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaimStatuses = append(m.ResourceClaimStatuses, PodGroupResourceClaimStatus{}) + if err := m.ResourceClaimStatuses[len(m.ResourceClaimStatuses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupTemplate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &PodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) + if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &DisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SingleCompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SingleCompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SingleCompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SingleDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SingleDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SingleDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TopologyConstraint: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TopologyConstraint: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TypedLocalObjectReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TypedLocalObjectReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field APIGroup", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.APIGroup = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Kind = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Workload) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Workload: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Workload: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupAllDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupAllDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupAllDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupBasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupBasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupBasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &WorkloadCompositePodGroupSingleDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &WorkloadCompositePodGroupAllDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupGangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupGangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupGangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinGroupCount", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.MinGroupCount = &v + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &WorkloadCompositePodGroupBasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &WorkloadCompositePodGroupGangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadCompositePodGroupSingleDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSingleDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadCompositePodGroupSingleDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, Workload{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupAllDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupAllDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupAllDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupBasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupBasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupBasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &WorkloadPodGroupSingleDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &WorkloadPodGroupAllDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupGangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupGangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupGangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinCount", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.MinCount = &v + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupResourceClaim) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupResourceClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupResourceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimName = &s + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimTemplateName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimTemplateName = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &WorkloadPodGroupBasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &WorkloadPodGroupGangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadPodGroupSingleDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadPodGroupSingleDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadPodGroupSingleDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WorkloadName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.WorkloadName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TemplateName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TemplateName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ControllerRef", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ControllerRef == nil { + m.ControllerRef = &TypedLocalObjectReference{} + } + if err := m.ControllerRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PodGroupTemplates = append(m.PodGroupTemplates, PodGroupTemplate{}) + if err := m.PodGroupTemplates[len(m.PodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompositePodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompositePodGroupTemplates = append(m.CompositePodGroupTemplates, CompositePodGroupTemplate{}) + if err := m.CompositePodGroupTemplates[len(m.CompositePodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenerated(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenerated + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenerated + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenerated + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") +) diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.proto b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.proto new file mode 100644 index 000000000..662b27b43 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/generated.proto @@ -0,0 +1,1353 @@ +/* +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. +*/ + + +// This file was autogenerated by go-to-protobuf. Do not edit it manually! + +syntax = "proto2"; + +package k8s.io.api.scheduling.v1alpha3; + +import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; + +// Package-wide variables from generator "generated". +option go_package = "k8s.io/api/scheduling/v1alpha3"; + +// AllCompositeDisruptionMode means that children of a CompositePodGroup can only be +// disrupted or preempted together. +message AllCompositeDisruptionMode { +} + +// AllDisruptionMode specifies that children can only be disrupted together. +message AllDisruptionMode { +} + +// BasicSchedulingPolicy indicates that standard Kubernetes +// scheduling behavior should be used. +message BasicSchedulingPolicy { +} + +// CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled independently. +message CompositeBasicSchedulingPolicy { +} + +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +// +// +union +message CompositeDisruptionMode { + // single specifies that children groups can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional SingleCompositeDisruptionMode single = 1; + + // all specifies that all children groups can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional AllCompositeDisruptionMode all = 2; +} + +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +message CompositeGangSchedulingPolicy { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + // + // +required + // +k8s:required + // +k8s:minimum=1 + optional int32 minGroupCount = 1; +} + +// CompositePodGroup represents a runtime instance of pod groups grouped together. +// CompositePodGroups are created by workload controllers (LWS, JobSet, etc...) from +// Workload.compositePodGroupTemplates. +// CompositePodGroup API enablement is toggled by the CompositePodGroup feature gate. +message CompositePodGroup { + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the desired state of the CompositePodGroup. + // + // +required + optional CompositePodGroupSpec spec = 2; + + // status represents the current observed state of the CompositePodGroup. + // + // +optional + optional CompositePodGroupStatus status = 3; +} + +// CompositePodGroupList contains a list of CompositePodGroup resources. +message CompositePodGroupList { + // Standard list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of CompositePodGroups. + repeated CompositePodGroup items = 2; +} + +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +message CompositePodGroupSchedulingConstraints { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +// +// +union +message CompositePodGroupSchedulingPolicy { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:unionMember + optional CompositeBasicSchedulingPolicy basic = 1; + + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional CompositeGangSchedulingPolicy gang = 2; +} + +// CompositePodGroupSpec defines the desired state of CompositePodGroup. +message CompositePodGroupSpec { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this composite pod group. It must be a DNS name. + // If it's nil, then this composite pod group is a root of a workload's hierarchy. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + optional string parentCompositePodGroupName = 1; + + // workloadRef references an optional CompositePodGroup template within the + // Workload object that was used to create the CompositePodGroup. + // This field is required. + // This field is immutable. + // + // +required + // +k8s:required + // +k8s:immutable + optional WorkloadReference workloadRef = 2; + + // schedulingPolicy defines the scheduling policy for this instance of the CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + // + // +required + // +k8s:immutable + optional CompositePodGroupSchedulingPolicy schedulingPolicy = 3; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositePodGroupSchedulingConstraints schedulingConstraints = 4; + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositeDisruptionMode disruptionMode = 5; + + // priorityClassName defines the priority that should be considered when scheduling this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // If left unspecified, it is validated and resolved similarly to the PriorityClassName field in Pods + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the composite pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + optional string priorityClassName = 6; + + // priority is the value of priority of this composite pod group. Various system components + // use this field to find the priority of the composite pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + optional int32 priority = 7; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 8; +} + +// CompositePodGroupStatus represents information about the status of a composite pod group. +message CompositePodGroupStatus { + // conditions represent the latest observations of the CompositePodGroup's state. + // + // Known condition types: + // - "CompositePodGroupInitiallyScheduled": Indicates whether the overall scheduling requirement + // for the subtree under this CompositePodGroup has been satisfied. Once this condition + // transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently deleted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the CompositePodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the CompositePodGroupInitiallyScheduled condition: + // - "Unschedulable": The CompositePodGroup's subtree could not be placed due to resource constraints, + // affinity/anti-affinity, or topological constraints. + // - "SchedulerError": The CompositePodGroup cannot be scheduled due to some internal error + // that occurred during scheduling. + // - "Invalid": Set to True when kube-scheduler detects an invalid group layout during + // runtime validation. The `message` field details the specific layout violation (such as + // a detected cycle, exceeding the maximum depth of 4, or referencing multiple distinct Workloads). + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The CompositePodGroup was targeted by the scheduler's preemption loop + // to free up capacity for higher-priority preemptors. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; +} + +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +message CompositePodGroupTemplate { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // schedulingPolicy defines the scheduling policy for this template. + // + // +required + optional CompositePodGroupSchedulingPolicy schedulingPolicy = 2; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositePodGroupSchedulingConstraints schedulingConstraints = 3; + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositeDisruptionMode disruptionMode = 4; + + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + optional string priorityClassName = 5; + + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + optional int32 priority = 6; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 7; + + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated PodGroupTemplate podGroupTemplates = 8; + + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated CompositePodGroupTemplate compositePodGroupTemplates = 9; +} + +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +// +// +union +message DisruptionMode { + // single specifies that children can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional SingleDisruptionMode single = 1; + + // all specifies that all children can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional AllDisruptionMode all = 2; +} + +// GangSchedulingPolicy defines the parameters for gang scheduling. +message GangSchedulingPolicy { + // minCount is the minimum number of pods that must be schedulable or scheduled + // at the same time for the scheduler to admit the entire group. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. + // + // +required + // +k8s:required + // +k8s:minimum=1 + optional int32 minCount = 1; +} + +// PodGroup represents a runtime instance of pods grouped together. +// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from +// Workload.podGroupTemplates. +// PodGroup API enablement is toggled by the GenericWorkload feature gate. +message PodGroup { + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the desired state of the PodGroup. + // + // +required + optional PodGroupSpec spec = 2; + + // status represents the current observed state of the PodGroup. + // + // +optional + optional PodGroupStatus status = 3; +} + +// PodGroupList contains a list of PodGroup resources. +message PodGroupList { + // Standard list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of PodGroups. + repeated PodGroup items = 2; +} + +// PodGroupResourceClaim references exactly one ResourceClaim, either directly +// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim +// for the PodGroup. +// +// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. +// Pods that need access to the ResourceClaim define a matching reference in its +// own Spec.ResourceClaims. The Pod's claim must match all fields of the +// PodGroup's claim exactly. +message PodGroupResourceClaim { + // name uniquely identifies this resource claim inside the PodGroup. + // This must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace as this PodGroup. The ResourceClaim will be reserved for the + // PodGroup instead of its individual pods. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimName = 2; + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace as this PodGroup. + // + // The template will be used to create a new ResourceClaim, which will + // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim + // will also be deleted. The PodGroup name and resource name, along with a + // generated component, will be used to form a unique name for the + // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. + // + // This field is immutable and no changes will be made to the + // corresponding ResourceClaim by the control plane after creating the + // ResourceClaim. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimTemplateName = 3; +} + +// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each +// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the +// generated name for the corresponding ResourceClaim. +message PodGroupResourceClaimStatus { + // name uniquely identifies this resource claim inside the PodGroup. This + // must match the name of an entry in podgroup.spec.resourceClaims, which + // implies that the string must be a DNS_LABEL. + // + // +required + optional string name = 1; + + // resourceClaimName is the name of the ResourceClaim that was generated for + // the PodGroup in the namespace of the PodGroup. If this is unset, then + // generating a ResourceClaim was not necessary. The + // podgroup.spec.resourceClaims entry can be ignored in this case. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + optional string resourceClaimName = 2; +} + +// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. +message PodGroupSchedulingConstraints { + // topology defines the topology constraints for the pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. +// +// +union +message PodGroupSchedulingPolicy { + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:immutable + optional BasicSchedulingPolicy basic = 1; + + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional GangSchedulingPolicy gang = 2; +} + +// PodGroupSpec defines the desired state of a PodGroup. +message PodGroupSpec { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + // + // +featureGate=CompositePodGroup + // +optional + // +k8s:ifDisabled(CompositePodGroup)=+k8s:forbidden + // +k8s:ifEnabled(CompositePodGroup)=+k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("workloadRef") + optional string parentCompositePodGroupName = 1; + + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional WorkloadReference workloadRef = 2; + + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // + // +required + optional PodGroupSchedulingPolicy schedulingPolicy = 3; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // This field is immutable. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable + optional PodGroupSchedulingConstraints schedulingConstraints = 4; + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + // +featureGate=DRAWorkloadResourceClaims + repeated PodGroupResourceClaim resourceClaims = 5; + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + optional DisruptionMode disruptionMode = 6; + + // priorityClassName defines the priority that should be considered when scheduling this pod group. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + optional string priorityClassName = 7; + + // priority is the value of priority of this pod group. Various system components + // use this field to find the priority of the pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + optional int32 priority = 8; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 9; +} + +// PodGroupStatus represents information about the status of a pod group. +message PodGroupStatus { + // conditions represent the latest observations of the PodGroup's state. + // + // Known condition types: + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the PodGroupInitiallyScheduled condition: + // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, + // affinity/anti-affinity rules, or insufficient capacity for the gang. + // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error + // that happened during scheduling, for example due to nodeAffinity parsing errors. + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for + // higher-priority PodGroups or Pods. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // resourceClaimStatuses is status of resource claims. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + repeated PodGroupResourceClaimStatus resourceClaimStatuses = 2; +} + +// PodGroupTemplate represents a template for a set of pods with a scheduling policy. +message PodGroupTemplate { + // name is a unique identifier for the PodGroupTemplate within the Workload. + // It must be a DNS label. This field is immutable. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. + // + // +required + optional PodGroupSchedulingPolicy schedulingPolicy = 2; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:immutable + optional PodGroupSchedulingConstraints schedulingConstraints = 3; + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + // +k8s:immutable + repeated PodGroupResourceClaim resourceClaims = 4; + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional DisruptionMode disruptionMode = 5; + + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + optional string priorityClassName = 6; + + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + optional int32 priority = 7; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 8; +} + +// SingleCompositeDisruptionMode means that individual children of a CompositePodGroup +// can be disrupted or preempted independently. +message SingleCompositeDisruptionMode { +} + +// SingleDisruptionMode specifies that children can be disrupted independently. +message SingleDisruptionMode { +} + +// TopologyConstraint defines a topology constraint for a PodGroup. +message TopologyConstraint { + // key specifies the key of the node label representing the topology domain. + // All pods within the PodGroup must be colocated within the same domain instance. + // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. + // Examples: "topology.kubernetes.io/rack" + // + // +required + // +k8s:required + // +k8s:format=k8s-label-key + optional string key = 1; +} + +// TypedLocalObjectReference allows to reference typed object inside the same namespace. +message TypedLocalObjectReference { + // apiGroup is the group for the resource being referenced. + // If APIGroup is empty, the specified Kind must be in the core API group. + // For any other third-party types, setting APIGroup is required. + // It must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + optional string apiGroup = 1; + + // kind is the type of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + optional string kind = 2; + + // name is the name of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + optional string name = 3; +} + +// Workload allows for expressing scheduling constraints that should be used +// when managing the lifecycle of workloads from the scheduling perspective, +// including scheduling, preemption, eviction and other phases. +// Workload API enablement is toggled by the GenericWorkload feature gate. +message Workload { + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the desired behavior of a Workload. + // + // +required + optional WorkloadSpec spec = 2; +} + +// WorkloadCompositePodGroupAllDisruptionMode indicates that all child groups +// must be disrupted together. +message WorkloadCompositePodGroupAllDisruptionMode { +} + +// WorkloadCompositePodGroupBasicSchedulingPolicy indicates that the child groups +// of a composite group should be scheduled independently. +message WorkloadCompositePodGroupBasicSchedulingPolicy { +} + +// WorkloadCompositePodGroupDisruptionMode defines how the child groups of a +// composite group can be disrupted. Exactly one mode must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupDisruptionMode. It's recommended +// to freeze the field after creation (+k8s:immutable), since the selected mode +// is immutable in the compiled Workload. For example, +// +// type JobSetSchedulingConfiguration struct { +// // DisruptionMode defines the mode in which this JobSet's child groups +// // can be disrupted. +// // One of Single, All. +// // This field is immutable after creation: it may not be added or removed, +// // and the selected mode may not be changed. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// DisruptionMode *schedulingv1alpha3.WorkloadCompositePodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,N,opt,name=disruptionMode"` +// +// // other scheduling fields +// } +// +// +union +message WorkloadCompositePodGroupDisruptionMode { + // single specifies that child groups can be disrupted independently from + // each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadCompositePodGroupSingleDisruptionMode single = 1; + + // all specifies that all child groups must be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadCompositePodGroupAllDisruptionMode all = 2; +} + +// WorkloadCompositePodGroupGangSchedulingPolicy defines the parameters for gang +// scheduling of a composite group's child groups. +message WorkloadCompositePodGroupGangSchedulingPolicy { + // minGroupCount is the minimum number of child groups that must be + // schedulable at the same time for the scheduler to admit the entire + // composite group. + // This field is optional. If it is not specified, the controller + // should inject a context-specific sane default (e.g., the number of + // child groups). + // If set, it must be a positive integer. + // + // +optional + // +k8s:optional + // +k8s:minimum=1 + optional int32 minGroupCount = 1; +} + +// WorkloadCompositePodGroupSchedulingConstraints defines composite-level +// scheduling constraints, such as topology, for a CompositePodGroup (a group of +// groups) managed by a workload controller. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupSchedulingConstraints. It's +// recommended to freeze the field after creation (+k8s:immutable), since +// constraints are immutable in the compiled Workload. For example, +// +// type JobSetSchedulingConfiguration struct { +// // SchedulingConstraints defines scheduling constraints (e.g. topology) +// // for this JobSet. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingConstraints *schedulingv1alpha3.WorkloadCompositePodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,N,opt,name=schedulingConstraints"` +// +// // other scheduling fields +// } +message WorkloadCompositePodGroupSchedulingConstraints { + // topology specifies desired topological placements for all child groups + // within the composite group. + // If unset, no topology placement is requested. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// WorkloadCompositePodGroupSchedulingPolicy defines the scheduling policy for a +// CompositePodGroup (a group of groups) managed by a workload controller. +// Exactly one policy must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupSchedulingPolicy. The composite +// scheduling policy is immutable, so it's recommended to freeze the whole +// field after creation (+k8s:immutable). For example, +// +// type JobSetSchedulingConfiguration struct { +// // SchedulingPolicy defines the scheduling policy for this JobSet. +// // Exactly one of Basic or Gang must be set. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingPolicy *schedulingv1alpha3.WorkloadCompositePodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,N,opt,name=schedulingPolicy"` +// +// // other scheduling fields +// } +// +// +union +message WorkloadCompositePodGroupSchedulingPolicy { + // basic specifies that the child groups of this composite group should be + // scheduled independently. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadCompositePodGroupBasicSchedulingPolicy basic = 1; + + // gang specifies that the child groups of this composite group should be + // scheduled using all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadCompositePodGroupGangSchedulingPolicy gang = 2; +} + +// WorkloadCompositePodGroupSingleDisruptionMode indicates that child groups +// can be disrupted independently. +message WorkloadCompositePodGroupSingleDisruptionMode { +} + +// WorkloadList contains a list of Workload resources. +message WorkloadList { + // Standard list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of Workloads. + repeated Workload items = 2; +} + +// WorkloadPodGroupAllDisruptionMode indicates that all pods in the +// group must be disrupted together. +message WorkloadPodGroupAllDisruptionMode { +} + +// WorkloadPodGroupBasicSchedulingPolicy indicates standard Kubernetes +// scheduling behavior. +message WorkloadPodGroupBasicSchedulingPolicy { +} + +// WorkloadPodGroupDisruptionMode defines how individual pods within a +// group can be disrupted. Exactly one mode must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since the selected mode is immutable in the compiled +// Workload. For example, +// +// type JobSchedulingConfiguration struct { +// // DisruptionMode defines the mode in which the Job's pods can be disrupted. +// // One of Single, All. +// // This field is immutable after creation: it may not be added or removed, +// // and the selected mode may not be changed. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// DisruptionMode *schedulingv1alpha3.WorkloadPodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,N,opt,name=disruptionMode"` +// +// // other scheduling fields +// } +// +// +union +message WorkloadPodGroupDisruptionMode { + // single specifies that pods can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadPodGroupSingleDisruptionMode single = 1; + + // all specifies that all pods in the group must be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadPodGroupAllDisruptionMode all = 2; +} + +// WorkloadPodGroupGangSchedulingPolicy defines the parameters for gang +// (all-or-nothing) scheduling. +message WorkloadPodGroupGangSchedulingPolicy { + // minCount is the minimum number of pods that must be scheduled + // at the same time for the scheduler to admit the entire group. + // This field is optional. If it is not specified, the controller + // should inject a context-specific sane default (e.g., + // parallelism for a Job). + // If set, it must be a positive integer. + // + // +optional + // +k8s:optional + // +k8s:minimum=1 + optional int32 minCount = 1; +} + +// WorkloadPodGroupResourceClaim references a dynamic resource claim +// that is shared across pods in the group. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API as a list, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the whole list after creation +// (+k8s:immutable), since the list is immutable in the compiled Workload. For +// example, +// +// type JobSchedulingConfiguration struct { +// // ResourceClaims lists the ResourceClaims shared among the group's pods. +// // At most 4 claims may be set, matching the limit on the resulting PodGroup. +// // This list is immutable after creation: entries may neither be added, +// // removed, nor modified. +// // +optional +// // +patchMergeKey=name +// // +patchStrategy=merge +// // +listType=map +// // +listMapKey=name +// // +k8s:optional +// // +k8s:listType=map +// // +k8s:listMapKey=name +// // +k8s:maxItems=4 +// // +k8s:immutable +// ResourceClaims []schedulingv1alpha3.WorkloadPodGroupResourceClaim `json:"resourceClaims,omitempty" protobuf:"bytes,N,rep,name=resourceClaims"` +// +// // other scheduling fields +// } +message WorkloadPodGroupResourceClaim { + // name uniquely identifies this resource claim inside the group. + // This field is required. It must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace. + // This field is optional. If it is not specified, no resource claim + // is used. If set, it must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimName = 2; + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace. + // This field is optional. If it is not specified, no resource claim + // template is used. If set, it must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimTemplateName = 3; +} + +// WorkloadPodGroupSchedulingConstraints defines leaf-level scheduling +// constraints, such as topology. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since constraints are immutable in the compiled Workload. +// For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingConstraints defines scheduling constraints (e.g. topology) +// // for the Job's pods. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingConstraints *schedulingv1alpha3.WorkloadPodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,N,opt,name=schedulingConstraints"` +// +// // other scheduling fields +// } +message WorkloadPodGroupSchedulingConstraints { + // topology specifies desired topological placements for all pods + // within the pod group. + // If unset, no topology placement is requested. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// WorkloadPodGroupSchedulingPolicy defines the scheduling policy for a +// group of pods managed by a workload controller. +// Exactly one policy must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to block changing the policy +// after creation, while still allowing gang.minCount to change. DV cannot +// express that only gang.minCount is mutable while the basic/gang variant is +// frozen, so the embedder must enforce variant immutability with hand-written +// validation. For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingPolicy defines the scheduling policy for this Job. +// // Exactly one of Basic or Gang must be set. +// // This field is immutable after creation: the policy may not be added or +// // removed. The policy variant (basic/gang) is frozen by the controller's +// // hand-written validation; only schedulingPolicy.gang.minCount may be changed. +// // +optional +// // +k8s:optional +// // +k8s:update=NoSet +// // +k8s:update=NoUnset +// SchedulingPolicy *schedulingv1alpha3.WorkloadPodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,N,opt,name=schedulingPolicy"` +// +// // other scheduling fields +// } +// +// +union +message WorkloadPodGroupSchedulingPolicy { + // basic specifies that standard, pod-by-pod Kubernetes scheduling + // behavior should be used. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadPodGroupBasicSchedulingPolicy basic = 1; + + // gang specifies all-or-nothing scheduling semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional WorkloadPodGroupGangSchedulingPolicy gang = 2; +} + +// WorkloadPodGroupSingleDisruptionMode indicates that individual pods +// can be disrupted independently. +message WorkloadPodGroupSingleDisruptionMode { +} + +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +message WorkloadReference { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-long-name + optional string workloadName = 1; + + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string templateName = 2; +} + +// WorkloadSpec defines the desired state of a Workload. +message WorkloadSpec { + // controllerRef is an optional reference to the controlling object, such as a + // Deployment or Job. This field is intended for use by tools like CLIs + // to provide a link back to the original workload definition. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional TypedLocalObjectReference controllerRef = 1; + + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated PodGroupTemplate podGroupTemplates = 2; + + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + // + // +featureGate=CompositePodGroup + // +optional + // +listType=map + // +listMapKey=name + // +k8s:ifDisabled("CompositePodGroup")=+k8s:forbidden + // +k8s:ifEnabled("CompositePodGroup")=+k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated CompositePodGroupTemplate compositePodGroupTemplates = 3; +} + diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/register.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/register.go similarity index 95% rename from constraint/vendor/k8s.io/api/scheduling/v1alpha2/register.go rename to constraint/vendor/k8s.io/api/scheduling/v1alpha3/register.go index fc03ae5ec..fe3bac60e 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1alpha2/register.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/register.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha2 +package v1alpha3 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -26,7 +26,7 @@ import ( const GroupName = "scheduling.k8s.io" // SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha2"} +var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha3"} // Resource takes an unqualified resource and returns a Group qualified GroupResource func Resource(resource string) schema.GroupResource { @@ -49,6 +49,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &WorkloadList{}, &PodGroup{}, &PodGroupList{}, + &CompositePodGroup{}, + &CompositePodGroupList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types.go new file mode 100644 index 000000000..138659ae4 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types.go @@ -0,0 +1,1429 @@ +/* +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 v1alpha3 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Workload allows for expressing scheduling constraints that should be used +// when managing the lifecycle of workloads from the scheduling perspective, +// including scheduling, preemption, eviction and other phases. +// Workload API enablement is toggled by the GenericWorkload feature gate. +type Workload struct { + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the desired behavior of a Workload. + // + // +required + Spec WorkloadSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// WorkloadList contains a list of Workload resources. +type WorkloadList struct { + metav1.TypeMeta `json:""` + // Standard list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of Workloads. + Items []Workload `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +const ( + // WorkloadMaxPodGroupTemplates is the maximum number of pod group templates per Workload. + WorkloadMaxPodGroupTemplates = 8 + // WorkloadMaxTreeDepth is the maximum allowed depth for a tree of (composite) pod group templates in a Workload. + WorkloadMaxTreeDepth = 4 +) + +// WorkloadSpec defines the desired state of a Workload. +type WorkloadSpec struct { + // controllerRef is an optional reference to the controlling object, such as a + // Deployment or Job. This field is intended for use by tools like CLIs + // to provide a link back to the original workload definition. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + ControllerRef *TypedLocalObjectReference `json:"controllerRef,omitempty" protobuf:"bytes,1,opt,name=controllerRef"` + + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + PodGroupTemplates []PodGroupTemplate `json:"podGroupTemplates" protobuf:"bytes,2,rep,name=podGroupTemplates"` + + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + // + // +featureGate=CompositePodGroup + // +optional + // +listType=map + // +listMapKey=name + // +k8s:ifDisabled("CompositePodGroup")=+k8s:forbidden + // +k8s:ifEnabled("CompositePodGroup")=+k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + CompositePodGroupTemplates []CompositePodGroupTemplate `json:"compositePodGroupTemplates,omitempty" protobuf:"bytes,3,rep,name=compositePodGroupTemplates"` +} + +// TypedLocalObjectReference allows to reference typed object inside the same namespace. +type TypedLocalObjectReference struct { + // apiGroup is the group for the resource being referenced. + // If APIGroup is empty, the specified Kind must be in the core API group. + // For any other third-party types, setting APIGroup is required. + // It must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,1,opt,name=apiGroup"` + // kind is the type of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` + // name is the name of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + Name string `json:"name" protobuf:"bytes,3,opt,name=name"` +} + +// MaxPodGroupResourceClaims is the maximum number of resource claims for a +// PodGroup or a Workload's PodGroupTemplate. +const MaxPodGroupResourceClaims = 4 + +// PodGroupTemplate represents a template for a set of pods with a scheduling policy. +type PodGroupTemplate struct { + // name is a unique identifier for the PodGroupTemplate within the Workload. + // It must be a DNS label. This field is immutable. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. + // + // +required + SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:immutable + SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints" protobuf:"bytes,3,opt,name=schedulingConstraints"` + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + // +k8s:immutable + ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,4,rep,name=resourceClaims"` + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,5,opt,name=disruptionMode"` + + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,6,opt,name=priorityClassName"` + + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + Priority *int32 `json:"priority,omitempty" protobuf:"varint,7,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,8,opt,name=preemptionPolicy"` +} + +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +type CompositePodGroupTemplate struct { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // schedulingPolicy defines the scheduling policy for this template. + // + // +required + SchedulingPolicy CompositePodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + SchedulingConstraints *CompositePodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,3,opt,name=schedulingConstraints"` + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *CompositeDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,4,opt,name=disruptionMode"` + + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,5,opt,name=priorityClassName"` + + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + Priority *int32 `json:"priority,omitempty" protobuf:"varint,6,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,7,opt,name=preemptionPolicy"` + + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + PodGroupTemplates []PodGroupTemplate `json:"podGroupTemplates,omitempty" protobuf:"bytes,8,rep,name=podGroupTemplates"` + + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + CompositePodGroupTemplates []CompositePodGroupTemplate `json:"compositePodGroupTemplates,omitempty" protobuf:"bytes,9,rep,name=compositePodGroupTemplates"` +} + +// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. +// +// +union +type PodGroupSchedulingPolicy struct { + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:immutable + Basic *BasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + Gang *GangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// BasicSchedulingPolicy indicates that standard Kubernetes +// scheduling behavior should be used. +type BasicSchedulingPolicy struct { + // This is intentionally empty. Its presence indicates that the basic + // scheduling policy should be applied. In the future, new fields may appear, + // describing such constraints on a pod group level without "all or nothing" + // (gang) scheduling. +} + +// GangSchedulingPolicy defines the parameters for gang scheduling. +type GangSchedulingPolicy struct { + // minCount is the minimum number of pods that must be schedulable or scheduled + // at the same time for the scheduler to admit the entire group. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. + // + // +required + // +k8s:required + // +k8s:minimum=1 + MinCount int32 `json:"minCount" protobuf:"varint,1,opt,name=minCount"` +} + +// PodGroupResourceClaim references exactly one ResourceClaim, either directly +// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim +// for the PodGroup. +// +// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. +// Pods that need access to the ResourceClaim define a matching reference in its +// own Spec.ResourceClaims. The Pod's claim must match all fields of the +// PodGroup's claim exactly. +type PodGroupResourceClaim struct { + // name uniquely identifies this resource claim inside the PodGroup. + // This must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace as this PodGroup. The ResourceClaim will be reserved for the + // PodGroup instead of its individual pods. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace as this PodGroup. + // + // The template will be used to create a new ResourceClaim, which will + // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim + // will also be deleted. The PodGroup name and resource name, along with a + // generated component, will be used to form a unique name for the + // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. + // + // This field is immutable and no changes will be made to the + // corresponding ResourceClaim by the control plane after creating the + // ResourceClaim. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty" protobuf:"bytes,3,opt,name=resourceClaimTemplateName"` +} + +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +// +// +union +type DisruptionMode struct { + // single specifies that children can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *SingleDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all children can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *AllDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// SingleDisruptionMode specifies that children can be disrupted independently. +type SingleDisruptionMode struct { + // Intentionally empty now. +} + +// AllDisruptionMode specifies that children can only be disrupted together. +type AllDisruptionMode struct { + // Intentionally empty now. +} + +// PreemptionPolicy describes a policy for if/when to preempt a pod. +// +enum +// +k8s:enum +type PreemptionPolicy string + +const ( + // PreemptLowerPriority means that pod can preempt other pods with lower priority. + PreemptLowerPriority PreemptionPolicy = "PreemptLowerPriority" + // PreemptNever means that pod never preempts other pods with lower priority. + PreemptNever PreemptionPolicy = "Never" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:supportsSubresource="/status" + +// PodGroup represents a runtime instance of pods grouped together. +// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from +// Workload.podGroupTemplates. +// PodGroup API enablement is toggled by the GenericWorkload feature gate. +type PodGroup struct { + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the desired state of the PodGroup. + // + // +required + Spec PodGroupSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status represents the current observed state of the PodGroup. + // + // +optional + Status PodGroupStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodGroupList contains a list of PodGroup resources. +type PodGroupList struct { + metav1.TypeMeta `json:""` + // Standard list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of PodGroups. + Items []PodGroup `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// PodGroupSpec defines the desired state of a PodGroup. +type PodGroupSpec struct { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + // + // +featureGate=CompositePodGroup + // +optional + // +k8s:ifDisabled(CompositePodGroup)=+k8s:forbidden + // +k8s:ifEnabled(CompositePodGroup)=+k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("workloadRef") + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty" protobuf:"bytes,1,opt,name=parentCompositePodGroupName"` + + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + WorkloadRef *WorkloadReference `json:"workloadRef,omitempty" protobuf:"bytes,2,opt,name=workloadRef"` + + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // + // +required + SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,3,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // This field is immutable. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable + SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,4,opt,name=schedulingConstraints"` + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + // +featureGate=DRAWorkloadResourceClaims + ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,5,rep,name=resourceClaims"` + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,6,opt,name=disruptionMode"` + + // priorityClassName defines the priority that should be considered when scheduling this pod group. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,7,opt,name=priorityClassName"` + + // priority is the value of priority of this pod group. Various system components + // use this field to find the priority of the pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + Priority *int32 `json:"priority,omitempty" protobuf:"varint,8,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,9,opt,name=preemptionPolicy"` +} + +// PodGroupStatus represents information about the status of a pod group. +type PodGroupStatus struct { + // conditions represent the latest observations of the PodGroup's state. + // + // Known condition types: + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the PodGroupInitiallyScheduled condition: + // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, + // affinity/anti-affinity rules, or insufficient capacity for the gang. + // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error + // that happened during scheduling, for example due to nodeAffinity parsing errors. + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for + // higher-priority PodGroups or Pods. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + + // resourceClaimStatuses is status of resource claims. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + ResourceClaimStatuses []PodGroupResourceClaimStatus `json:"resourceClaimStatuses,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,2,rep,name=resourceClaimStatuses"` +} + +// Well-known condition types for PodGroups. +const ( + // PodGroupInitiallyScheduled represents status of the scheduling process for this PodGroup till first success. + PodGroupInitiallyScheduled string = "PodGroupInitiallyScheduled" + // DisruptionTarget indicates the PodGroup is about to be terminated due to disruption + // such as preemption. + DisruptionTarget string = "DisruptionTarget" +) + +// Well-known condition reasons for PodGroups. +const ( + // Unschedulable reason in the PodGroupInitiallyScheduled condition indicates that the PodGroup cannot be scheduled + // due to resource constraints, affinity/anti-affinity rules, or insufficient capacity for the PodGroup. + PodGroupReasonUnschedulable string = "Unschedulable" + // SchedulerError reason in the PodGroupInitiallyScheduled condition means that some internal error happens + // during scheduling, for example due to nodeAffinity parsing errors. + PodGroupReasonSchedulerError string = "SchedulerError" + // PreemptionByScheduler reason in the DisruptionTarget condition indicates the PodGroup was preempted + // to make room for higher-priority PodGroups or Pods. + PodGroupReasonPreemptionByScheduler string = "PreemptionByScheduler" +) + +// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each +// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the +// generated name for the corresponding ResourceClaim. +type PodGroupResourceClaimStatus struct { + // name uniquely identifies this resource claim inside the PodGroup. This + // must match the name of an entry in podgroup.spec.resourceClaims, which + // implies that the string must be a DNS_LABEL. + // + // +required + Name string `json:"name" protobuf:"bytes,1,name=name"` + + // resourceClaimName is the name of the ResourceClaim that was generated for + // the PodGroup in the namespace of the PodGroup. If this is unset, then + // generating a ResourceClaim was not necessary. The + // podgroup.spec.resourceClaims entry can be ignored in this case. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` +} + +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +type WorkloadReference struct { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-long-name + WorkloadName string `json:"workloadName" protobuf:"bytes,1,opt,name=workloadName"` + + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + TemplateName string `json:"templateName" protobuf:"bytes,2,opt,name=templateName"` +} + +// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. +type PodGroupSchedulingConstraints struct { + // topology defines the topology constraints for the pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} + +// TopologyConstraint defines a topology constraint for a PodGroup. +type TopologyConstraint struct { + // key specifies the key of the node label representing the topology domain. + // All pods within the PodGroup must be colocated within the same domain instance. + // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. + // Examples: "topology.kubernetes.io/rack" + // + // +required + // +k8s:required + // +k8s:format=k8s-label-key + Key string `json:"key" protobuf:"bytes,1,opt,name=key"` +} + +// WorkloadPodGroupSchedulingPolicy defines the scheduling policy for a +// group of pods managed by a workload controller. +// Exactly one policy must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to block changing the policy +// after creation, while still allowing gang.minCount to change. DV cannot +// express that only gang.minCount is mutable while the basic/gang variant is +// frozen, so the embedder must enforce variant immutability with hand-written +// validation. For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingPolicy defines the scheduling policy for this Job. +// // Exactly one of Basic or Gang must be set. +// // This field is immutable after creation: the policy may not be added or +// // removed. The policy variant (basic/gang) is frozen by the controller's +// // hand-written validation; only schedulingPolicy.gang.minCount may be changed. +// // +optional +// // +k8s:optional +// // +k8s:update=NoSet +// // +k8s:update=NoUnset +// SchedulingPolicy *schedulingv1alpha3.WorkloadPodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,N,opt,name=schedulingPolicy"` +// +// // other scheduling fields +// } +// +// +union +type WorkloadPodGroupSchedulingPolicy struct { + // basic specifies that standard, pod-by-pod Kubernetes scheduling + // behavior should be used. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Basic *WorkloadPodGroupBasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies all-or-nothing scheduling semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Gang *WorkloadPodGroupGangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// WorkloadPodGroupBasicSchedulingPolicy indicates standard Kubernetes +// scheduling behavior. +type WorkloadPodGroupBasicSchedulingPolicy struct { + // Intentionally empty for now. +} + +// WorkloadPodGroupGangSchedulingPolicy defines the parameters for gang +// (all-or-nothing) scheduling. +type WorkloadPodGroupGangSchedulingPolicy struct { + // minCount is the minimum number of pods that must be scheduled + // at the same time for the scheduler to admit the entire group. + // This field is optional. If it is not specified, the controller + // should inject a context-specific sane default (e.g., + // parallelism for a Job). + // If set, it must be a positive integer. + // + // +optional + // +k8s:optional + // +k8s:minimum=1 + MinCount *int32 `json:"minCount,omitempty" protobuf:"varint,1,opt,name=minCount"` +} + +// WorkloadPodGroupSchedulingConstraints defines leaf-level scheduling +// constraints, such as topology. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since constraints are immutable in the compiled Workload. +// For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingConstraints defines scheduling constraints (e.g. topology) +// // for the Job's pods. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingConstraints *schedulingv1alpha3.WorkloadPodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,N,opt,name=schedulingConstraints"` +// +// // other scheduling fields +// } +type WorkloadPodGroupSchedulingConstraints struct { + // topology specifies desired topological placements for all pods + // within the pod group. + // If unset, no topology placement is requested. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} + +// WorkloadPodGroupResourceClaim references a dynamic resource claim +// that is shared across pods in the group. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API as a list, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the whole list after creation +// (+k8s:immutable), since the list is immutable in the compiled Workload. For +// example, +// +// type JobSchedulingConfiguration struct { +// // ResourceClaims lists the ResourceClaims shared among the group's pods. +// // At most 4 claims may be set, matching the limit on the resulting PodGroup. +// // This list is immutable after creation: entries may neither be added, +// // removed, nor modified. +// // +optional +// // +patchMergeKey=name +// // +patchStrategy=merge +// // +listType=map +// // +listMapKey=name +// // +k8s:optional +// // +k8s:listType=map +// // +k8s:listMapKey=name +// // +k8s:maxItems=4 +// // +k8s:immutable +// ResourceClaims []schedulingv1alpha3.WorkloadPodGroupResourceClaim `json:"resourceClaims,omitempty" protobuf:"bytes,N,rep,name=resourceClaims"` +// +// // other scheduling fields +// } +type WorkloadPodGroupResourceClaim struct { + // name uniquely identifies this resource claim inside the group. + // This field is required. It must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace. + // This field is optional. If it is not specified, no resource claim + // is used. If set, it must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace. + // This field is optional. If it is not specified, no resource claim + // template is used. If set, it must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty" protobuf:"bytes,3,opt,name=resourceClaimTemplateName"` +} + +// WorkloadPodGroupDisruptionMode defines how individual pods within a +// group can be disrupted. Exactly one mode must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since the selected mode is immutable in the compiled +// Workload. For example, +// +// type JobSchedulingConfiguration struct { +// // DisruptionMode defines the mode in which the Job's pods can be disrupted. +// // One of Single, All. +// // This field is immutable after creation: it may not be added or removed, +// // and the selected mode may not be changed. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// DisruptionMode *schedulingv1alpha3.WorkloadPodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,N,opt,name=disruptionMode"` +// +// // other scheduling fields +// } +// +// +union +type WorkloadPodGroupDisruptionMode struct { + // single specifies that pods can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *WorkloadPodGroupSingleDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all pods in the group must be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *WorkloadPodGroupAllDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// WorkloadPodGroupSingleDisruptionMode indicates that individual pods +// can be disrupted independently. +type WorkloadPodGroupSingleDisruptionMode struct { + // Intentionally empty for now. +} + +// WorkloadPodGroupAllDisruptionMode indicates that all pods in the +// group must be disrupted together. +type WorkloadPodGroupAllDisruptionMode struct { + // Intentionally empty for now. +} + +// WorkloadCompositePodGroupSchedulingPolicy defines the scheduling policy for a +// CompositePodGroup (a group of groups) managed by a workload controller. +// Exactly one policy must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupSchedulingPolicy. The composite +// scheduling policy is immutable, so it's recommended to freeze the whole +// field after creation (+k8s:immutable). For example, +// +// type JobSetSchedulingConfiguration struct { +// // SchedulingPolicy defines the scheduling policy for this JobSet. +// // Exactly one of Basic or Gang must be set. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingPolicy *schedulingv1alpha3.WorkloadCompositePodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,N,opt,name=schedulingPolicy"` +// +// // other scheduling fields +// } +// +// +union +type WorkloadCompositePodGroupSchedulingPolicy struct { + // basic specifies that the child groups of this composite group should be + // scheduled independently. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Basic *WorkloadCompositePodGroupBasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies that the child groups of this composite group should be + // scheduled using all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Gang *WorkloadCompositePodGroupGangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// WorkloadCompositePodGroupBasicSchedulingPolicy indicates that the child groups +// of a composite group should be scheduled independently. +type WorkloadCompositePodGroupBasicSchedulingPolicy struct { + // Intentionally empty for now. +} + +// WorkloadCompositePodGroupGangSchedulingPolicy defines the parameters for gang +// scheduling of a composite group's child groups. +type WorkloadCompositePodGroupGangSchedulingPolicy struct { + // minGroupCount is the minimum number of child groups that must be + // schedulable at the same time for the scheduler to admit the entire + // composite group. + // This field is optional. If it is not specified, the controller + // should inject a context-specific sane default (e.g., the number of + // child groups). + // If set, it must be a positive integer. + // + // +optional + // +k8s:optional + // +k8s:minimum=1 + MinGroupCount *int32 `json:"minGroupCount,omitempty" protobuf:"varint,1,opt,name=minGroupCount"` +} + +// WorkloadCompositePodGroupSchedulingConstraints defines composite-level +// scheduling constraints, such as topology, for a CompositePodGroup (a group of +// groups) managed by a workload controller. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupSchedulingConstraints. It's +// recommended to freeze the field after creation (+k8s:immutable), since +// constraints are immutable in the compiled Workload. For example, +// +// type JobSetSchedulingConfiguration struct { +// // SchedulingConstraints defines scheduling constraints (e.g. topology) +// // for this JobSet. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingConstraints *schedulingv1alpha3.WorkloadCompositePodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,N,opt,name=schedulingConstraints"` +// +// // other scheduling fields +// } +type WorkloadCompositePodGroupSchedulingConstraints struct { + // topology specifies desired topological placements for all child groups + // within the composite group. + // If unset, no topology placement is requested. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} + +// WorkloadCompositePodGroupDisruptionMode defines how the child groups of a +// composite group can be disrupted. Exactly one mode must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a composite +// controller's own API, next to its other scheduling fields. It is the +// group-of-groups analogue of WorkloadPodGroupDisruptionMode. It's recommended +// to freeze the field after creation (+k8s:immutable), since the selected mode +// is immutable in the compiled Workload. For example, +// +// type JobSetSchedulingConfiguration struct { +// // DisruptionMode defines the mode in which this JobSet's child groups +// // can be disrupted. +// // One of Single, All. +// // This field is immutable after creation: it may not be added or removed, +// // and the selected mode may not be changed. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// DisruptionMode *schedulingv1alpha3.WorkloadCompositePodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,N,opt,name=disruptionMode"` +// +// // other scheduling fields +// } +// +// +union +type WorkloadCompositePodGroupDisruptionMode struct { + // single specifies that child groups can be disrupted independently from + // each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *WorkloadCompositePodGroupSingleDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all child groups must be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *WorkloadCompositePodGroupAllDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// WorkloadCompositePodGroupSingleDisruptionMode indicates that child groups +// can be disrupted independently. +type WorkloadCompositePodGroupSingleDisruptionMode struct { + // Intentionally empty for now. +} + +// WorkloadCompositePodGroupAllDisruptionMode indicates that all child groups +// must be disrupted together. +type WorkloadCompositePodGroupAllDisruptionMode struct { + // Intentionally empty for now. +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:supportsSubresource="/status" + +// CompositePodGroup represents a runtime instance of pod groups grouped together. +// CompositePodGroups are created by workload controllers (LWS, JobSet, etc...) from +// Workload.compositePodGroupTemplates. +// CompositePodGroup API enablement is toggled by the CompositePodGroup feature gate. +type CompositePodGroup struct { + metav1.TypeMeta `json:""` + + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the desired state of the CompositePodGroup. + // + // +required + Spec CompositePodGroupSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status represents the current observed state of the CompositePodGroup. + // + // +optional + Status CompositePodGroupStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CompositePodGroupList contains a list of CompositePodGroup resources. +type CompositePodGroupList struct { + metav1.TypeMeta `json:""` + // Standard list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of CompositePodGroups. + Items []CompositePodGroup `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// CompositePodGroupSpec defines the desired state of CompositePodGroup. +type CompositePodGroupSpec struct { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this composite pod group. It must be a DNS name. + // If it's nil, then this composite pod group is a root of a workload's hierarchy. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty" protobuf:"bytes,1,opt,name=parentCompositePodGroupName"` + + // workloadRef references an optional CompositePodGroup template within the + // Workload object that was used to create the CompositePodGroup. + // This field is required. + // This field is immutable. + // + // +required + // +k8s:required + // +k8s:immutable + WorkloadRef *WorkloadReference `json:"workloadRef" protobuf:"bytes,2,opt,name=workloadRef"` + + // schedulingPolicy defines the scheduling policy for this instance of the CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + // + // +required + // +k8s:immutable + SchedulingPolicy CompositePodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,3,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + SchedulingConstraints *CompositePodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,4,opt,name=schedulingConstraints"` + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *CompositeDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,5,opt,name=disruptionMode"` + + // priorityClassName defines the priority that should be considered when scheduling this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // If left unspecified, it is validated and resolved similarly to the PriorityClassName field in Pods + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the composite pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,6,opt,name=priorityClassName"` + + // priority is the value of priority of this composite pod group. Various system components + // use this field to find the priority of the composite pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + Priority *int32 `json:"priority,omitempty" protobuf:"varint,7,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,8,opt,name=preemptionPolicy"` +} + +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +// +// +union +type CompositePodGroupSchedulingPolicy struct { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:unionMember + Basic *CompositeBasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + Gang *CompositeGangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled independently. +type CompositeBasicSchedulingPolicy struct { + // This is intentionally empty. Its presence indicates that the basic group + // scheduling policy should be applied. In the future, new fields may appear, + // describing such constraints on a composite pod group level without "all or + // nothing" (gang) scheduling. +} + +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +type CompositeGangSchedulingPolicy struct { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + // + // +required + // +k8s:required + // +k8s:minimum=1 + MinGroupCount int32 `json:"minGroupCount" protobuf:"varint,1,req,name=minGroupCount"` +} + +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +// +// +union +type CompositeDisruptionMode struct { + // single specifies that children groups can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *SingleCompositeDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all children groups can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *AllCompositeDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// SingleCompositeDisruptionMode means that individual children of a CompositePodGroup +// can be disrupted or preempted independently. +type SingleCompositeDisruptionMode struct { + // This is intentionally empty. +} + +// AllCompositeDisruptionMode means that children of a CompositePodGroup can only be +// disrupted or preempted together. +type AllCompositeDisruptionMode struct { + // This is intentionally empty. +} + +// CompositePodGroupStatus represents information about the status of a composite pod group. +type CompositePodGroupStatus struct { + // conditions represent the latest observations of the CompositePodGroup's state. + // + // Known condition types: + // - "CompositePodGroupInitiallyScheduled": Indicates whether the overall scheduling requirement + // for the subtree under this CompositePodGroup has been satisfied. Once this condition + // transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently deleted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the CompositePodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the CompositePodGroupInitiallyScheduled condition: + // - "Unschedulable": The CompositePodGroup's subtree could not be placed due to resource constraints, + // affinity/anti-affinity, or topological constraints. + // - "SchedulerError": The CompositePodGroup cannot be scheduled due to some internal error + // that occurred during scheduling. + // - "Invalid": Set to True when kube-scheduler detects an invalid group layout during + // runtime validation. The `message` field details the specific layout violation (such as + // a detected cycle, exceeding the maximum depth of 4, or referencing multiple distinct Workloads). + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The CompositePodGroup was targeted by the scheduler's preemption loop + // to free up capacity for higher-priority preemptors. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` +} + +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +type CompositePodGroupSchedulingConstraints struct { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types_swagger_doc_generated.go new file mode 100644 index 000000000..953a72fcd --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/types_swagger_doc_generated.go @@ -0,0 +1,498 @@ +/* +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 v1alpha3 + +// This file contains a collection of methods that can be used from go-restful to +// generate Swagger API documentation for its models. Please read this PR for more +// information on the implementation: https://github.com/emicklei/go-restful/pull/215 +// +// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if +// they are on one line! For multiple line or blocks that you want to ignore use ---. +// Any context after a --- is ignored. +// +// Those methods can be generated by using hack/update-codegen.sh + +// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. +var map_AllCompositeDisruptionMode = map[string]string{ + "": "AllCompositeDisruptionMode means that children of a CompositePodGroup can only be disrupted or preempted together.", +} + +func (AllCompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_AllCompositeDisruptionMode +} + +var map_AllDisruptionMode = map[string]string{ + "": "AllDisruptionMode specifies that children can only be disrupted together.", +} + +func (AllDisruptionMode) SwaggerDoc() map[string]string { + return map_AllDisruptionMode +} + +var map_BasicSchedulingPolicy = map[string]string{ + "": "BasicSchedulingPolicy indicates that standard Kubernetes scheduling behavior should be used.", +} + +func (BasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_BasicSchedulingPolicy +} + +var map_CompositeBasicSchedulingPolicy = map[string]string{ + "": "CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group should be scheduled independently.", +} + +func (CompositeBasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositeBasicSchedulingPolicy +} + +var map_CompositeDisruptionMode = map[string]string{ + "": "CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. Exactly one mode must be set.", + "single": "single specifies that children groups can be disrupted independently from each other.", + "all": "all specifies that all children groups can only be disrupted together.", +} + +func (CompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_CompositeDisruptionMode +} + +var map_CompositeGangSchedulingPolicy = map[string]string{ + "": "CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group should be scheduled using all-or-nothing semantics.", + "minGroupCount": "minGroupCount is the minimum number of child groups that must be schedulable or scheduled at the same time for the scheduler to admit the entire group. It must be a positive integer.", +} + +func (CompositeGangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositeGangSchedulingPolicy +} + +var map_CompositePodGroup = map[string]string{ + "": "CompositePodGroup represents a runtime instance of pod groups grouped together. CompositePodGroups are created by workload controllers (LWS, JobSet, etc...) from Workload.compositePodGroupTemplates. CompositePodGroup API enablement is toggled by the CompositePodGroup feature gate.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec defines the desired state of the CompositePodGroup.", + "status": "status represents the current observed state of the CompositePodGroup.", +} + +func (CompositePodGroup) SwaggerDoc() map[string]string { + return map_CompositePodGroup +} + +var map_CompositePodGroupList = map[string]string{ + "": "CompositePodGroupList contains a list of CompositePodGroup resources.", + "metadata": "Standard list metadata.", + "items": "Items is the list of CompositePodGroups.", +} + +func (CompositePodGroupList) SwaggerDoc() map[string]string { + return map_CompositePodGroupList +} + +var map_CompositePodGroupSchedulingConstraints = map[string]string{ + "": "CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup.", + "topology": "topology defines the topology constraints for the composite pod group. Currently only a single topology constraint can be specified. This may change in the future.", +} + +func (CompositePodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_CompositePodGroupSchedulingConstraints +} + +var map_CompositePodGroupSchedulingPolicy = map[string]string{ + "": "CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. Exactly one policy must be set.", + "basic": "basic specifies that the groups of this composite group should be scheduled independently. This field is immutable.", + "gang": "gang specifies that the groups of this composite group should be scheduled using all-or-nothing semantics.", +} + +func (CompositePodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositePodGroupSchedulingPolicy +} + +var map_CompositePodGroupSpec = map[string]string{ + "": "CompositePodGroupSpec defines the desired state of CompositePodGroup.", + "parentCompositePodGroupName": "parentCompositePodGroupName contains the name of the parent composite pod group within the same namespace as this composite pod group. It must be a DNS name. If it's nil, then this composite pod group is a root of a workload's hierarchy. This field is immutable.", + "workloadRef": "workloadRef references an optional CompositePodGroup template within the Workload object that was used to create the CompositePodGroup. This field is required. This field is immutable.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this instance of the CompositePodGroup. Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. This field is immutable.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroup. Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. This field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. One of Single, All. Defaults to Single if unset. This field is immutable.", + "priorityClassName": "priorityClassName defines the priority that should be considered when scheduling this CompositePodGroup. Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. If left unspecified, it is validated and resolved similarly to the PriorityClassName field in Pods (i.e. if no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, the composite pod group's priority will be zero). This field is immutable.", + "priority": "priority is the value of priority of this composite pod group. Various system components use this field to find the priority of the composite pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. When Priority Admission Controller is enabled, it populates this field from PriorityClassName, and defaults to PreemptLowerPriority if value is unset in PriorityClass. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", +} + +func (CompositePodGroupSpec) SwaggerDoc() map[string]string { + return map_CompositePodGroupSpec +} + +var map_CompositePodGroupStatus = map[string]string{ + "": "CompositePodGroupStatus represents information about the status of a composite pod group.", + "conditions": "conditions represent the latest observations of the CompositePodGroup's state.\n\nKnown condition types: - \"CompositePodGroupInitiallyScheduled\": Indicates whether the overall scheduling requirement\n for the subtree under this CompositePodGroup has been satisfied. Once this condition\n transitions to True, it serves as a terminal state and will never revert to False,\n even if pods are subsequently deleted and group constraints are no longer met.\n- \"DisruptionTarget\": Indicates whether the CompositePodGroup is about to be terminated\n due to disruption such as preemption.\n\nKnown reasons for the CompositePodGroupInitiallyScheduled condition: - \"Unschedulable\": The CompositePodGroup's subtree could not be placed due to resource constraints,\n affinity/anti-affinity, or topological constraints.\n- \"SchedulerError\": The CompositePodGroup cannot be scheduled due to some internal error\n that occurred during scheduling.\n- \"Invalid\": Set to True when kube-scheduler detects an invalid group layout during\n runtime validation. The `message` field details the specific layout violation (such as\n a detected cycle, exceeding the maximum depth of 4, or referencing multiple distinct Workloads).\n\nKnown reasons for the DisruptionTarget condition: - \"PreemptionByScheduler\": The CompositePodGroup was targeted by the scheduler's preemption loop\n to free up capacity for higher-priority preemptors.", +} + +func (CompositePodGroupStatus) SwaggerDoc() map[string]string { + return map_CompositePodGroupStatus +} + +var map_CompositePodGroupTemplate = map[string]string{ + "": "CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy.", + "name": "name is a unique identifier for the CompositePodGroupTemplate within the Workload. It must be a DNS label. This field is required.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this template.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. This field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. One of Single, All. This field is immutable.", + "priorityClassName": "priorityClassName indicates the priority that should be considered when scheduling a composite pod group created from this template. If no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, composite pod groups created from this template will have the priority set to zero. This field is immutable.", + "priority": "priority is the value of priority of composite pod groups created from this template. Various system components use this field to find the priority of the composite pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", + "podGroupTemplates": "podGroupTemplates is the list of templates for children PodGroups. The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates or PodGroupTemplates must be set.", + "compositePodGroupTemplates": "compositePodGroupTemplates is the list of templates for children CompositePodGroups. The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates or PodGroupTemplates must be set.", +} + +func (CompositePodGroupTemplate) SwaggerDoc() map[string]string { + return map_CompositePodGroupTemplate +} + +var map_DisruptionMode = map[string]string{ + "": "DisruptionMode defines how individual entities within a group can be disrupted. Exactly one mode can be set.", + "single": "single specifies that children can be disrupted independently from each other.", + "all": "all specifies that all children can only be disrupted together.", +} + +func (DisruptionMode) SwaggerDoc() map[string]string { + return map_DisruptionMode +} + +var map_GangSchedulingPolicy = map[string]string{ + "": "GangSchedulingPolicy defines the parameters for gang scheduling.", + "minCount": "minCount is the minimum number of pods that must be schedulable or scheduled at the same time for the scheduler to admit the entire group. It must be a positive integer. This field is mutable to support workload scaling.\n\nNote that the scheduler operates on an eventually consistent model. Updates to minCount may not be immediately reflected in scheduling decisions due to propagation delays. If minCount is updated while a scheduling cycle is in progress for that group, the new value may not take effect until the next cycle. Moreover, minCount is only enforced during scheduling, meaning that modifications to this field do not affect already-scheduled pods, applying only to those evaluated in future cycles.", +} + +func (GangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_GangSchedulingPolicy +} + +var map_PodGroup = map[string]string{ + "": "PodGroup represents a runtime instance of pods grouped together. PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from Workload.podGroupTemplates. PodGroup API enablement is toggled by the GenericWorkload feature gate.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec defines the desired state of the PodGroup.", + "status": "status represents the current observed state of the PodGroup.", +} + +func (PodGroup) SwaggerDoc() map[string]string { + return map_PodGroup +} + +var map_PodGroupList = map[string]string{ + "": "PodGroupList contains a list of PodGroup resources.", + "metadata": "Standard list metadata.", + "items": "Items is the list of PodGroups.", +} + +func (PodGroupList) SwaggerDoc() map[string]string { + return map_PodGroupList +} + +var map_PodGroupResourceClaim = map[string]string{ + "": "PodGroupResourceClaim references exactly one ResourceClaim, either directly or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim for the PodGroup.\n\nIt adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. Pods that need access to the ResourceClaim define a matching reference in its own Spec.ResourceClaims. The Pod's claim must match all fields of the PodGroup's claim exactly.", + "name": "name uniquely identifies this resource claim inside the PodGroup. This must be a DNS_LABEL.", + "resourceClaimName": "resourceClaimName is the name of a ResourceClaim object in the same namespace as this PodGroup. The ResourceClaim will be reserved for the PodGroup instead of its individual pods.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", + "resourceClaimTemplateName": "resourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this PodGroup.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim will also be deleted. The PodGroup name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", +} + +func (PodGroupResourceClaim) SwaggerDoc() map[string]string { + return map_PodGroupResourceClaim +} + +var map_PodGroupResourceClaimStatus = map[string]string{ + "": "PodGroupResourceClaimStatus is stored in the PodGroupStatus for each PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the generated name for the corresponding ResourceClaim.", + "name": "name uniquely identifies this resource claim inside the PodGroup. This must match the name of an entry in podgroup.spec.resourceClaims, which implies that the string must be a DNS_LABEL.", + "resourceClaimName": "resourceClaimName is the name of the ResourceClaim that was generated for the PodGroup in the namespace of the PodGroup. If this is unset, then generating a ResourceClaim was not necessary. The podgroup.spec.resourceClaims entry can be ignored in this case.", +} + +func (PodGroupResourceClaimStatus) SwaggerDoc() map[string]string { + return map_PodGroupResourceClaimStatus +} + +var map_PodGroupSchedulingConstraints = map[string]string{ + "": "PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup.", + "topology": "topology defines the topology constraints for the pod group. Currently only a single topology constraint can be specified. This may change in the future.", +} + +func (PodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_PodGroupSchedulingConstraints +} + +var map_PodGroupSchedulingPolicy = map[string]string{ + "": "PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. Exactly one policy must be set. The policy is chosen at creation time by setting either the Basic or Gang field. The PodGroup may not change policy after creation. Fields within chosen policy may be updated after creation when their individual fields allow it.", + "basic": "basic specifies that the pods in this group should be scheduled using standard Kubernetes scheduling behavior. Setting this field at group creation time opts this group to basic scheduling; this field cannot be changed afterward.", + "gang": "gang specifies that the pods in this group should be scheduled using all-or-nothing semantics. Setting this field at group creation time opts this group to gang scheduling; this field cannot be set or unset afterward. The minCount field within Gang scheduling policy remains mutable after group creation.", +} + +func (PodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_PodGroupSchedulingPolicy +} + +var map_PodGroupSpec = map[string]string{ + "": "PodGroupSpec defines the desired state of a PodGroup.", + "parentCompositePodGroupName": "parentCompositePodGroupName contains the name of the parent composite pod group within the same namespace as this pod group. If it's nil, then this pod group is a root of a workload's hierarchy. This field is used only when the CompositePodGroup feature gate is enabled. This field is immutable.", + "workloadRef": "workloadRef references an optional PodGroup template within the Workload object that was used to create the PodGroup. This field is immutable.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this instance of the PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate. This field is immutable. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled.", + "resourceClaims": "resourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is a beta-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given PodGroup can be disrupted. Controllers are expected to fill this field by copying it from a PodGroupTemplate. One of Single, All. Defaults to Single if unset. This field is immutable.", + "priorityClassName": "priorityClassName defines the priority that should be considered when scheduling this pod group. Controllers are expected to fill this field by copying it from a PodGroupTemplate. Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate (i.e. if no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, the pod group's priority will be zero). This field is immutable.", + "priority": "priority is the value of priority of this pod group. Various system components use this field to find the priority of the pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. When Priority Admission Controller is enabled, it populates this field from PriorityClassName, and defaults to PreemptLowerPriority if value is unset in PriorityClass. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", +} + +func (PodGroupSpec) SwaggerDoc() map[string]string { + return map_PodGroupSpec +} + +var map_PodGroupStatus = map[string]string{ + "": "PodGroupStatus represents information about the status of a pod group.", + "conditions": "conditions represent the latest observations of the PodGroup's state.\n\nKnown condition types: - \"PodGroupInitiallyScheduled\": Indicates whether the scheduling requirement has been satisfied. Once this condition transitions to True, it serves as a terminal state and will never revert to False, even if pods are subsequently evicted and group constraints are no longer met. - \"DisruptionTarget\": Indicates whether the PodGroup is about to be terminated\n due to disruption such as preemption.\n\nKnown reasons for the PodGroupInitiallyScheduled condition: - \"Unschedulable\": The PodGroup cannot be scheduled due to resource constraints,\n affinity/anti-affinity rules, or insufficient capacity for the gang.\n- \"SchedulerError\": The PodGroup cannot be scheduled due to some internal error\n that happened during scheduling, for example due to nodeAffinity parsing errors.\n\nKnown reasons for the DisruptionTarget condition: - \"PreemptionByScheduler\": The PodGroup was preempted by the scheduler to make room for\n higher-priority PodGroups or Pods.", + "resourceClaimStatuses": "resourceClaimStatuses is status of resource claims.", +} + +func (PodGroupStatus) SwaggerDoc() map[string]string { + return map_PodGroupStatus +} + +var map_PodGroupTemplate = map[string]string{ + "": "PodGroupTemplate represents a template for a set of pods with a scheduling policy.", + "name": "name is a unique identifier for the PodGroupTemplate within the Workload. It must be a DNS label. This field is immutable.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this PodGroupTemplate.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. This field is immutable.", + "resourceClaims": "resourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is a beta-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given PodGroup can be disrupted. One of Single, All. This field is immutable.", + "priorityClassName": "priorityClassName indicates the priority that should be considered when scheduling a pod group created from this template. This field is immutable.", + "priority": "priority is the value of priority of pod groups created from this template. Various system components use this field to find the priority of the pod group. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", +} + +func (PodGroupTemplate) SwaggerDoc() map[string]string { + return map_PodGroupTemplate +} + +var map_SingleCompositeDisruptionMode = map[string]string{ + "": "SingleCompositeDisruptionMode means that individual children of a CompositePodGroup can be disrupted or preempted independently.", +} + +func (SingleCompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_SingleCompositeDisruptionMode +} + +var map_SingleDisruptionMode = map[string]string{ + "": "SingleDisruptionMode specifies that children can be disrupted independently.", +} + +func (SingleDisruptionMode) SwaggerDoc() map[string]string { + return map_SingleDisruptionMode +} + +var map_TopologyConstraint = map[string]string{ + "": "TopologyConstraint defines a topology constraint for a PodGroup.", + "key": "key specifies the key of the node label representing the topology domain. All pods within the PodGroup must be colocated within the same domain instance. Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. Examples: \"topology.kubernetes.io/rack\"", +} + +func (TopologyConstraint) SwaggerDoc() map[string]string { + return map_TopologyConstraint +} + +var map_TypedLocalObjectReference = map[string]string{ + "": "TypedLocalObjectReference allows to reference typed object inside the same namespace.", + "apiGroup": "apiGroup is the group for the resource being referenced. If APIGroup is empty, the specified Kind must be in the core API group. For any other third-party types, setting APIGroup is required. It must be a DNS subdomain.", + "kind": "kind is the type of resource being referenced. It must be a path segment name.", + "name": "name is the name of resource being referenced. It must be a path segment name.", +} + +func (TypedLocalObjectReference) SwaggerDoc() map[string]string { + return map_TypedLocalObjectReference +} + +var map_Workload = map[string]string{ + "": "Workload allows for expressing scheduling constraints that should be used when managing the lifecycle of workloads from the scheduling perspective, including scheduling, preemption, eviction and other phases. Workload API enablement is toggled by the GenericWorkload feature gate.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec defines the desired behavior of a Workload.", +} + +func (Workload) SwaggerDoc() map[string]string { + return map_Workload +} + +var map_WorkloadCompositePodGroupAllDisruptionMode = map[string]string{ + "": "WorkloadCompositePodGroupAllDisruptionMode indicates that all child groups must be disrupted together.", +} + +func (WorkloadCompositePodGroupAllDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupAllDisruptionMode +} + +var map_WorkloadCompositePodGroupBasicSchedulingPolicy = map[string]string{ + "": "WorkloadCompositePodGroupBasicSchedulingPolicy indicates that the child groups of a composite group should be scheduled independently.", +} + +func (WorkloadCompositePodGroupBasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupBasicSchedulingPolicy +} + +var map_WorkloadCompositePodGroupDisruptionMode = map[string]string{ + "": "WorkloadCompositePodGroupDisruptionMode defines how the child groups of a composite group can be disrupted. Exactly one mode must be set.", + "single": "single specifies that child groups can be disrupted independently from each other.", + "all": "all specifies that all child groups must be disrupted together.", +} + +func (WorkloadCompositePodGroupDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupDisruptionMode +} + +var map_WorkloadCompositePodGroupGangSchedulingPolicy = map[string]string{ + "": "WorkloadCompositePodGroupGangSchedulingPolicy defines the parameters for gang scheduling of a composite group's child groups.", + "minGroupCount": "minGroupCount is the minimum number of child groups that must be schedulable at the same time for the scheduler to admit the entire composite group. This field is optional. If it is not specified, the controller should inject a context-specific sane default (e.g., the number of child groups). If set, it must be a positive integer.", +} + +func (WorkloadCompositePodGroupGangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupGangSchedulingPolicy +} + +var map_WorkloadCompositePodGroupSchedulingConstraints = map[string]string{ + "": "WorkloadCompositePodGroupSchedulingConstraints defines composite-level scheduling constraints, such as topology, for a CompositePodGroup (a group of groups) managed by a workload controller.", + "topology": "topology specifies desired topological placements for all child groups within the composite group. If unset, no topology placement is requested.", +} + +func (WorkloadCompositePodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupSchedulingConstraints +} + +var map_WorkloadCompositePodGroupSchedulingPolicy = map[string]string{ + "": "WorkloadCompositePodGroupSchedulingPolicy defines the scheduling policy for a CompositePodGroup (a group of groups) managed by a workload controller. Exactly one policy must be set.", + "basic": "basic specifies that the child groups of this composite group should be scheduled independently.", + "gang": "gang specifies that the child groups of this composite group should be scheduled using all-or-nothing semantics.", +} + +func (WorkloadCompositePodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupSchedulingPolicy +} + +var map_WorkloadCompositePodGroupSingleDisruptionMode = map[string]string{ + "": "WorkloadCompositePodGroupSingleDisruptionMode indicates that child groups can be disrupted independently.", +} + +func (WorkloadCompositePodGroupSingleDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadCompositePodGroupSingleDisruptionMode +} + +var map_WorkloadList = map[string]string{ + "": "WorkloadList contains a list of Workload resources.", + "metadata": "Standard list metadata.", + "items": "Items is the list of Workloads.", +} + +func (WorkloadList) SwaggerDoc() map[string]string { + return map_WorkloadList +} + +var map_WorkloadPodGroupAllDisruptionMode = map[string]string{ + "": "WorkloadPodGroupAllDisruptionMode indicates that all pods in the group must be disrupted together.", +} + +func (WorkloadPodGroupAllDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupAllDisruptionMode +} + +var map_WorkloadPodGroupBasicSchedulingPolicy = map[string]string{ + "": "WorkloadPodGroupBasicSchedulingPolicy indicates standard Kubernetes scheduling behavior.", +} + +func (WorkloadPodGroupBasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupBasicSchedulingPolicy +} + +var map_WorkloadPodGroupDisruptionMode = map[string]string{ + "": "WorkloadPodGroupDisruptionMode defines how individual pods within a group can be disrupted. Exactly one mode must be set.", + "single": "single specifies that pods can be disrupted independently from each other.", + "all": "all specifies that all pods in the group must be disrupted together.", +} + +func (WorkloadPodGroupDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupDisruptionMode +} + +var map_WorkloadPodGroupGangSchedulingPolicy = map[string]string{ + "": "WorkloadPodGroupGangSchedulingPolicy defines the parameters for gang (all-or-nothing) scheduling.", + "minCount": "minCount is the minimum number of pods that must be scheduled at the same time for the scheduler to admit the entire group. This field is optional. If it is not specified, the controller should inject a context-specific sane default (e.g., parallelism for a Job). If set, it must be a positive integer.", +} + +func (WorkloadPodGroupGangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupGangSchedulingPolicy +} + +var map_WorkloadPodGroupResourceClaim = map[string]string{ + "": "WorkloadPodGroupResourceClaim references a dynamic resource claim that is shared across pods in the group.", + "name": "name uniquely identifies this resource claim inside the group. This field is required. It must be a DNS_LABEL.", + "resourceClaimName": "resourceClaimName is the name of a ResourceClaim object in the same namespace. This field is optional. If it is not specified, no resource claim is used. If set, it must be a DNS subdomain.", + "resourceClaimTemplateName": "resourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace. This field is optional. If it is not specified, no resource claim template is used. If set, it must be a DNS subdomain.", +} + +func (WorkloadPodGroupResourceClaim) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupResourceClaim +} + +var map_WorkloadPodGroupSchedulingConstraints = map[string]string{ + "": "WorkloadPodGroupSchedulingConstraints defines leaf-level scheduling constraints, such as topology.", + "topology": "topology specifies desired topological placements for all pods within the pod group. If unset, no topology placement is requested.", +} + +func (WorkloadPodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupSchedulingConstraints +} + +var map_WorkloadPodGroupSchedulingPolicy = map[string]string{ + "": "WorkloadPodGroupSchedulingPolicy defines the scheduling policy for a group of pods managed by a workload controller. Exactly one policy must be set.", + "basic": "basic specifies that standard, pod-by-pod Kubernetes scheduling behavior should be used.", + "gang": "gang specifies all-or-nothing scheduling semantics.", +} + +func (WorkloadPodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupSchedulingPolicy +} + +var map_WorkloadPodGroupSingleDisruptionMode = map[string]string{ + "": "WorkloadPodGroupSingleDisruptionMode indicates that individual pods can be disrupted independently.", +} + +func (WorkloadPodGroupSingleDisruptionMode) SwaggerDoc() map[string]string { + return map_WorkloadPodGroupSingleDisruptionMode +} + +var map_WorkloadReference = map[string]string{ + "": "WorkloadReference references the Workload object together with the template that was used to create a particular PodGroup.", + "workloadName": "workloadName is the name of the Workload object that contains a template that was used when creating a pod group. It must be a DNS name. This field is required.", + "templateName": "templateName is the name of a template within the Workload object that was used to create a pod group. It must be a DNS label. This field is required.", +} + +func (WorkloadReference) SwaggerDoc() map[string]string { + return map_WorkloadReference +} + +var map_WorkloadSpec = map[string]string{ + "": "WorkloadSpec defines the desired state of a Workload.", + "controllerRef": "controllerRef is an optional reference to the controlling object, such as a Deployment or Job. This field is intended for use by tools like CLIs to provide a link back to the original workload definition. This field is immutable.", + "podGroupTemplates": "podGroupTemplates is the list of templates that make up the Workload. The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. Existing templates may still be updated where their individual fields allow it. Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set.", + "compositePodGroupTemplates": "compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. The maximum number of templates is 8. This field is immutable. Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set.\n\nThis field is used only when the CompositePodGroup feature gate is enabled.", +} + +func (WorkloadSpec) SwaggerDoc() map[string]string { + return map_WorkloadSpec +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.deepcopy.go new file mode 100644 index 000000000..ae0a82088 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.deepcopy.go @@ -0,0 +1,1172 @@ +//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 deepcopy-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AllCompositeDisruptionMode) DeepCopyInto(out *AllCompositeDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllCompositeDisruptionMode. +func (in *AllCompositeDisruptionMode) DeepCopy() *AllCompositeDisruptionMode { + if in == nil { + return nil + } + out := new(AllCompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AllDisruptionMode) DeepCopyInto(out *AllDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllDisruptionMode. +func (in *AllDisruptionMode) DeepCopy() *AllDisruptionMode { + if in == nil { + return nil + } + out := new(AllDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BasicSchedulingPolicy) DeepCopyInto(out *BasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicSchedulingPolicy. +func (in *BasicSchedulingPolicy) DeepCopy() *BasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(BasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeBasicSchedulingPolicy) DeepCopyInto(out *CompositeBasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeBasicSchedulingPolicy. +func (in *CompositeBasicSchedulingPolicy) DeepCopy() *CompositeBasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositeBasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeDisruptionMode) DeepCopyInto(out *CompositeDisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(SingleCompositeDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(AllCompositeDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeDisruptionMode. +func (in *CompositeDisruptionMode) DeepCopy() *CompositeDisruptionMode { + if in == nil { + return nil + } + out := new(CompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeGangSchedulingPolicy) DeepCopyInto(out *CompositeGangSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeGangSchedulingPolicy. +func (in *CompositeGangSchedulingPolicy) DeepCopy() *CompositeGangSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositeGangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroup) DeepCopyInto(out *CompositePodGroup) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroup. +func (in *CompositePodGroup) DeepCopy() *CompositePodGroup { + if in == nil { + return nil + } + out := new(CompositePodGroup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CompositePodGroup) 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 *CompositePodGroupList) DeepCopyInto(out *CompositePodGroupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CompositePodGroup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupList. +func (in *CompositePodGroupList) DeepCopy() *CompositePodGroupList { + if in == nil { + return nil + } + out := new(CompositePodGroupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CompositePodGroupList) 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 *CompositePodGroupSchedulingConstraints) DeepCopyInto(out *CompositePodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupSchedulingConstraints. +func (in *CompositePodGroupSchedulingConstraints) DeepCopy() *CompositePodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(CompositePodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupSchedulingPolicy) DeepCopyInto(out *CompositePodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(CompositeBasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(CompositeGangSchedulingPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupSchedulingPolicy. +func (in *CompositePodGroupSchedulingPolicy) DeepCopy() *CompositePodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositePodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupSpec) DeepCopyInto(out *CompositePodGroupSpec) { + *out = *in + if in.ParentCompositePodGroupName != nil { + in, out := &in.ParentCompositePodGroupName, &out.ParentCompositePodGroupName + *out = new(string) + **out = **in + } + if in.WorkloadRef != nil { + in, out := &in.WorkloadRef, &out.WorkloadRef + *out = new(WorkloadReference) + **out = **in + } + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(CompositePodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(CompositeDisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupSpec. +func (in *CompositePodGroupSpec) DeepCopy() *CompositePodGroupSpec { + if in == nil { + return nil + } + out := new(CompositePodGroupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupStatus) DeepCopyInto(out *CompositePodGroupStatus) { + *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]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupStatus. +func (in *CompositePodGroupStatus) DeepCopy() *CompositePodGroupStatus { + if in == nil { + return nil + } + out := new(CompositePodGroupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupTemplate) DeepCopyInto(out *CompositePodGroupTemplate) { + *out = *in + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(CompositePodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(CompositeDisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + if in.PodGroupTemplates != nil { + in, out := &in.PodGroupTemplates, &out.PodGroupTemplates + *out = make([]PodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.CompositePodGroupTemplates != nil { + in, out := &in.CompositePodGroupTemplates, &out.CompositePodGroupTemplates + *out = make([]CompositePodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupTemplate. +func (in *CompositePodGroupTemplate) DeepCopy() *CompositePodGroupTemplate { + if in == nil { + return nil + } + out := new(CompositePodGroupTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DisruptionMode) DeepCopyInto(out *DisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(SingleDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(AllDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DisruptionMode. +func (in *DisruptionMode) DeepCopy() *DisruptionMode { + if in == nil { + return nil + } + out := new(DisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GangSchedulingPolicy) DeepCopyInto(out *GangSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GangSchedulingPolicy. +func (in *GangSchedulingPolicy) DeepCopy() *GangSchedulingPolicy { + if in == nil { + return nil + } + out := new(GangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroup) DeepCopyInto(out *PodGroup) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroup. +func (in *PodGroup) DeepCopy() *PodGroup { + if in == nil { + return nil + } + out := new(PodGroup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodGroup) 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 *PodGroupList) DeepCopyInto(out *PodGroupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodGroup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupList. +func (in *PodGroupList) DeepCopy() *PodGroupList { + if in == nil { + return nil + } + out := new(PodGroupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodGroupList) 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 *PodGroupResourceClaim) DeepCopyInto(out *PodGroupResourceClaim) { + *out = *in + if in.ResourceClaimName != nil { + in, out := &in.ResourceClaimName, &out.ResourceClaimName + *out = new(string) + **out = **in + } + if in.ResourceClaimTemplateName != nil { + in, out := &in.ResourceClaimTemplateName, &out.ResourceClaimTemplateName + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaim. +func (in *PodGroupResourceClaim) DeepCopy() *PodGroupResourceClaim { + if in == nil { + return nil + } + out := new(PodGroupResourceClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupResourceClaimStatus) DeepCopyInto(out *PodGroupResourceClaimStatus) { + *out = *in + if in.ResourceClaimName != nil { + in, out := &in.ResourceClaimName, &out.ResourceClaimName + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaimStatus. +func (in *PodGroupResourceClaimStatus) DeepCopy() *PodGroupResourceClaimStatus { + if in == nil { + return nil + } + out := new(PodGroupResourceClaimStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSchedulingConstraints) DeepCopyInto(out *PodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingConstraints. +func (in *PodGroupSchedulingConstraints) DeepCopy() *PodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(PodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSchedulingPolicy) DeepCopyInto(out *PodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(BasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(GangSchedulingPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingPolicy. +func (in *PodGroupSchedulingPolicy) DeepCopy() *PodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(PodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSpec) DeepCopyInto(out *PodGroupSpec) { + *out = *in + if in.ParentCompositePodGroupName != nil { + in, out := &in.ParentCompositePodGroupName, &out.ParentCompositePodGroupName + *out = new(string) + **out = **in + } + if in.WorkloadRef != nil { + in, out := &in.WorkloadRef, &out.WorkloadRef + *out = new(WorkloadReference) + **out = **in + } + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(PodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.ResourceClaims != nil { + in, out := &in.ResourceClaims, &out.ResourceClaims + *out = make([]PodGroupResourceClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(DisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSpec. +func (in *PodGroupSpec) DeepCopy() *PodGroupSpec { + if in == nil { + return nil + } + out := new(PodGroupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupStatus) DeepCopyInto(out *PodGroupStatus) { + *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.ResourceClaimStatuses != nil { + in, out := &in.ResourceClaimStatuses, &out.ResourceClaimStatuses + *out = make([]PodGroupResourceClaimStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupStatus. +func (in *PodGroupStatus) DeepCopy() *PodGroupStatus { + if in == nil { + return nil + } + out := new(PodGroupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupTemplate) DeepCopyInto(out *PodGroupTemplate) { + *out = *in + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(PodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.ResourceClaims != nil { + in, out := &in.ResourceClaims, &out.ResourceClaims + *out = make([]PodGroupResourceClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(DisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupTemplate. +func (in *PodGroupTemplate) DeepCopy() *PodGroupTemplate { + if in == nil { + return nil + } + out := new(PodGroupTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SingleCompositeDisruptionMode) DeepCopyInto(out *SingleCompositeDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SingleCompositeDisruptionMode. +func (in *SingleCompositeDisruptionMode) DeepCopy() *SingleCompositeDisruptionMode { + if in == nil { + return nil + } + out := new(SingleCompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SingleDisruptionMode) DeepCopyInto(out *SingleDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SingleDisruptionMode. +func (in *SingleDisruptionMode) DeepCopy() *SingleDisruptionMode { + if in == nil { + return nil + } + out := new(SingleDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TopologyConstraint) DeepCopyInto(out *TopologyConstraint) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TopologyConstraint. +func (in *TopologyConstraint) DeepCopy() *TopologyConstraint { + if in == nil { + return nil + } + out := new(TopologyConstraint) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TypedLocalObjectReference) DeepCopyInto(out *TypedLocalObjectReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TypedLocalObjectReference. +func (in *TypedLocalObjectReference) DeepCopy() *TypedLocalObjectReference { + if in == nil { + return nil + } + out := new(TypedLocalObjectReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Workload) DeepCopyInto(out *Workload) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Workload. +func (in *Workload) DeepCopy() *Workload { + if in == nil { + return nil + } + out := new(Workload) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Workload) 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 *WorkloadCompositePodGroupAllDisruptionMode) DeepCopyInto(out *WorkloadCompositePodGroupAllDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupAllDisruptionMode. +func (in *WorkloadCompositePodGroupAllDisruptionMode) DeepCopy() *WorkloadCompositePodGroupAllDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupAllDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupBasicSchedulingPolicy) DeepCopyInto(out *WorkloadCompositePodGroupBasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupBasicSchedulingPolicy. +func (in *WorkloadCompositePodGroupBasicSchedulingPolicy) DeepCopy() *WorkloadCompositePodGroupBasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupBasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupDisruptionMode) DeepCopyInto(out *WorkloadCompositePodGroupDisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(WorkloadCompositePodGroupSingleDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(WorkloadCompositePodGroupAllDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupDisruptionMode. +func (in *WorkloadCompositePodGroupDisruptionMode) DeepCopy() *WorkloadCompositePodGroupDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupGangSchedulingPolicy) DeepCopyInto(out *WorkloadCompositePodGroupGangSchedulingPolicy) { + *out = *in + if in.MinGroupCount != nil { + in, out := &in.MinGroupCount, &out.MinGroupCount + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupGangSchedulingPolicy. +func (in *WorkloadCompositePodGroupGangSchedulingPolicy) DeepCopy() *WorkloadCompositePodGroupGangSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupGangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupSchedulingConstraints) DeepCopyInto(out *WorkloadCompositePodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupSchedulingConstraints. +func (in *WorkloadCompositePodGroupSchedulingConstraints) DeepCopy() *WorkloadCompositePodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupSchedulingPolicy) DeepCopyInto(out *WorkloadCompositePodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(WorkloadCompositePodGroupBasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(WorkloadCompositePodGroupGangSchedulingPolicy) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupSchedulingPolicy. +func (in *WorkloadCompositePodGroupSchedulingPolicy) DeepCopy() *WorkloadCompositePodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadCompositePodGroupSingleDisruptionMode) DeepCopyInto(out *WorkloadCompositePodGroupSingleDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadCompositePodGroupSingleDisruptionMode. +func (in *WorkloadCompositePodGroupSingleDisruptionMode) DeepCopy() *WorkloadCompositePodGroupSingleDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadCompositePodGroupSingleDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadList) DeepCopyInto(out *WorkloadList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Workload, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadList. +func (in *WorkloadList) DeepCopy() *WorkloadList { + if in == nil { + return nil + } + out := new(WorkloadList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *WorkloadList) 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 *WorkloadPodGroupAllDisruptionMode) DeepCopyInto(out *WorkloadPodGroupAllDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupAllDisruptionMode. +func (in *WorkloadPodGroupAllDisruptionMode) DeepCopy() *WorkloadPodGroupAllDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadPodGroupAllDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupBasicSchedulingPolicy) DeepCopyInto(out *WorkloadPodGroupBasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupBasicSchedulingPolicy. +func (in *WorkloadPodGroupBasicSchedulingPolicy) DeepCopy() *WorkloadPodGroupBasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadPodGroupBasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupDisruptionMode) DeepCopyInto(out *WorkloadPodGroupDisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(WorkloadPodGroupSingleDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(WorkloadPodGroupAllDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupDisruptionMode. +func (in *WorkloadPodGroupDisruptionMode) DeepCopy() *WorkloadPodGroupDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadPodGroupDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupGangSchedulingPolicy) DeepCopyInto(out *WorkloadPodGroupGangSchedulingPolicy) { + *out = *in + if in.MinCount != nil { + in, out := &in.MinCount, &out.MinCount + *out = new(int32) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupGangSchedulingPolicy. +func (in *WorkloadPodGroupGangSchedulingPolicy) DeepCopy() *WorkloadPodGroupGangSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadPodGroupGangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupResourceClaim) DeepCopyInto(out *WorkloadPodGroupResourceClaim) { + *out = *in + if in.ResourceClaimName != nil { + in, out := &in.ResourceClaimName, &out.ResourceClaimName + *out = new(string) + **out = **in + } + if in.ResourceClaimTemplateName != nil { + in, out := &in.ResourceClaimTemplateName, &out.ResourceClaimTemplateName + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupResourceClaim. +func (in *WorkloadPodGroupResourceClaim) DeepCopy() *WorkloadPodGroupResourceClaim { + if in == nil { + return nil + } + out := new(WorkloadPodGroupResourceClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupSchedulingConstraints) DeepCopyInto(out *WorkloadPodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupSchedulingConstraints. +func (in *WorkloadPodGroupSchedulingConstraints) DeepCopy() *WorkloadPodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(WorkloadPodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupSchedulingPolicy) DeepCopyInto(out *WorkloadPodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(WorkloadPodGroupBasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(WorkloadPodGroupGangSchedulingPolicy) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupSchedulingPolicy. +func (in *WorkloadPodGroupSchedulingPolicy) DeepCopy() *WorkloadPodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(WorkloadPodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadPodGroupSingleDisruptionMode) DeepCopyInto(out *WorkloadPodGroupSingleDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadPodGroupSingleDisruptionMode. +func (in *WorkloadPodGroupSingleDisruptionMode) DeepCopy() *WorkloadPodGroupSingleDisruptionMode { + if in == nil { + return nil + } + out := new(WorkloadPodGroupSingleDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadReference) DeepCopyInto(out *WorkloadReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadReference. +func (in *WorkloadReference) DeepCopy() *WorkloadReference { + if in == nil { + return nil + } + out := new(WorkloadReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadSpec) DeepCopyInto(out *WorkloadSpec) { + *out = *in + if in.ControllerRef != nil { + in, out := &in.ControllerRef, &out.ControllerRef + *out = new(TypedLocalObjectReference) + **out = **in + } + if in.PodGroupTemplates != nil { + in, out := &in.PodGroupTemplates, &out.PodGroupTemplates + *out = make([]PodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.CompositePodGroupTemplates != nil { + in, out := &in.CompositePodGroupTemplates, &out.CompositePodGroupTemplates + *out = make([]CompositePodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadSpec. +func (in *WorkloadSpec) DeepCopy() *WorkloadSpec { + if in == nil { + return nil + } + out := new(WorkloadSpec) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.model_name.go new file mode 100644 index 000000000..acd9818f2 --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.model_name.go @@ -0,0 +1,257 @@ +//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 v1alpha3 + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in AllCompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.AllCompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in AllDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.AllDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in BasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.BasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeBasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositeBasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeGangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositeGangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroup) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroup" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupList) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupSpec) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupStatus) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupTemplate) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.CompositePodGroupTemplate" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.DisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in GangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.GangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroup) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroup" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupList) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupResourceClaim) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaim" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupResourceClaimStatus) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaimStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSpec) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupStatus) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupTemplate) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.PodGroupTemplate" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in SingleCompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.SingleCompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in SingleDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.SingleDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in TopologyConstraint) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.TopologyConstraint" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in TypedLocalObjectReference) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.TypedLocalObjectReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in Workload) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.Workload" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupAllDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupAllDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupBasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupBasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupGangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupGangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadCompositePodGroupSingleDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadCompositePodGroupSingleDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadList) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupAllDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupAllDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupBasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupBasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupGangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupGangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupResourceClaim) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupResourceClaim" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadPodGroupSingleDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSingleDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadReference) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadSpec) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1alpha3.WorkloadSpec" +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.validations.go b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.validations.go new file mode 100644 index 000000000..3202dbe2b --- /dev/null +++ b/constraint/vendor/k8s.io/api/scheduling/v1alpha3/zz_generated.validations.go @@ -0,0 +1,3368 @@ +//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 validation-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + + equality "k8s.io/apimachinery/pkg/api/equality" + operation "k8s.io/apimachinery/pkg/api/operation" + safe "k8s.io/apimachinery/pkg/api/safe" + validate "k8s.io/apimachinery/pkg/api/validate" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + sets "k8s.io/apimachinery/pkg/util/sets" + field "k8s.io/apimachinery/pkg/util/validation/field" +) + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_CompositeDisruptionMode_ = validate.NewUnionMembership(validate.NewUnionMember("single"), validate.NewUnionMember("all")) + +// Validate_CompositeDisruptionMode validates an instance of CompositeDisruptionMode according +// to declarative validation rules in the API schema. +func Validate_CompositeDisruptionMode( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositeDisruptionMode) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_CompositeDisruptionMode_, + func(obj *CompositeDisruptionMode) bool { + if obj == nil { + return false + } + return obj.Single != nil + }, + func(obj *CompositeDisruptionMode) bool { + if obj == nil { + return false + } + return obj.All != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field CompositeDisruptionMode.Single + fn := func( + fldPath *field.Path, + obj, oldObj *SingleCompositeDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositeDisruptionMode) *SingleCompositeDisruptionMode { + return oldObj.Single + }) + errs = append(errs, fn(fldPath.Child("single"), obj.Single, oldVal, oldObj != nil)...) + } + + { // field CompositeDisruptionMode.All + fn := func( + fldPath *field.Path, + obj, oldObj *AllCompositeDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositeDisruptionMode) *AllCompositeDisruptionMode { + return oldObj.All + }) + errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositeGangSchedulingPolicy validates an instance of CompositeGangSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_CompositeGangSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositeGangSchedulingPolicy) (errs field.ErrorList) { + + { // field CompositeGangSchedulingPolicy.MinGroupCount + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositeGangSchedulingPolicy) *int32 { + return &oldObj.MinGroupCount + }) + errs = append(errs, fn(fldPath.Child("minGroupCount"), &obj.MinGroupCount, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositePodGroup validates an instance of CompositePodGroup according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroup( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroup) (errs field.ErrorList) { + + // field CompositePodGroup.TypeMeta has no validation + + { // field CompositePodGroup.ObjectMeta + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectMeta, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, validation.Validate_ObjectMeta(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroup) *v1.ObjectMeta { + return &oldObj.ObjectMeta + }) + errs = append(errs, fn(fldPath.Child("metadata"), &obj.ObjectMeta, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroup.Spec + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupSpec, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupSpec(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroup) *CompositePodGroupSpec { + return &oldObj.Spec + }) + errs = append(errs, fn(fldPath.Child("spec"), &obj.Spec, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroup.Status + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupStatus(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroup) *CompositePodGroupStatus { + return &oldObj.Status + }) + errs = append(errs, fn(fldPath.Child("status"), &obj.Status, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositePodGroupSchedulingConstraints validates an instance of CompositePodGroupSchedulingConstraints according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroupSchedulingConstraints( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingConstraints) (errs field.ErrorList) { + + { // field CompositePodGroupSchedulingConstraints.Topology + fn := func( + fldPath *field.Path, + obj, oldObj []TopologyConstraint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_TopologyConstraint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSchedulingConstraints) []TopologyConstraint { + return oldObj.Topology + }) + errs = append(errs, fn(fldPath.Child("topology"), obj.Topology, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_CompositePodGroupSchedulingPolicy_ = validate.NewUnionMembership(validate.NewUnionMember("basic"), validate.NewUnionMember("gang")) + +// Validate_CompositePodGroupSchedulingPolicy validates an instance of CompositePodGroupSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroupSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingPolicy) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_CompositePodGroupSchedulingPolicy_, + func(obj *CompositePodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Basic != nil + }, + func(obj *CompositePodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Gang != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field CompositePodGroupSchedulingPolicy.Basic + fn := func( + fldPath *field.Path, + obj, oldObj *CompositeBasicSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSchedulingPolicy) *CompositeBasicSchedulingPolicy { + return oldObj.Basic + }) + errs = append(errs, fn(fldPath.Child("basic"), obj.Basic, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSchedulingPolicy.Gang + fn := func( + fldPath *field.Path, + obj, oldObj *CompositeGangSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoSet, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositeGangSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSchedulingPolicy) *CompositeGangSchedulingPolicy { + return oldObj.Gang + }) + errs = append(errs, fn(fldPath.Child("gang"), obj.Gang, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositePodGroupSpec validates an instance of CompositePodGroupSpec according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroupSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroupSpec) (errs field.ErrorList) { + + { // field CompositePodGroupSpec.ParentCompositePodGroupName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *string { + return oldObj.ParentCompositePodGroupName + }) + errs = append(errs, fn(fldPath.Child("parentCompositePodGroupName"), obj.ParentCompositePodGroupName, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.WorkloadRef + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadReference, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_WorkloadReference(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *WorkloadReference { + return oldObj.WorkloadRef + }) + errs = append(errs, fn(fldPath.Child("workloadRef"), obj.WorkloadRef, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.SchedulingPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *CompositePodGroupSchedulingPolicy { + return &oldObj.SchedulingPolicy + }) + errs = append(errs, fn(fldPath.Child("schedulingPolicy"), &obj.SchedulingPolicy, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.SchedulingConstraints + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingConstraints, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupSchedulingConstraints(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *CompositePodGroupSchedulingConstraints { + return oldObj.SchedulingConstraints + }) + errs = append(errs, fn(fldPath.Child("schedulingConstraints"), obj.SchedulingConstraints, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.DisruptionMode + fn := func( + fldPath *field.Path, + obj, oldObj *CompositeDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + // optional fields with default values are effectively required + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositeDisruptionMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *CompositeDisruptionMode { + return oldObj.DisruptionMode + }) + errs = append(errs, fn(fldPath.Child("disruptionMode"), obj.DisruptionMode, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.PriorityClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *string { + return &oldObj.PriorityClassName + }) + errs = append(errs, fn(fldPath.Child("priorityClassName"), &obj.PriorityClassName, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.Priority + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1000000000); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *int32 { + return oldObj.Priority + }) + errs = append(errs, fn(fldPath.Child("priority"), obj.Priority, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupSpec.PreemptionPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PreemptionPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PreemptionPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupSpec) *PreemptionPolicy { + return oldObj.PreemptionPolicy + }) + errs = append(errs, fn(fldPath.Child("preemptionPolicy"), obj.PreemptionPolicy, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositePodGroupStatus validates an instance of CompositePodGroupStatus according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroupStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroupStatus) (errs field.ErrorList) { + + { // field CompositePodGroupStatus.Conditions + fn := func( + fldPath *field.Path, + obj, oldObj []v1.Condition, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *v1.Condition, b *v1.Condition) bool { return a.Type == b.Type }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *v1.Condition, b *v1.Condition) bool { return a.Type == b.Type }, validate.SemanticDeepEqual, validation.Validate_Condition); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupStatus) []v1.Condition { + return oldObj.Conditions + }) + errs = append(errs, fn(fldPath.Child("conditions"), obj.Conditions, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CompositePodGroupTemplate validates an instance of CompositePodGroupTemplate according +// to declarative validation rules in the API schema. +func Validate_CompositePodGroupTemplate( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *CompositePodGroupTemplate) (errs field.ErrorList) { + + { // field CompositePodGroupTemplate.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.SchedulingPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *CompositePodGroupSchedulingPolicy { + return &oldObj.SchedulingPolicy + }) + errs = append(errs, fn(fldPath.Child("schedulingPolicy"), &obj.SchedulingPolicy, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.SchedulingConstraints + fn := func( + fldPath *field.Path, + obj, oldObj *CompositePodGroupSchedulingConstraints, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositePodGroupSchedulingConstraints(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *CompositePodGroupSchedulingConstraints { + return oldObj.SchedulingConstraints + }) + errs = append(errs, fn(fldPath.Child("schedulingConstraints"), obj.SchedulingConstraints, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.DisruptionMode + fn := func( + fldPath *field.Path, + obj, oldObj *CompositeDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_CompositeDisruptionMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *CompositeDisruptionMode { + return oldObj.DisruptionMode + }) + errs = append(errs, fn(fldPath.Child("disruptionMode"), obj.DisruptionMode, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.PriorityClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *string { + return &oldObj.PriorityClassName + }) + errs = append(errs, fn(fldPath.Child("priorityClassName"), &obj.PriorityClassName, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.Priority + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1000000000); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *int32 { + return oldObj.Priority + }) + errs = append(errs, fn(fldPath.Child("priority"), obj.Priority, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.PreemptionPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PreemptionPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PreemptionPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) *PreemptionPolicy { + return oldObj.PreemptionPolicy + }) + errs = append(errs, fn(fldPath.Child("preemptionPolicy"), obj.PreemptionPolicy, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.PodGroupTemplates + fn := func( + fldPath *field.Path, + obj, oldObj []PodGroupTemplate, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.ValSliceUpdate(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }, validate.NoAddItem, validate.NoRemoveItem).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_PodGroupTemplate); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) []PodGroupTemplate { + return oldObj.PodGroupTemplates + }) + errs = append(errs, fn(fldPath.Child("podGroupTemplates"), obj.PodGroupTemplates, oldVal, oldObj != nil)...) + } + + { // field CompositePodGroupTemplate.CompositePodGroupTemplates + fn := func( + fldPath *field.Path, + obj, oldObj []CompositePodGroupTemplate, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.ValSliceUpdate(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }, validate.NoAddItem, validate.NoRemoveItem).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_CompositePodGroupTemplate); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *CompositePodGroupTemplate) []CompositePodGroupTemplate { + return oldObj.CompositePodGroupTemplates + }) + errs = append(errs, fn(fldPath.Child("compositePodGroupTemplates"), obj.CompositePodGroupTemplates, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_DisruptionMode_ = validate.NewUnionMembership(validate.NewUnionMember("single"), validate.NewUnionMember("all")) + +// Validate_DisruptionMode validates an instance of DisruptionMode according +// to declarative validation rules in the API schema. +func Validate_DisruptionMode( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *DisruptionMode) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_DisruptionMode_, + func(obj *DisruptionMode) bool { + if obj == nil { + return false + } + return obj.Single != nil + }, + func(obj *DisruptionMode) bool { + if obj == nil { + return false + } + return obj.All != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field DisruptionMode.Single + fn := func( + fldPath *field.Path, + obj, oldObj *SingleDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DisruptionMode) *SingleDisruptionMode { + return oldObj.Single + }) + errs = append(errs, fn(fldPath.Child("single"), obj.Single, oldVal, oldObj != nil)...) + } + + { // field DisruptionMode.All + fn := func( + fldPath *field.Path, + obj, oldObj *AllDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *DisruptionMode) *AllDisruptionMode { + return oldObj.All + }) + errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GangSchedulingPolicy validates an instance of GangSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_GangSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *GangSchedulingPolicy) (errs field.ErrorList) { + + { // field GangSchedulingPolicy.MinCount + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *GangSchedulingPolicy) *int32 { + return &oldObj.MinCount + }) + errs = append(errs, fn(fldPath.Child("minCount"), &obj.MinCount, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroup validates an instance of PodGroup according +// to declarative validation rules in the API schema. +func Validate_PodGroup( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroup) (errs field.ErrorList) { + + // field PodGroup.TypeMeta has no validation + + { // field PodGroup.ObjectMeta + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectMeta, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, validation.Validate_ObjectMeta(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroup) *v1.ObjectMeta { + return &oldObj.ObjectMeta + }) + errs = append(errs, fn(fldPath.Child("metadata"), &obj.ObjectMeta, oldVal, oldObj != nil)...) + } + + { // field PodGroup.Spec + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupSpec, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_PodGroupSpec(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroup) *PodGroupSpec { + return &oldObj.Spec + }) + errs = append(errs, fn(fldPath.Child("spec"), &obj.Spec, oldVal, oldObj != nil)...) + } + + { // field PodGroup.Status + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_PodGroupStatus(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroup) *PodGroupStatus { + return &oldObj.Status + }) + errs = append(errs, fn(fldPath.Child("status"), &obj.Status, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_PodGroupResourceClaim_ = validate.NewUnionMembership(validate.NewUnionMember("resourceClaimName"), validate.NewUnionMember("resourceClaimTemplateName")) + +// Validate_PodGroupResourceClaim validates an instance of PodGroupResourceClaim according +// to declarative validation rules in the API schema. +func Validate_PodGroupResourceClaim( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupResourceClaim) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_PodGroupResourceClaim_, + func(obj *PodGroupResourceClaim) bool { + if obj == nil { + return false + } + return obj.ResourceClaimName != nil + }, + func(obj *PodGroupResourceClaim) bool { + if obj == nil { + return false + } + return obj.ResourceClaimTemplateName != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field PodGroupResourceClaim.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupResourceClaim) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field PodGroupResourceClaim.ResourceClaimName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupResourceClaim) *string { + return oldObj.ResourceClaimName + }) + errs = append(errs, fn(fldPath.Child("resourceClaimName"), obj.ResourceClaimName, oldVal, oldObj != nil)...) + } + + { // field PodGroupResourceClaim.ResourceClaimTemplateName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupResourceClaim) *string { + return oldObj.ResourceClaimTemplateName + }) + errs = append(errs, fn(fldPath.Child("resourceClaimTemplateName"), obj.ResourceClaimTemplateName, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroupResourceClaimStatus validates an instance of PodGroupResourceClaimStatus according +// to declarative validation rules in the API schema. +func Validate_PodGroupResourceClaimStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupResourceClaimStatus) (errs field.ErrorList) { + + // field PodGroupResourceClaimStatus.Name has no validation + + { // field PodGroupResourceClaimStatus.ResourceClaimName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupResourceClaimStatus) *string { + return oldObj.ResourceClaimName + }) + errs = append(errs, fn(fldPath.Child("resourceClaimName"), obj.ResourceClaimName, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroupSchedulingConstraints validates an instance of PodGroupSchedulingConstraints according +// to declarative validation rules in the API schema. +func Validate_PodGroupSchedulingConstraints( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupSchedulingConstraints) (errs field.ErrorList) { + + { // field PodGroupSchedulingConstraints.Topology + fn := func( + fldPath *field.Path, + obj, oldObj []TopologyConstraint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_TopologyConstraint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSchedulingConstraints) []TopologyConstraint { + return oldObj.Topology + }) + errs = append(errs, fn(fldPath.Child("topology"), obj.Topology, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_PodGroupSchedulingPolicy_ = validate.NewUnionMembership(validate.NewUnionMember("basic"), validate.NewUnionMember("gang")) + +// Validate_PodGroupSchedulingPolicy validates an instance of PodGroupSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_PodGroupSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupSchedulingPolicy) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_PodGroupSchedulingPolicy_, + func(obj *PodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Basic != nil + }, + func(obj *PodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Gang != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field PodGroupSchedulingPolicy.Basic + fn := func( + fldPath *field.Path, + obj, oldObj *BasicSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSchedulingPolicy) *BasicSchedulingPolicy { + return oldObj.Basic + }) + errs = append(errs, fn(fldPath.Child("basic"), obj.Basic, oldVal, oldObj != nil)...) + } + + { // field PodGroupSchedulingPolicy.Gang + fn := func( + fldPath *field.Path, + obj, oldObj *GangSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoSet, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_GangSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSchedulingPolicy) *GangSchedulingPolicy { + return oldObj.Gang + }) + errs = append(errs, fn(fldPath.Child("gang"), obj.Gang, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroupSpec validates an instance of PodGroupSpec according +// to declarative validation rules in the API schema. +func Validate_PodGroupSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupSpec) (errs field.ErrorList) { + + if e := validate.DependentRequired(ctx, op, fldPath, obj, oldObj, "parentCompositePodGroupName", + func(obj *PodGroupSpec) bool { + if obj == nil { + return false + } + return obj.ParentCompositePodGroupName != nil + }, "workloadRef", + func(obj *PodGroupSpec) bool { + if obj == nil { + return false + } + return obj.WorkloadRef != nil + }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + + { // field PodGroupSpec.ParentCompositePodGroupName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *string { + return oldObj.ParentCompositePodGroupName + }) + errs = append(errs, fn(fldPath.Child("parentCompositePodGroupName"), obj.ParentCompositePodGroupName, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.WorkloadRef + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadReference, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_WorkloadReference(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *WorkloadReference { + return oldObj.WorkloadRef + }) + errs = append(errs, fn(fldPath.Child("workloadRef"), obj.WorkloadRef, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.SchedulingPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_PodGroupSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *PodGroupSchedulingPolicy { + return &oldObj.SchedulingPolicy + }) + errs = append(errs, fn(fldPath.Child("schedulingPolicy"), &obj.SchedulingPolicy, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.SchedulingConstraints + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupSchedulingConstraints, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", true, validate.Immutable).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PodGroupSchedulingConstraints(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *PodGroupSchedulingConstraints { + return oldObj.SchedulingConstraints + }) + errs = append(errs, fn(fldPath.Child("schedulingConstraints"), obj.SchedulingConstraints, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.ResourceClaims + fn := func( + fldPath *field.Path, + obj, oldObj []PodGroupResourceClaim, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaim, b *PodGroupResourceClaim) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaim, b *PodGroupResourceClaim) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_PodGroupResourceClaim); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) []PodGroupResourceClaim { + return oldObj.ResourceClaims + }) + errs = append(errs, fn(fldPath.Child("resourceClaims"), obj.ResourceClaims, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.DisruptionMode + fn := func( + fldPath *field.Path, + obj, oldObj *DisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + // optional fields with default values are effectively required + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DisruptionMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *DisruptionMode { + return oldObj.DisruptionMode + }) + errs = append(errs, fn(fldPath.Child("disruptionMode"), obj.DisruptionMode, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.PriorityClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *string { + return &oldObj.PriorityClassName + }) + errs = append(errs, fn(fldPath.Child("priorityClassName"), &obj.PriorityClassName, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.Priority + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1000000000); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *int32 { + return oldObj.Priority + }) + errs = append(errs, fn(fldPath.Child("priority"), obj.Priority, oldVal, oldObj != nil)...) + } + + { // field PodGroupSpec.PreemptionPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PreemptionPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PreemptionPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupSpec) *PreemptionPolicy { + return oldObj.PreemptionPolicy + }) + errs = append(errs, fn(fldPath.Child("preemptionPolicy"), obj.PreemptionPolicy, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroupStatus validates an instance of PodGroupStatus according +// to declarative validation rules in the API schema. +func Validate_PodGroupStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupStatus) (errs field.ErrorList) { + + { // field PodGroupStatus.Conditions + fn := func( + fldPath *field.Path, + obj, oldObj []v1.Condition, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *v1.Condition, b *v1.Condition) bool { return a.Type == b.Type }).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *v1.Condition, b *v1.Condition) bool { return a.Type == b.Type }, validate.SemanticDeepEqual, validation.Validate_Condition); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupStatus) []v1.Condition { + return oldObj.Conditions + }) + errs = append(errs, fn(fldPath.Child("conditions"), obj.Conditions, oldVal, oldObj != nil)...) + } + + { // field PodGroupStatus.ResourceClaimStatuses + fn := func( + fldPath *field.Path, + obj, oldObj []PodGroupResourceClaimStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaimStatus, b *PodGroupResourceClaimStatus) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaimStatus, b *PodGroupResourceClaimStatus) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_PodGroupResourceClaimStatus); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupStatus) []PodGroupResourceClaimStatus { + return oldObj.ResourceClaimStatuses + }) + errs = append(errs, fn(fldPath.Child("resourceClaimStatuses"), obj.ResourceClaimStatuses, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_PodGroupTemplate validates an instance of PodGroupTemplate according +// to declarative validation rules in the API schema. +func Validate_PodGroupTemplate( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PodGroupTemplate) (errs field.ErrorList) { + + { // field PodGroupTemplate.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.SchedulingPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_PodGroupSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *PodGroupSchedulingPolicy { + return &oldObj.SchedulingPolicy + }) + errs = append(errs, fn(fldPath.Child("schedulingPolicy"), &obj.SchedulingPolicy, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.SchedulingConstraints + fn := func( + fldPath *field.Path, + obj, oldObj *PodGroupSchedulingConstraints, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "TopologyAwareWorkloadScheduling", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PodGroupSchedulingConstraints(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *PodGroupSchedulingConstraints { + return oldObj.SchedulingConstraints + }) + errs = append(errs, fn(fldPath.Child("schedulingConstraints"), obj.SchedulingConstraints, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.ResourceClaims + fn := func( + fldPath *field.Path, + obj, oldObj []PodGroupResourceClaim, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 4).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaim, b *PodGroupResourceClaim) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupResourceClaim, b *PodGroupResourceClaim) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_PodGroupResourceClaim); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) []PodGroupResourceClaim { + return oldObj.ResourceClaims + }) + errs = append(errs, fn(fldPath.Child("resourceClaims"), obj.ResourceClaims, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.DisruptionMode + fn := func( + fldPath *field.Path, + obj, oldObj *DisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DisruptionMode(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *DisruptionMode { + return oldObj.DisruptionMode + }) + errs = append(errs, fn(fldPath.Child("disruptionMode"), obj.DisruptionMode, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.PriorityClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *string { + return &oldObj.PriorityClassName + }) + errs = append(errs, fn(fldPath.Child("priorityClassName"), &obj.PriorityClassName, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.Priority + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1000000000); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *int32 { + return oldObj.Priority + }) + errs = append(errs, fn(fldPath.Child("priority"), obj.Priority, oldVal, oldObj != nil)...) + } + + { // field PodGroupTemplate.PreemptionPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *PreemptionPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", false, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PodGroupPreemptionPolicy", true, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_PreemptionPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *PodGroupTemplate) *PreemptionPolicy { + return oldObj.PreemptionPolicy + }) + errs = append(errs, fn(fldPath.Child("preemptionPolicy"), obj.PreemptionPolicy, oldVal, oldObj != nil)...) + } + + return errs +} + +var symbolsForPreemptionPolicy = sets.New(PreemptLowerPriority, PreemptNever) + +// Validate_PreemptionPolicy validates an instance of PreemptionPolicy according +// to declarative validation rules in the API schema. +func Validate_PreemptionPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *PreemptionPolicy) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForPreemptionPolicy, nil); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_TopologyConstraint validates an instance of TopologyConstraint according +// to declarative validation rules in the API schema. +func Validate_TopologyConstraint( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *TopologyConstraint) (errs field.ErrorList) { + + { // field TopologyConstraint.Key + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LabelKey(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *TopologyConstraint) *string { + return &oldObj.Key + }) + errs = append(errs, fn(fldPath.Child("key"), &obj.Key, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_TypedLocalObjectReference validates an instance of TypedLocalObjectReference according +// to declarative validation rules in the API schema. +func Validate_TypedLocalObjectReference( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *TypedLocalObjectReference) (errs field.ErrorList) { + + { // field TypedLocalObjectReference.APIGroup + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *TypedLocalObjectReference) *string { + return &oldObj.APIGroup + }) + errs = append(errs, fn(fldPath.Child("apiGroup"), &obj.APIGroup, oldVal, oldObj != nil)...) + } + + { // field TypedLocalObjectReference.Kind + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.PathSegmentName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *TypedLocalObjectReference) *string { + return &oldObj.Kind + }) + errs = append(errs, fn(fldPath.Child("kind"), &obj.Kind, oldVal, oldObj != nil)...) + } + + { // field TypedLocalObjectReference.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.PathSegmentName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *TypedLocalObjectReference) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_Workload validates an instance of Workload according +// to declarative validation rules in the API schema. +func Validate_Workload( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *Workload) (errs field.ErrorList) { + + // field Workload.TypeMeta has no validation + + { // field Workload.ObjectMeta + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectMeta, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, validation.Validate_ObjectMeta(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Workload) *v1.ObjectMeta { + return &oldObj.ObjectMeta + }) + errs = append(errs, fn(fldPath.Child("metadata"), &obj.ObjectMeta, oldVal, oldObj != nil)...) + } + + { // field Workload.Spec + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadSpec, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call the type's validation function + errs = append(errs, Validate_WorkloadSpec(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Workload) *WorkloadSpec { + return &oldObj.Spec + }) + errs = append(errs, fn(fldPath.Child("spec"), &obj.Spec, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadCompositePodGroupDisruptionMode_ = validate.NewUnionMembership(validate.NewUnionMember("single"), validate.NewUnionMember("all")) + +// Validate_WorkloadCompositePodGroupDisruptionMode validates an instance of WorkloadCompositePodGroupDisruptionMode according +// to declarative validation rules in the API schema. +func Validate_WorkloadCompositePodGroupDisruptionMode( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupDisruptionMode) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadCompositePodGroupDisruptionMode_, + func(obj *WorkloadCompositePodGroupDisruptionMode) bool { + if obj == nil { + return false + } + return obj.Single != nil + }, + func(obj *WorkloadCompositePodGroupDisruptionMode) bool { + if obj == nil { + return false + } + return obj.All != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadCompositePodGroupDisruptionMode.Single + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupSingleDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupDisruptionMode) *WorkloadCompositePodGroupSingleDisruptionMode { + return oldObj.Single + }) + errs = append(errs, fn(fldPath.Child("single"), obj.Single, oldVal, oldObj != nil)...) + } + + { // field WorkloadCompositePodGroupDisruptionMode.All + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupAllDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupDisruptionMode) *WorkloadCompositePodGroupAllDisruptionMode { + return oldObj.All + }) + errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_WorkloadCompositePodGroupGangSchedulingPolicy validates an instance of WorkloadCompositePodGroupGangSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_WorkloadCompositePodGroupGangSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupGangSchedulingPolicy) (errs field.ErrorList) { + + { // field WorkloadCompositePodGroupGangSchedulingPolicy.MinGroupCount + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupGangSchedulingPolicy) *int32 { + return oldObj.MinGroupCount + }) + errs = append(errs, fn(fldPath.Child("minGroupCount"), obj.MinGroupCount, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_WorkloadCompositePodGroupSchedulingConstraints validates an instance of WorkloadCompositePodGroupSchedulingConstraints according +// to declarative validation rules in the API schema. +func Validate_WorkloadCompositePodGroupSchedulingConstraints( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupSchedulingConstraints) (errs field.ErrorList) { + + { // field WorkloadCompositePodGroupSchedulingConstraints.Topology + fn := func( + fldPath *field.Path, + obj, oldObj []TopologyConstraint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_TopologyConstraint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupSchedulingConstraints) []TopologyConstraint { + return oldObj.Topology + }) + errs = append(errs, fn(fldPath.Child("topology"), obj.Topology, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadCompositePodGroupSchedulingPolicy_ = validate.NewUnionMembership(validate.NewUnionMember("basic"), validate.NewUnionMember("gang")) + +// Validate_WorkloadCompositePodGroupSchedulingPolicy validates an instance of WorkloadCompositePodGroupSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_WorkloadCompositePodGroupSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupSchedulingPolicy) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadCompositePodGroupSchedulingPolicy_, + func(obj *WorkloadCompositePodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Basic != nil + }, + func(obj *WorkloadCompositePodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Gang != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadCompositePodGroupSchedulingPolicy.Basic + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupBasicSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupSchedulingPolicy) *WorkloadCompositePodGroupBasicSchedulingPolicy { + return oldObj.Basic + }) + errs = append(errs, fn(fldPath.Child("basic"), obj.Basic, oldVal, oldObj != nil)...) + } + + { // field WorkloadCompositePodGroupSchedulingPolicy.Gang + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadCompositePodGroupGangSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_WorkloadCompositePodGroupGangSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadCompositePodGroupSchedulingPolicy) *WorkloadCompositePodGroupGangSchedulingPolicy { + return oldObj.Gang + }) + errs = append(errs, fn(fldPath.Child("gang"), obj.Gang, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupDisruptionMode_ = validate.NewUnionMembership(validate.NewUnionMember("single"), validate.NewUnionMember("all")) + +// Validate_WorkloadPodGroupDisruptionMode validates an instance of WorkloadPodGroupDisruptionMode according +// to declarative validation rules in the API schema. +func Validate_WorkloadPodGroupDisruptionMode( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadPodGroupDisruptionMode) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupDisruptionMode_, + func(obj *WorkloadPodGroupDisruptionMode) bool { + if obj == nil { + return false + } + return obj.Single != nil + }, + func(obj *WorkloadPodGroupDisruptionMode) bool { + if obj == nil { + return false + } + return obj.All != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadPodGroupDisruptionMode.Single + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadPodGroupSingleDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupDisruptionMode) *WorkloadPodGroupSingleDisruptionMode { + return oldObj.Single + }) + errs = append(errs, fn(fldPath.Child("single"), obj.Single, oldVal, oldObj != nil)...) + } + + { // field WorkloadPodGroupDisruptionMode.All + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadPodGroupAllDisruptionMode, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupDisruptionMode) *WorkloadPodGroupAllDisruptionMode { + return oldObj.All + }) + errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_WorkloadPodGroupGangSchedulingPolicy validates an instance of WorkloadPodGroupGangSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_WorkloadPodGroupGangSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadPodGroupGangSchedulingPolicy) (errs field.ErrorList) { + + { // field WorkloadPodGroupGangSchedulingPolicy.MinCount + fn := func( + fldPath *field.Path, + obj, oldObj *int32, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupGangSchedulingPolicy) *int32 { + return oldObj.MinCount + }) + errs = append(errs, fn(fldPath.Child("minCount"), obj.MinCount, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupResourceClaim_ = validate.NewUnionMembership(validate.NewUnionMember("resourceClaimName"), validate.NewUnionMember("resourceClaimTemplateName")) + +// Validate_WorkloadPodGroupResourceClaim validates an instance of WorkloadPodGroupResourceClaim according +// to declarative validation rules in the API schema. +func Validate_WorkloadPodGroupResourceClaim( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadPodGroupResourceClaim) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupResourceClaim_, + func(obj *WorkloadPodGroupResourceClaim) bool { + if obj == nil { + return false + } + return obj.ResourceClaimName != nil + }, + func(obj *WorkloadPodGroupResourceClaim) bool { + if obj == nil { + return false + } + return obj.ResourceClaimTemplateName != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadPodGroupResourceClaim.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupResourceClaim) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field WorkloadPodGroupResourceClaim.ResourceClaimName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupResourceClaim) *string { + return oldObj.ResourceClaimName + }) + errs = append(errs, fn(fldPath.Child("resourceClaimName"), obj.ResourceClaimName, oldVal, oldObj != nil)...) + } + + { // field WorkloadPodGroupResourceClaim.ResourceClaimTemplateName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupResourceClaim) *string { + return oldObj.ResourceClaimTemplateName + }) + errs = append(errs, fn(fldPath.Child("resourceClaimTemplateName"), obj.ResourceClaimTemplateName, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_WorkloadPodGroupSchedulingConstraints validates an instance of WorkloadPodGroupSchedulingConstraints according +// to declarative validation rules in the API schema. +func Validate_WorkloadPodGroupSchedulingConstraints( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadPodGroupSchedulingConstraints) (errs field.ErrorList) { + + { // field WorkloadPodGroupSchedulingConstraints.Topology + fn := func( + fldPath *field.Path, + obj, oldObj []TopologyConstraint, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_TopologyConstraint); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupSchedulingConstraints) []TopologyConstraint { + return oldObj.Topology + }) + errs = append(errs, fn(fldPath.Child("topology"), obj.Topology, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupSchedulingPolicy_ = validate.NewUnionMembership(validate.NewUnionMember("basic"), validate.NewUnionMember("gang")) + +// Validate_WorkloadPodGroupSchedulingPolicy validates an instance of WorkloadPodGroupSchedulingPolicy according +// to declarative validation rules in the API schema. +func Validate_WorkloadPodGroupSchedulingPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadPodGroupSchedulingPolicy) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadPodGroupSchedulingPolicy_, + func(obj *WorkloadPodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Basic != nil + }, + func(obj *WorkloadPodGroupSchedulingPolicy) bool { + if obj == nil { + return false + } + return obj.Gang != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadPodGroupSchedulingPolicy.Basic + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadPodGroupBasicSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupSchedulingPolicy) *WorkloadPodGroupBasicSchedulingPolicy { + return oldObj.Basic + }) + errs = append(errs, fn(fldPath.Child("basic"), obj.Basic, oldVal, oldObj != nil)...) + } + + { // field WorkloadPodGroupSchedulingPolicy.Gang + fn := func( + fldPath *field.Path, + obj, oldObj *WorkloadPodGroupGangSchedulingPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_WorkloadPodGroupGangSchedulingPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadPodGroupSchedulingPolicy) *WorkloadPodGroupGangSchedulingPolicy { + return oldObj.Gang + }) + errs = append(errs, fn(fldPath.Child("gang"), obj.Gang, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_WorkloadReference validates an instance of WorkloadReference according +// to declarative validation rules in the API schema. +func Validate_WorkloadReference( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadReference) (errs field.ErrorList) { + + { // field WorkloadReference.WorkloadName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadReference) *string { + return &oldObj.WorkloadName + }) + errs = append(errs, fn(fldPath.Child("workloadName"), &obj.WorkloadName, oldVal, oldObj != nil)...) + } + + { // field WorkloadReference.TemplateName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadReference) *string { + return &oldObj.TemplateName + }) + errs = append(errs, fn(fldPath.Child("templateName"), &obj.TemplateName, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadSpec_ = validate.NewUnionMembership(validate.NewUnionMember("podGroupTemplates"), validate.NewUnionMember("compositePodGroupTemplates")) + +// Validate_WorkloadSpec validates an instance of WorkloadSpec according +// to declarative validation rules in the API schema. +func Validate_WorkloadSpec( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *WorkloadSpec) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_k8s_io_api_scheduling_v1alpha3_WorkloadSpec_, + func(obj *WorkloadSpec) bool { + if obj == nil { + return false + } + return len(obj.PodGroupTemplates) != 0 + }, + func(obj *WorkloadSpec) bool { + if obj == nil { + return false + } + return len(obj.CompositePodGroupTemplates) != 0 + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field WorkloadSpec.ControllerRef + fn := func( + fldPath *field.Path, + obj, oldObj *TypedLocalObjectReference, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_TypedLocalObjectReference(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadSpec) *TypedLocalObjectReference { + return oldObj.ControllerRef + }) + errs = append(errs, fn(fldPath.Child("controllerRef"), obj.ControllerRef, oldVal, oldObj != nil)...) + } + + { // field WorkloadSpec.PodGroupTemplates + fn := func( + fldPath *field.Path, + obj, oldObj []PodGroupTemplate, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.ValSliceUpdate(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }, validate.NoAddItem, validate.NoRemoveItem).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *PodGroupTemplate, b *PodGroupTemplate) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_PodGroupTemplate); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadSpec) []PodGroupTemplate { + return oldObj.PodGroupTemplates + }) + errs = append(errs, fn(fldPath.Child("podGroupTemplates"), obj.PodGroupTemplates, oldVal, oldObj != nil)...) + } + + { // field WorkloadSpec.CompositePodGroupTemplates + fn := func( + fldPath *field.Path, + obj, oldObj []CompositePodGroupTemplate, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", false, validate.ForbiddenSlice).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", false, validate.OptionalSlice).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "CompositePodGroup", true, validate.OptionalSlice).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.ValSliceUpdate(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }, validate.NoAddItem, validate.NoRemoveItem).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *CompositePodGroupTemplate, b *CompositePodGroupTemplate) bool { return a.Name == b.Name }, validate.SemanticDeepEqual, Validate_CompositePodGroupTemplate); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *WorkloadSpec) []CompositePodGroupTemplate { + return oldObj.CompositePodGroupTemplates + }) + errs = append(errs, fn(fldPath.Child("compositePodGroupTemplates"), obj.CompositePodGroupTemplates, oldVal, oldObj != nil)...) + } + + return errs +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.pb.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.pb.go index cd25ded40..d8572d3c0 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.pb.go @@ -25,17 +25,76 @@ import ( io "io" k8s_io_api_core_v1 "k8s.io/api/core/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" math_bits "math/bits" reflect "reflect" strings "strings" ) +func (m *AllCompositeDisruptionMode) Reset() { *m = AllCompositeDisruptionMode{} } + +func (m *AllDisruptionMode) Reset() { *m = AllDisruptionMode{} } + +func (m *BasicSchedulingPolicy) Reset() { *m = BasicSchedulingPolicy{} } + +func (m *CompositeBasicSchedulingPolicy) Reset() { *m = CompositeBasicSchedulingPolicy{} } + +func (m *CompositeDisruptionMode) Reset() { *m = CompositeDisruptionMode{} } + +func (m *CompositeGangSchedulingPolicy) Reset() { *m = CompositeGangSchedulingPolicy{} } + +func (m *CompositePodGroupSchedulingConstraints) Reset() { + *m = CompositePodGroupSchedulingConstraints{} +} + +func (m *CompositePodGroupSchedulingPolicy) Reset() { *m = CompositePodGroupSchedulingPolicy{} } + +func (m *CompositePodGroupTemplate) Reset() { *m = CompositePodGroupTemplate{} } + +func (m *DisruptionMode) Reset() { *m = DisruptionMode{} } + +func (m *GangSchedulingPolicy) Reset() { *m = GangSchedulingPolicy{} } + +func (m *PodGroup) Reset() { *m = PodGroup{} } + +func (m *PodGroupList) Reset() { *m = PodGroupList{} } + +func (m *PodGroupResourceClaim) Reset() { *m = PodGroupResourceClaim{} } + +func (m *PodGroupResourceClaimStatus) Reset() { *m = PodGroupResourceClaimStatus{} } + +func (m *PodGroupSchedulingConstraints) Reset() { *m = PodGroupSchedulingConstraints{} } + +func (m *PodGroupSchedulingPolicy) Reset() { *m = PodGroupSchedulingPolicy{} } + +func (m *PodGroupSpec) Reset() { *m = PodGroupSpec{} } + +func (m *PodGroupStatus) Reset() { *m = PodGroupStatus{} } + +func (m *PodGroupTemplate) Reset() { *m = PodGroupTemplate{} } + func (m *PriorityClass) Reset() { *m = PriorityClass{} } func (m *PriorityClassList) Reset() { *m = PriorityClassList{} } -func (m *PriorityClass) Marshal() (dAtA []byte, err error) { +func (m *SingleCompositeDisruptionMode) Reset() { *m = SingleCompositeDisruptionMode{} } + +func (m *SingleDisruptionMode) Reset() { *m = SingleDisruptionMode{} } + +func (m *TopologyConstraint) Reset() { *m = TopologyConstraint{} } + +func (m *TypedLocalObjectReference) Reset() { *m = TypedLocalObjectReference{} } + +func (m *Workload) Reset() { *m = Workload{} } + +func (m *WorkloadList) Reset() { *m = WorkloadList{} } + +func (m *WorkloadReference) Reset() { *m = WorkloadReference{} } + +func (m *WorkloadSpec) Reset() { *m = WorkloadSpec{} } + +func (m *AllCompositeDisruptionMode) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -45,53 +104,162 @@ func (m *PriorityClass) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PriorityClass) MarshalTo(dAtA []byte) (int, error) { +func (m *AllCompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PriorityClass) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *AllCompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.PreemptionPolicy != nil { - i -= len(*m.PreemptionPolicy) - copy(dAtA[i:], *m.PreemptionPolicy) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) - i-- - dAtA[i] = 0x2a + return len(dAtA) - i, nil +} + +func (m *AllDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x22 - i-- - if m.GlobalDefault { - dAtA[i] = 1 - } else { - dAtA[i] = 0 + return dAtA[:n], nil +} + +func (m *AllDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AllDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *BasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - i-- - dAtA[i] = 0x18 - i = encodeVarintGenerated(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x10 - { - size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + return dAtA[:n], nil +} + +func (m *BasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *BasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *CompositeBasicSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositeBasicSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeBasicSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *CompositeDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *CompositeGangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } + return dAtA[:n], nil +} + +func (m *CompositeGangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CompositeGangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i = encodeVarintGenerated(dAtA, i, uint64(m.MinGroupCount)) i-- - dAtA[i] = 0xa + dAtA[i] = 0x8 return len(dAtA) - i, nil } -func (m *PriorityClassList) Marshal() (dAtA []byte, err error) { +func (m *CompositePodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -101,20 +269,20 @@ func (m *PriorityClassList) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *PriorityClassList) MarshalTo(dAtA []byte) (int, error) { +func (m *CompositePodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PriorityClassList) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *CompositePodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if len(m.Items) > 0 { - for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { { - size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -122,114 +290,5354 @@ func (m *PriorityClassList) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenerated(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + dAtA[i] = 0xa } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ +func (m *CompositePodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *PriorityClass) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ObjectMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - n += 1 + sovGenerated(uint64(m.Value)) - n += 2 - l = len(m.Description) - n += 1 + l + sovGenerated(uint64(l)) - if m.PreemptionPolicy != nil { - l = len(*m.PreemptionPolicy) - n += 1 + l + sovGenerated(uint64(l)) - } - return n + +func (m *CompositePodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PriorityClassList) Size() (n int) { - if m == nil { - return 0 - } +func (m *CompositePodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.ListMeta.Size() - n += 1 + l + sovGenerated(uint64(l)) - if len(m.Items) > 0 { - for _, e := range m.Items { - l = e.Size() - n += 1 + l + sovGenerated(uint64(l)) + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x12 } - return n + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil } -func sovGenerated(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 +func (m *CompositePodGroupTemplate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil } -func sozGenerated(x uint64) (n int) { - return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) + +func (m *CompositePodGroupTemplate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (this *PriorityClass) String() string { - if this == nil { + +func (m *CompositePodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CompositePodGroupTemplates) > 0 { + for iNdEx := len(m.CompositePodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CompositePodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + } + } + if len(m.PodGroupTemplates) > 0 { + for iNdEx := len(m.PodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x3a + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x30 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x2a + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *DisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.All != nil { + { + size, err := m.All.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Single != nil { + { + size, err := m.Single.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *GangSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GangSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GangSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i = encodeVarintGenerated(dAtA, i, uint64(m.MinCount)) + i-- + dAtA[i] = 0x8 + return len(dAtA) - i, nil +} + +func (m *PodGroup) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroup) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroup) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupResourceClaim) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupResourceClaim) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupResourceClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResourceClaimTemplateName != nil { + i -= len(*m.ResourceClaimTemplateName) + copy(dAtA[i:], *m.ResourceClaimTemplateName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimTemplateName))) + i-- + dAtA[i] = 0x1a + } + if m.ResourceClaimName != nil { + i -= len(*m.ResourceClaimName) + copy(dAtA[i:], *m.ResourceClaimName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupResourceClaimStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupResourceClaimStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupResourceClaimStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ResourceClaimName != nil { + i -= len(*m.ResourceClaimName) + copy(dAtA[i:], *m.ResourceClaimName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ResourceClaimName))) + i-- + dAtA[i] = 0x12 + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PodGroupSchedulingConstraints) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSchedulingConstraints) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSchedulingConstraints) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Topology) > 0 { + for iNdEx := len(m.Topology) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Topology[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *PodGroupSchedulingPolicy) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSchedulingPolicy) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSchedulingPolicy) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Gang != nil { + { + size, err := m.Gang.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.Basic != nil { + { + size, err := m.Basic.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PodGroupSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x4a + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x40 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x3a + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if len(m.ResourceClaims) > 0 { + for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.WorkloadRef != nil { + { + size, err := m.WorkloadRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.ParentCompositePodGroupName != nil { + i -= len(*m.ParentCompositePodGroupName) + copy(dAtA[i:], *m.ParentCompositePodGroupName) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.ParentCompositePodGroupName))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PodGroupStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ResourceClaimStatuses) > 0 { + for iNdEx := len(m.ResourceClaimStatuses) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaimStatuses[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *PodGroupTemplate) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PodGroupTemplate) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PodGroupTemplate) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x42 + } + if m.Priority != nil { + i = encodeVarintGenerated(dAtA, i, uint64(*m.Priority)) + i-- + dAtA[i] = 0x38 + } + i -= len(m.PriorityClassName) + copy(dAtA[i:], m.PriorityClassName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.PriorityClassName))) + i-- + dAtA[i] = 0x32 + if m.DisruptionMode != nil { + { + size, err := m.DisruptionMode.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if len(m.ResourceClaims) > 0 { + for iNdEx := len(m.ResourceClaims) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ResourceClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if m.SchedulingConstraints != nil { + { + size, err := m.SchedulingConstraints.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + { + size, err := m.SchedulingPolicy.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PriorityClass) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PriorityClass) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PriorityClass) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PreemptionPolicy != nil { + i -= len(*m.PreemptionPolicy) + copy(dAtA[i:], *m.PreemptionPolicy) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PreemptionPolicy))) + i-- + dAtA[i] = 0x2a + } + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x22 + i-- + if m.GlobalDefault { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + i = encodeVarintGenerated(dAtA, i, uint64(m.Value)) + i-- + dAtA[i] = 0x10 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *PriorityClassList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PriorityClassList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PriorityClassList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *SingleCompositeDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SingleCompositeDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SingleCompositeDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *SingleDisruptionMode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SingleDisruptionMode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SingleDisruptionMode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *TopologyConstraint) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TopologyConstraint) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TopologyConstraint) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *TypedLocalObjectReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *TypedLocalObjectReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *TypedLocalObjectReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x1a + i -= len(m.Kind) + copy(dAtA[i:], m.Kind) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind))) + i-- + dAtA[i] = 0x12 + i -= len(m.APIGroup) + copy(dAtA[i:], m.APIGroup) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Workload) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Workload) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Workload) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadReference) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadReference) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadReference) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.TemplateName) + copy(dAtA[i:], m.TemplateName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.TemplateName))) + i-- + dAtA[i] = 0x12 + i -= len(m.WorkloadName) + copy(dAtA[i:], m.WorkloadName) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.WorkloadName))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *WorkloadSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *WorkloadSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WorkloadSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CompositePodGroupTemplates) > 0 { + for iNdEx := len(m.CompositePodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CompositePodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.PodGroupTemplates) > 0 { + for iNdEx := len(m.PodGroupTemplates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PodGroupTemplates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if m.ControllerRef != nil { + { + size, err := m.ControllerRef.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AllCompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *AllDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *BasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *CompositeBasicSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *CompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CompositeGangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + n += 1 + sovGenerated(uint64(m.MinGroupCount)) + return n +} + +func (m *CompositePodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CompositePodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *CompositePodGroupTemplate) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.PodGroupTemplates) > 0 { + for _, e := range m.PodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.CompositePodGroupTemplates) > 0 { + for _, e := range m.CompositePodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *DisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Single != nil { + l = m.Single.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.All != nil { + l = m.All.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *GangSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + n += 1 + sovGenerated(uint64(m.MinCount)) + return n +} + +func (m *PodGroup) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *PodGroupList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupResourceClaim) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.ResourceClaimName != nil { + l = len(*m.ResourceClaimName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.ResourceClaimTemplateName != nil { + l = len(*m.ResourceClaimTemplateName) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupResourceClaimStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if m.ResourceClaimName != nil { + l = len(*m.ResourceClaimName) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupSchedulingConstraints) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Topology) > 0 { + for _, e := range m.Topology { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupSchedulingPolicy) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Basic != nil { + l = m.Basic.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if m.Gang != nil { + l = m.Gang.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ParentCompositePodGroupName != nil { + l = len(*m.ParentCompositePodGroupName) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.WorkloadRef != nil { + l = m.WorkloadRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.ResourceClaims) > 0 { + for _, e := range m.ResourceClaims { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PodGroupStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.ResourceClaimStatuses) > 0 { + for _, e := range m.ResourceClaimStatuses { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *PodGroupTemplate) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + l = m.SchedulingPolicy.Size() + n += 1 + l + sovGenerated(uint64(l)) + if m.SchedulingConstraints != nil { + l = m.SchedulingConstraints.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.ResourceClaims) > 0 { + for _, e := range m.ResourceClaims { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.DisruptionMode != nil { + l = m.DisruptionMode.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.PriorityClassName) + n += 1 + l + sovGenerated(uint64(l)) + if m.Priority != nil { + n += 1 + sovGenerated(uint64(*m.Priority)) + } + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PriorityClass) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + n += 1 + sovGenerated(uint64(m.Value)) + n += 2 + l = len(m.Description) + n += 1 + l + sovGenerated(uint64(l)) + if m.PreemptionPolicy != nil { + l = len(*m.PreemptionPolicy) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (m *PriorityClassList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *SingleCompositeDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *SingleDisruptionMode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *TopologyConstraint) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *TypedLocalObjectReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.APIGroup) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Kind) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *Workload) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *WorkloadList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *WorkloadReference) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.WorkloadName) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.TemplateName) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *WorkloadSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ControllerRef != nil { + l = m.ControllerRef.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + if len(m.PodGroupTemplates) > 0 { + for _, e := range m.PodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if len(m.CompositePodGroupTemplates) > 0 { + for _, e := range m.CompositePodGroupTemplates { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func sovGenerated(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *AllCompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AllCompositeDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *AllDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AllDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *BasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&BasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *CompositeBasicSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeBasicSchedulingPolicy{`, + `}`, + }, "") + return s +} +func (this *CompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeDisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "SingleCompositeDisruptionMode", "SingleCompositeDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "AllCompositeDisruptionMode", "AllCompositeDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *CompositeGangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositeGangSchedulingPolicy{`, + `MinGroupCount:` + fmt.Sprintf("%v", this.MinGroupCount) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&CompositePodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CompositePodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "CompositeBasicSchedulingPolicy", "CompositeBasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "CompositeGangSchedulingPolicy", "CompositeGangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *CompositePodGroupTemplate) String() string { + if this == nil { + return "nil" + } + repeatedStringForPodGroupTemplates := "[]PodGroupTemplate{" + for _, f := range this.PodGroupTemplates { + repeatedStringForPodGroupTemplates += strings.Replace(strings.Replace(f.String(), "PodGroupTemplate", "PodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForPodGroupTemplates += "}" + repeatedStringForCompositePodGroupTemplates := "[]CompositePodGroupTemplate{" + for _, f := range this.CompositePodGroupTemplates { + repeatedStringForCompositePodGroupTemplates += strings.Replace(strings.Replace(f.String(), "CompositePodGroupTemplate", "CompositePodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForCompositePodGroupTemplates += "}" + s := strings.Join([]string{`&CompositePodGroupTemplate{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "CompositePodGroupSchedulingPolicy", "CompositePodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "CompositePodGroupSchedulingConstraints", "CompositePodGroupSchedulingConstraints", 1) + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "CompositeDisruptionMode", "CompositeDisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `PodGroupTemplates:` + repeatedStringForPodGroupTemplates + `,`, + `CompositePodGroupTemplates:` + repeatedStringForCompositePodGroupTemplates + `,`, + `}`, + }, "") + return s +} +func (this *DisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DisruptionMode{`, + `Single:` + strings.Replace(this.Single.String(), "SingleDisruptionMode", "SingleDisruptionMode", 1) + `,`, + `All:` + strings.Replace(this.All.String(), "AllDisruptionMode", "AllDisruptionMode", 1) + `,`, + `}`, + }, "") + return s +} +func (this *GangSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GangSchedulingPolicy{`, + `MinCount:` + fmt.Sprintf("%v", this.MinCount) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroup) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroup{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodGroupSpec", "PodGroupSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodGroupStatus", "PodGroupStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]PodGroup{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PodGroup", "PodGroup", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&PodGroupList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupResourceClaim) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupResourceClaim{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + `ResourceClaimTemplateName:` + valueToStringGenerated(this.ResourceClaimTemplateName) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupResourceClaimStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupResourceClaimStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ResourceClaimName:` + valueToStringGenerated(this.ResourceClaimName) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSchedulingConstraints) String() string { + if this == nil { + return "nil" + } + repeatedStringForTopology := "[]TopologyConstraint{" + for _, f := range this.Topology { + repeatedStringForTopology += strings.Replace(strings.Replace(f.String(), "TopologyConstraint", "TopologyConstraint", 1), `&`, ``, 1) + "," + } + repeatedStringForTopology += "}" + s := strings.Join([]string{`&PodGroupSchedulingConstraints{`, + `Topology:` + repeatedStringForTopology + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSchedulingPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodGroupSchedulingPolicy{`, + `Basic:` + strings.Replace(this.Basic.String(), "BasicSchedulingPolicy", "BasicSchedulingPolicy", 1) + `,`, + `Gang:` + strings.Replace(this.Gang.String(), "GangSchedulingPolicy", "GangSchedulingPolicy", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupSpec) String() string { + if this == nil { + return "nil" + } + repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" + for _, f := range this.ResourceClaims { + repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaims += "}" + s := strings.Join([]string{`&PodGroupSpec{`, + `ParentCompositePodGroupName:` + valueToStringGenerated(this.ParentCompositePodGroupName) + `,`, + `WorkloadRef:` + strings.Replace(this.WorkloadRef.String(), "WorkloadReference", "WorkloadReference", 1) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, + `ResourceClaims:` + repeatedStringForResourceClaims + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "DisruptionMode", "DisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + repeatedStringForResourceClaimStatuses := "[]PodGroupResourceClaimStatus{" + for _, f := range this.ResourceClaimStatuses { + repeatedStringForResourceClaimStatuses += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaimStatus", "PodGroupResourceClaimStatus", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaimStatuses += "}" + s := strings.Join([]string{`&PodGroupStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `ResourceClaimStatuses:` + repeatedStringForResourceClaimStatuses + `,`, + `}`, + }, "") + return s +} +func (this *PodGroupTemplate) String() string { + if this == nil { + return "nil" + } + repeatedStringForResourceClaims := "[]PodGroupResourceClaim{" + for _, f := range this.ResourceClaims { + repeatedStringForResourceClaims += strings.Replace(strings.Replace(f.String(), "PodGroupResourceClaim", "PodGroupResourceClaim", 1), `&`, ``, 1) + "," + } + repeatedStringForResourceClaims += "}" + s := strings.Join([]string{`&PodGroupTemplate{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `SchedulingPolicy:` + strings.Replace(strings.Replace(this.SchedulingPolicy.String(), "PodGroupSchedulingPolicy", "PodGroupSchedulingPolicy", 1), `&`, ``, 1) + `,`, + `SchedulingConstraints:` + strings.Replace(this.SchedulingConstraints.String(), "PodGroupSchedulingConstraints", "PodGroupSchedulingConstraints", 1) + `,`, + `ResourceClaims:` + repeatedStringForResourceClaims + `,`, + `DisruptionMode:` + strings.Replace(this.DisruptionMode.String(), "DisruptionMode", "DisruptionMode", 1) + `,`, + `PriorityClassName:` + fmt.Sprintf("%v", this.PriorityClassName) + `,`, + `Priority:` + valueToStringGenerated(this.Priority) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *PriorityClass) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PriorityClass{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `GlobalDefault:` + fmt.Sprintf("%v", this.GlobalDefault) + `,`, + `Description:` + fmt.Sprintf("%v", this.Description) + `,`, + `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *PriorityClassList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]PriorityClass{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PriorityClass", "PriorityClass", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&PriorityClassList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *SingleCompositeDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SingleCompositeDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *SingleDisruptionMode) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SingleDisruptionMode{`, + `}`, + }, "") + return s +} +func (this *TopologyConstraint) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TopologyConstraint{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `}`, + }, "") + return s +} +func (this *TypedLocalObjectReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TypedLocalObjectReference{`, + `APIGroup:` + fmt.Sprintf("%v", this.APIGroup) + `,`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `}`, + }, "") + return s +} +func (this *Workload) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Workload{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "WorkloadSpec", "WorkloadSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]Workload{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "Workload", "Workload", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&WorkloadList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WorkloadReference{`, + `WorkloadName:` + fmt.Sprintf("%v", this.WorkloadName) + `,`, + `TemplateName:` + fmt.Sprintf("%v", this.TemplateName) + `,`, + `}`, + }, "") + return s +} +func (this *WorkloadSpec) String() string { + if this == nil { + return "nil" + } + repeatedStringForPodGroupTemplates := "[]PodGroupTemplate{" + for _, f := range this.PodGroupTemplates { + repeatedStringForPodGroupTemplates += strings.Replace(strings.Replace(f.String(), "PodGroupTemplate", "PodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForPodGroupTemplates += "}" + repeatedStringForCompositePodGroupTemplates := "[]CompositePodGroupTemplate{" + for _, f := range this.CompositePodGroupTemplates { + repeatedStringForCompositePodGroupTemplates += strings.Replace(strings.Replace(f.String(), "CompositePodGroupTemplate", "CompositePodGroupTemplate", 1), `&`, ``, 1) + "," + } + repeatedStringForCompositePodGroupTemplates += "}" + s := strings.Join([]string{`&WorkloadSpec{`, + `ControllerRef:` + strings.Replace(this.ControllerRef.String(), "TypedLocalObjectReference", "TypedLocalObjectReference", 1) + `,`, + `PodGroupTemplates:` + repeatedStringForPodGroupTemplates + `,`, + `CompositePodGroupTemplates:` + repeatedStringForCompositePodGroupTemplates + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { return "nil" } - s := strings.Join([]string{`&PriorityClass{`, - `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, - `Value:` + fmt.Sprintf("%v", this.Value) + `,`, - `GlobalDefault:` + fmt.Sprintf("%v", this.GlobalDefault) + `,`, - `Description:` + fmt.Sprintf("%v", this.Description) + `,`, - `PreemptionPolicy:` + valueToStringGenerated(this.PreemptionPolicy) + `,`, - `}`, - }, "") - return s + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *AllCompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllCompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllCompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AllDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AllDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AllDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *BasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: BasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: BasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeBasicSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeBasicSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeBasicSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &SingleCompositeDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &AllCompositeDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositeGangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositeGangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositeGangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinGroupCount", wireType) + } + m.MinGroupCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinGroupCount |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &CompositeBasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &CompositeGangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CompositePodGroupTemplate) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CompositePodGroupTemplate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CompositePodGroupTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &CompositePodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &CompositeDisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PodGroupTemplates = append(m.PodGroupTemplates, PodGroupTemplate{}) + if err := m.PodGroupTemplates[len(m.PodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompositePodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompositePodGroupTemplates = append(m.CompositePodGroupTemplates, CompositePodGroupTemplate{}) + if err := m.CompositePodGroupTemplates[len(m.CompositePodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Single", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Single == nil { + m.Single = &SingleDisruptionMode{} + } + if err := m.Single.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field All", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.All == nil { + m.All = &AllDisruptionMode{} + } + if err := m.All.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *GangSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GangSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GangSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinCount", wireType) + } + m.MinCount = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinCount |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroup) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroup: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroup: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, PodGroup{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupResourceClaim) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupResourceClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupResourceClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimName = &s + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimTemplateName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimTemplateName = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupResourceClaimStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupResourceClaimStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupResourceClaimStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ResourceClaimName = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSchedulingConstraints) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSchedulingConstraints: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSchedulingConstraints: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Topology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Topology = append(m.Topology, TopologyConstraint{}) + if err := m.Topology[len(m.Topology)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSchedulingPolicy) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSchedulingPolicy: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSchedulingPolicy: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Basic", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Basic == nil { + m.Basic = &BasicSchedulingPolicy{} + } + if err := m.Basic.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Gang", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Gang == nil { + m.Gang = &GangSchedulingPolicy{} + } + if err := m.Gang.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ParentCompositePodGroupName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := string(dAtA[iNdEx:postIndex]) + m.ParentCompositePodGroupName = &s + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WorkloadRef", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.WorkloadRef == nil { + m.WorkloadRef = &WorkloadReference{} + } + if err := m.WorkloadRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &PodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) + if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &DisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaimStatuses", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaimStatuses = append(m.ResourceClaimStatuses, PodGroupResourceClaimStatus{}) + if err := m.ResourceClaimStatuses[len(m.ResourceClaimStatuses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PodGroupTemplate) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodGroupTemplate: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodGroupTemplate: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingPolicy", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SchedulingPolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SchedulingConstraints", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.SchedulingConstraints == nil { + m.SchedulingConstraints = &PodGroupSchedulingConstraints{} + } + if err := m.SchedulingConstraints.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceClaims", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceClaims = append(m.ResourceClaims, PodGroupResourceClaim{}) + if err := m.ResourceClaims[len(m.ResourceClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DisruptionMode", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.DisruptionMode == nil { + m.DisruptionMode = &DisruptionMode{} + } + if err := m.DisruptionMode.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriorityClassName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PriorityClassName = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Priority", wireType) + } + var v int32 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Priority = &v + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PriorityClass) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PriorityClass: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PriorityClass: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + m.Value = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Value |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field GlobalDefault", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.GlobalDefault = bool(v != 0) + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := k8s_io_api_core_v1.PreemptionPolicy(dAtA[iNdEx:postIndex]) + m.PreemptionPolicy = &s + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PriorityClassList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PriorityClassList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PriorityClassList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, PriorityClass{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SingleCompositeDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SingleCompositeDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SingleCompositeDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil } -func (this *PriorityClassList) String() string { - if this == nil { - return "nil" +func (m *SingleDisruptionMode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SingleDisruptionMode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SingleDisruptionMode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } } - repeatedStringForItems := "[]PriorityClass{" - for _, f := range this.Items { - repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "PriorityClass", "PriorityClass", 1), `&`, ``, 1) + "," + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TopologyConstraint) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TopologyConstraint: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TopologyConstraint: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *TypedLocalObjectReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: TypedLocalObjectReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: TypedLocalObjectReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field APIGroup", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.APIGroup = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Kind = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } } - repeatedStringForItems += "}" - s := strings.Join([]string{`&PriorityClassList{`, - `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, - `Items:` + repeatedStringForItems + `,`, - `}`, - }, "") - return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" + + if iNdEx > l { + return io.ErrUnexpectedEOF } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) + return nil } -func (m *PriorityClass) Unmarshal(dAtA []byte) error { +func (m *Workload) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -252,10 +5660,10 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PriorityClass: wiretype end group for non-group") + return fmt.Errorf("proto: Workload: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PriorityClass: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: Workload: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -292,10 +5700,10 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) } - m.Value = 0 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -305,16 +5713,80 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Value |= int32(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field GlobalDefault", wireType) + if msglen < 0 { + return ErrInvalidLengthGenerated } - var v int + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -324,15 +5796,112 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - v |= int(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - m.GlobalDefault = bool(v != 0) - case 4: + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, Workload{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WorkloadReference) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WorkloadReference: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WorkloadReference: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WorkloadName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -360,11 +5929,11 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Description = string(dAtA[iNdEx:postIndex]) + m.WorkloadName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreemptionPolicy", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TemplateName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -392,8 +5961,7 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - s := k8s_io_api_core_v1.PreemptionPolicy(dAtA[iNdEx:postIndex]) - m.PreemptionPolicy = &s + m.TemplateName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -416,7 +5984,7 @@ func (m *PriorityClass) Unmarshal(dAtA []byte) error { } return nil } -func (m *PriorityClassList) Unmarshal(dAtA []byte) error { +func (m *WorkloadSpec) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -439,15 +6007,15 @@ func (m *PriorityClassList) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: PriorityClassList: wiretype end group for non-group") + return fmt.Errorf("proto: WorkloadSpec: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: PriorityClassList: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: WorkloadSpec: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ControllerRef", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -474,13 +6042,16 @@ func (m *PriorityClassList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if m.ControllerRef == nil { + m.ControllerRef = &TypedLocalObjectReference{} + } + if err := m.ControllerRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PodGroupTemplates", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -507,8 +6078,42 @@ func (m *PriorityClassList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Items = append(m.Items, PriorityClass{}) - if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.PodGroupTemplates = append(m.PodGroupTemplates, PodGroupTemplate{}) + if err := m.PodGroupTemplates[len(m.PodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CompositePodGroupTemplates", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CompositePodGroupTemplates = append(m.CompositePodGroupTemplates, CompositePodGroupTemplate{}) + if err := m.CompositePodGroupTemplates[len(m.CompositePodGroupTemplates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.proto index 0e701be54..656841e41 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/generated.proto @@ -29,11 +29,651 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; // Package-wide variables from generator "generated". option go_package = "k8s.io/api/scheduling/v1beta1"; +// AllCompositeDisruptionMode means that children of a CompositePodGroup can only be +// disrupted or preempted together. +message AllCompositeDisruptionMode { +} + +// AllDisruptionMode specifies that children can only be disrupted together. +message AllDisruptionMode { +} + +// BasicSchedulingPolicy indicates that standard Kubernetes +// scheduling behavior should be used. +message BasicSchedulingPolicy { +} + +// CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled independently. +message CompositeBasicSchedulingPolicy { +} + +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +// +// +union +message CompositeDisruptionMode { + // single specifies that children groups can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional SingleCompositeDisruptionMode single = 1; + + // all specifies that all children groups can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional AllCompositeDisruptionMode all = 2; +} + +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +message CompositeGangSchedulingPolicy { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + // + // +required + // +k8s:required + // +k8s:minimum=1 + optional int32 minGroupCount = 1; +} + +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +message CompositePodGroupSchedulingConstraints { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +// +// +union +message CompositePodGroupSchedulingPolicy { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:unionMember + optional CompositeBasicSchedulingPolicy basic = 1; + + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional CompositeGangSchedulingPolicy gang = 2; +} + +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +message CompositePodGroupTemplate { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // schedulingPolicy defines the scheduling policy for this template. + // + // +required + optional CompositePodGroupSchedulingPolicy schedulingPolicy = 2; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositePodGroupSchedulingConstraints schedulingConstraints = 3; + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional CompositeDisruptionMode disruptionMode = 4; + + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + optional string priorityClassName = 5; + + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + optional int32 priority = 6; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 7; + + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated PodGroupTemplate podGroupTemplates = 8; + + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated CompositePodGroupTemplate compositePodGroupTemplates = 9; +} + +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +// +// +union +message DisruptionMode { + // single specifies that children can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional SingleDisruptionMode single = 1; + + // all specifies that all children can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + optional AllDisruptionMode all = 2; +} + +// GangSchedulingPolicy defines the parameters for gang scheduling. +message GangSchedulingPolicy { + // minCount is the minimum number of pods that must be schedulable or scheduled + // at the same time for the scheduler to admit the entire group. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. + // + // +required + // +k8s:required + // +k8s:minimum=1 + optional int32 minCount = 1; +} + +// PodGroup represents a runtime instance of pods grouped together. +// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from +// Workload.podGroupTemplates. +// PodGroup API enablement is toggled by the GenericWorkload feature gate. +message PodGroup { + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the desired state of the PodGroup. + // + // +required + optional PodGroupSpec spec = 2; + + // status represents the current observed state of the PodGroup. + // + // +optional + optional PodGroupStatus status = 3; +} + +// PodGroupList contains a list of PodGroup resources. +message PodGroupList { + // Standard list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of PodGroups. + repeated PodGroup items = 2; +} + +// PodGroupResourceClaim references exactly one ResourceClaim, either directly +// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim +// for the PodGroup. +// +// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. +// Pods that need access to the ResourceClaim define a matching reference in its +// own Spec.ResourceClaims. The Pod's claim must match all fields of the +// PodGroup's claim exactly. +message PodGroupResourceClaim { + // name uniquely identifies this resource claim inside the PodGroup. + // This must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace as this PodGroup. The ResourceClaim will be reserved for the + // PodGroup instead of its individual pods. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimName = 2; + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace as this PodGroup. + // + // The template will be used to create a new ResourceClaim, which will + // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim + // will also be deleted. The PodGroup name and resource name, along with a + // generated component, will be used to form a unique name for the + // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. + // + // This field is immutable and no changes will be made to the + // corresponding ResourceClaim by the control plane after creating the + // ResourceClaim. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + optional string resourceClaimTemplateName = 3; +} + +// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each +// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the +// generated name for the corresponding ResourceClaim. +message PodGroupResourceClaimStatus { + // name uniquely identifies this resource claim inside the PodGroup. This + // must match the name of an entry in podgroup.spec.resourceClaims, which + // implies that the string must be a DNS_LABEL. + // + // +required + optional string name = 1; + + // resourceClaimName is the name of the ResourceClaim that was generated for + // the PodGroup in the namespace of the PodGroup. If this is unset, then + // generating a ResourceClaim was not necessary. The + // podgroup.spec.resourceClaims entry can be ignored in this case. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + optional string resourceClaimName = 2; +} + +// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. +message PodGroupSchedulingConstraints { + // topology defines the topology constraints for the pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + repeated TopologyConstraint topology = 1; +} + +// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. +// +// +union +message PodGroupSchedulingPolicy { + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:immutable + optional BasicSchedulingPolicy basic = 1; + + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + optional GangSchedulingPolicy gang = 2; +} + +// PodGroupSpec defines the desired state of a PodGroup. +message PodGroupSpec { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + // + // +featureGate=CompositePodGroup + // +optional + // +k8s:ifDisabled(CompositePodGroup)=+k8s:forbidden + // +k8s:ifEnabled(CompositePodGroup)=+k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("workloadRef") + optional string parentCompositePodGroupName = 1; + + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional WorkloadReference workloadRef = 2; + + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // + // +required + optional PodGroupSchedulingPolicy schedulingPolicy = 3; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // This field is immutable. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable + optional PodGroupSchedulingConstraints schedulingConstraints = 4; + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + // +featureGate=DRAWorkloadResourceClaims + repeated PodGroupResourceClaim resourceClaims = 5; + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + optional DisruptionMode disruptionMode = 6; + + // priorityClassName defines the priority that should be considered when scheduling this pod group. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + optional string priorityClassName = 7; + + // priority is the value of priority of this pod group. Various system components + // use this field to find the priority of the pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + optional int32 priority = 8; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 9; +} + +// PodGroupStatus represents information about the status of a pod group. +message PodGroupStatus { + // conditions represent the latest observations of the PodGroup's state. + // + // Known condition types: + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the PodGroupInitiallyScheduled condition: + // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, + // affinity/anti-affinity rules, or insufficient capacity for the gang. + // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error + // that happened during scheduling, for example due to nodeAffinity parsing errors. + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for + // higher-priority PodGroups or Pods. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // resourceClaimStatuses is status of resource claims. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + repeated PodGroupResourceClaimStatus resourceClaimStatuses = 2; +} + +// PodGroupTemplate represents a template for a set of pods with a scheduling policy. +message PodGroupTemplate { + // name is a unique identifier for the PodGroupTemplate within the Workload. + // It must be a DNS label. This field is immutable. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string name = 1; + + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. + // + // +required + optional PodGroupSchedulingPolicy schedulingPolicy = 2; + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:immutable + optional PodGroupSchedulingConstraints schedulingConstraints = 3; + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + // +k8s:immutable + repeated PodGroupResourceClaim resourceClaims = 4; + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional DisruptionMode disruptionMode = 5; + + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + optional string priorityClassName = 6; + + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + optional int32 priority = 7; + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + optional string preemptionPolicy = 8; +} + // DEPRECATED - This group version of PriorityClass is deprecated by scheduling.k8s.io/v1/PriorityClass. // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. message PriorityClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; @@ -74,3 +714,155 @@ message PriorityClassList { repeated PriorityClass items = 2; } +// SingleCompositeDisruptionMode means that individual children of a CompositePodGroup +// can be disrupted or preempted independently. +message SingleCompositeDisruptionMode { +} + +// SingleDisruptionMode specifies that children can be disrupted independently. +message SingleDisruptionMode { +} + +// TopologyConstraint defines a topology constraint for a PodGroup. +message TopologyConstraint { + // key specifies the key of the node label representing the topology domain. + // All pods within the PodGroup must be colocated within the same domain instance. + // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. + // Examples: "topology.kubernetes.io/rack" + // + // +required + // +k8s:required + // +k8s:format=k8s-label-key + optional string key = 1; +} + +// TypedLocalObjectReference allows to reference typed object inside the same namespace. +message TypedLocalObjectReference { + // apiGroup is the group for the resource being referenced. + // If apiGroup is empty, the specified Kind must be in the core API group. + // For any other third-party types, setting apiGroup is required. + // It must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + optional string apiGroup = 1; + + // kind is the type of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + optional string kind = 2; + + // name is the name of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + optional string name = 3; +} + +// Workload allows for expressing scheduling constraints that should be used +// when managing the lifecycle of workloads from the scheduling perspective, +// including scheduling, preemption, eviction and other phases. +// Workload API enablement is toggled by the GenericWorkload feature gate. +message Workload { + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // spec defines the desired behavior of a Workload. + // + // +required + optional WorkloadSpec spec = 2; +} + +// WorkloadList contains a list of Workload resources. +message WorkloadList { + // metadata is the standard list metadata. + // + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // items is the list of Workloads. + repeated Workload items = 2; +} + +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +message WorkloadReference { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-long-name + optional string workloadName = 1; + + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + optional string templateName = 2; +} + +// WorkloadSpec defines the desired state of a Workload. +message WorkloadSpec { + // controllerRef is an optional reference to the controlling object, such as a + // Deployment or Job. This field is intended for use by tools like CLIs + // to provide a link back to the original workload definition. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + optional TypedLocalObjectReference controllerRef = 1; + + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated PodGroupTemplate podGroupTemplates = 2; + + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + // + // +featureGate=CompositePodGroup + // +optional + // +listType=map + // +listMapKey=name + // +k8s:ifDisabled("CompositePodGroup")=+k8s:forbidden + // +k8s:ifEnabled("CompositePodGroup")=+k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + repeated CompositePodGroupTemplate compositePodGroupTemplates = 3; +} + diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/register.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/register.go index fb26557bb..c2e75d907 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/register.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/register.go @@ -46,6 +46,10 @@ func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &PriorityClass{}, &PriorityClassList{}, + &Workload{}, + &WorkloadList{}, + &PodGroup{}, + &PodGroupList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/types.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/types.go index 8a7a2058f..57eeac948 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/types.go @@ -33,8 +33,8 @@ import ( // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. type PriorityClass struct { - metav1.TypeMeta `json:",inline"` - // Standard object's metadata. + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -72,7 +72,7 @@ type PriorityClass struct { // PriorityClassList is a collection of priority classes. type PriorityClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -81,3 +81,869 @@ type PriorityClassList struct { // items is the list of PriorityClasses Items []PriorityClass `json:"items" protobuf:"bytes,2,rep,name=items"` } + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// Workload allows for expressing scheduling constraints that should be used +// when managing the lifecycle of workloads from the scheduling perspective, +// including scheduling, preemption, eviction and other phases. +// Workload API enablement is toggled by the GenericWorkload feature gate. +type Workload struct { + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the desired behavior of a Workload. + // + // +required + Spec WorkloadSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// WorkloadList contains a list of Workload resources. +type WorkloadList struct { + metav1.TypeMeta `json:""` + // metadata is the standard list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // items is the list of Workloads. + Items []Workload `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +const ( + // WorkloadMaxPodGroupTemplates is the maximum number of pod group templates per Workload. + WorkloadMaxPodGroupTemplates = 8 + // WorkloadMaxTreeDepth is the maximum allowed depth for a tree of (composite) pod group templates in a Workload. + WorkloadMaxTreeDepth = 4 +) + +// WorkloadSpec defines the desired state of a Workload. +type WorkloadSpec struct { + // controllerRef is an optional reference to the controlling object, such as a + // Deployment or Job. This field is intended for use by tools like CLIs + // to provide a link back to the original workload definition. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + ControllerRef *TypedLocalObjectReference `json:"controllerRef,omitempty" protobuf:"bytes,1,opt,name=controllerRef"` + + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + PodGroupTemplates []PodGroupTemplate `json:"podGroupTemplates" protobuf:"bytes,2,rep,name=podGroupTemplates"` + + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + // + // +featureGate=CompositePodGroup + // +optional + // +listType=map + // +listMapKey=name + // +k8s:ifDisabled("CompositePodGroup")=+k8s:forbidden + // +k8s:ifEnabled("CompositePodGroup")=+k8s:optional + // +k8s:unionMember + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + CompositePodGroupTemplates []CompositePodGroupTemplate `json:"compositePodGroupTemplates,omitempty" protobuf:"bytes,3,rep,name=compositePodGroupTemplates"` +} + +// TypedLocalObjectReference allows to reference typed object inside the same namespace. +type TypedLocalObjectReference struct { + // apiGroup is the group for the resource being referenced. + // If apiGroup is empty, the specified Kind must be in the core API group. + // For any other third-party types, setting apiGroup is required. + // It must be a DNS subdomain. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + APIGroup string `json:"apiGroup,omitempty" protobuf:"bytes,1,opt,name=apiGroup"` + // kind is the type of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + Kind string `json:"kind" protobuf:"bytes,2,opt,name=kind"` + // name is the name of resource being referenced. + // It must be a path segment name. + // + // +required + // +k8s:required + // +k8s:format=k8s-path-segment-name + Name string `json:"name" protobuf:"bytes,3,opt,name=name"` +} + +// MaxPodGroupResourceClaims is the maximum number of resource claims for a +// PodGroup or a Workload's PodGroupTemplate. +const MaxPodGroupResourceClaims = 4 + +// PodGroupTemplate represents a template for a set of pods with a scheduling policy. +type PodGroupTemplate struct { + // name is a unique identifier for the PodGroupTemplate within the Workload. + // It must be a DNS label. This field is immutable. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. + // + // +required + SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:immutable + SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints" protobuf:"bytes,3,opt,name=schedulingConstraints"` + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + // +k8s:immutable + ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,4,rep,name=resourceClaims"` + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,5,opt,name=disruptionMode"` + + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,6,opt,name=priorityClassName"` + + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + Priority *int32 `json:"priority,omitempty" protobuf:"varint,7,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,8,opt,name=preemptionPolicy"` +} + +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +type CompositePodGroupTemplate struct { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // schedulingPolicy defines the scheduling policy for this template. + // + // +required + SchedulingPolicy CompositePodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,2,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + SchedulingConstraints *CompositePodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,3,opt,name=schedulingConstraints"` + + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *CompositeDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,4,opt,name=disruptionMode"` + + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + // +k8s:immutable + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,5,opt,name=priorityClassName"` + + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + // +k8s:immutable + Priority *int32 `json:"priority,omitempty" protobuf:"varint,6,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,7,opt,name=preemptionPolicy"` + + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + PodGroupTemplates []PodGroupTemplate `json:"podGroupTemplates,omitempty" protobuf:"bytes,8,rep,name=podGroupTemplates"` + + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + // + // +optional + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=8 + // +k8s:update=NoAddItem + // +k8s:update=NoRemoveItem + CompositePodGroupTemplates []CompositePodGroupTemplate `json:"compositePodGroupTemplates,omitempty" protobuf:"bytes,9,rep,name=compositePodGroupTemplates"` +} + +// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. +// +// +union +type PodGroupSchedulingPolicy struct { + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:immutable + Basic *BasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + Gang *GangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// BasicSchedulingPolicy indicates that standard Kubernetes +// scheduling behavior should be used. +type BasicSchedulingPolicy struct { + // This is intentionally empty. Its presence indicates that the basic + // scheduling policy should be applied. In the future, new fields may appear, + // describing such constraints on a pod group level without "all or nothing" + // (gang) scheduling. +} + +// GangSchedulingPolicy defines the parameters for gang scheduling. +type GangSchedulingPolicy struct { + // minCount is the minimum number of pods that must be schedulable or scheduled + // at the same time for the scheduler to admit the entire group. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. + // + // +required + // +k8s:required + // +k8s:minimum=1 + MinCount int32 `json:"minCount" protobuf:"varint,1,opt,name=minCount"` +} + +// PodGroupResourceClaim references exactly one ResourceClaim, either directly +// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim +// for the PodGroup. +// +// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. +// Pods that need access to the ResourceClaim define a matching reference in its +// own Spec.ResourceClaims. The Pod's claim must match all fields of the +// PodGroup's claim exactly. +type PodGroupResourceClaim struct { + // name uniquely identifies this resource claim inside the PodGroup. + // This must be a DNS_LABEL. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace as this PodGroup. The ResourceClaim will be reserved for the + // PodGroup instead of its individual pods. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` + + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace as this PodGroup. + // + // The template will be used to create a new ResourceClaim, which will + // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim + // will also be deleted. The PodGroup name and resource name, along with a + // generated component, will be used to form a unique name for the + // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. + // + // This field is immutable and no changes will be made to the + // corresponding ResourceClaim by the control plane after creating the + // ResourceClaim. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:format=k8s-long-name + ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty" protobuf:"bytes,3,opt,name=resourceClaimTemplateName"` +} + +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +// +// +union +type DisruptionMode struct { + // single specifies that children can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *SingleDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all children can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *AllDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// SingleDisruptionMode specifies that children can be disrupted independently. +type SingleDisruptionMode struct { + // Intentionally empty now. +} + +// AllDisruptionMode specifies that children can only be disrupted together. +type AllDisruptionMode struct { + // Intentionally empty now. +} + +// PreemptionPolicy describes a policy for if/when to preempt a pod. +// +enum +// +k8s:enum +type PreemptionPolicy string + +const ( + // PreemptLowerPriority means that pod can preempt other pods with lower priority. + PreemptLowerPriority PreemptionPolicy = "PreemptLowerPriority" + // PreemptNever means that pod never preempts other pods with lower priority. + PreemptNever PreemptionPolicy = "Never" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 +// +k8s:supportsSubresource="/status" + +// PodGroup represents a runtime instance of pods grouped together. +// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from +// Workload.podGroupTemplates. +// PodGroup API enablement is toggled by the GenericWorkload feature gate. +type PodGroup struct { + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // spec defines the desired state of the PodGroup. + // + // +required + Spec PodGroupSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status represents the current observed state of the PodGroup. + // + // +optional + Status PodGroupStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// PodGroupList contains a list of PodGroup resources. +type PodGroupList struct { + metav1.TypeMeta `json:""` + // Standard list metadata. + // + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of PodGroups. + Items []PodGroup `json:"items" protobuf:"bytes,2,rep,name=items"` +} + +// PodGroupSpec defines the desired state of a PodGroup. +type PodGroupSpec struct { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + // + // +featureGate=CompositePodGroup + // +optional + // +k8s:ifDisabled(CompositePodGroup)=+k8s:forbidden + // +k8s:ifEnabled(CompositePodGroup)=+k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + // +k8s:alpha(since: "1.37")=+k8s:dependentRequired("workloadRef") + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty" protobuf:"bytes,1,opt,name=parentCompositePodGroupName"` + + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + WorkloadRef *WorkloadReference `json:"workloadRef,omitempty" protobuf:"bytes,2,opt,name=workloadRef"` + + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // + // +required + SchedulingPolicy PodGroupSchedulingPolicy `json:"schedulingPolicy" protobuf:"bytes,3,opt,name=schedulingPolicy"` + + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // This field is immutable. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // + // +featureGate=TopologyAwareWorkloadScheduling + // +optional + // +k8s:ifDisabled(TopologyAwareWorkloadScheduling)=+k8s:forbidden + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:optional + // +k8s:ifEnabled(TopologyAwareWorkloadScheduling)=+k8s:immutable + SchedulingConstraints *PodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,4,opt,name=schedulingConstraints"` + + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + // + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +k8s:immutable + // +featureGate=DRAWorkloadResourceClaims + ResourceClaims []PodGroupResourceClaim `json:"resourceClaims,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,5,rep,name=resourceClaims"` + + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + // + // +default={"single": {}} + // +optional + // +k8s:optional + // +k8s:immutable + DisruptionMode *DisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,6,opt,name=disruptionMode"` + + // priorityClassName defines the priority that should be considered when scheduling this pod group. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the pod group's priority will be zero). + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:format=k8s-long-name + PriorityClassName string `json:"priorityClassName,omitempty" protobuf:"bytes,7,opt,name=priorityClassName"` + + // priority is the value of priority of this pod group. Various system components + // use this field to find the priority of the pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:maximum=1000000000 # HighestUserDefinablePriority + Priority *int32 `json:"priority,omitempty" protobuf:"varint,8,opt,name=priority"` + + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + // + // +featureGate=PodGroupPreemptionPolicy + // +optional + // +k8s:immutable + // +k8s:ifDisabled("PodGroupPreemptionPolicy")=+k8s:forbidden + // +k8s:ifEnabled("PodGroupPreemptionPolicy")=+k8s:optional + PreemptionPolicy *PreemptionPolicy `json:"preemptionPolicy,omitempty" protobuf:"bytes,9,opt,name=preemptionPolicy"` +} + +// PodGroupStatus represents information about the status of a pod group. +type PodGroupStatus struct { + // conditions represent the latest observations of the PodGroup's state. + // + // Known condition types: + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the PodGroupInitiallyScheduled condition: + // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, + // affinity/anti-affinity rules, or insufficient capacity for the gang. + // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error + // that happened during scheduling, for example due to nodeAffinity parsing errors. + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for + // higher-priority PodGroups or Pods. + // + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + + // resourceClaimStatuses is status of resource claims. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge,retainKeys + // +listType=map + // +listMapKey=name + // +k8s:optional + // +k8s:listType=map + // +k8s:listMapKey=name + // +k8s:maxItems=4 + // +featureGate=DRAWorkloadResourceClaims + ResourceClaimStatuses []PodGroupResourceClaimStatus `json:"resourceClaimStatuses,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name" protobuf:"bytes,2,rep,name=resourceClaimStatuses"` +} + +// Well-known condition types for PodGroups. +const ( + // PodGroupInitiallyScheduled represents status of the scheduling process for this PodGroup till first success. + PodGroupInitiallyScheduled string = "PodGroupInitiallyScheduled" + // DisruptionTarget indicates the PodGroup is about to be terminated due to disruption + // such as preemption. + DisruptionTarget string = "DisruptionTarget" +) + +// Well-known condition reasons for PodGroups. +const ( + // Unschedulable reason in the PodGroupInitiallyScheduled condition indicates that the PodGroup cannot be scheduled + // due to resource constraints, affinity/anti-affinity rules, or insufficient capacity for the PodGroup. + PodGroupReasonUnschedulable string = "Unschedulable" + // SchedulerError reason in the PodGroupInitiallyScheduled condition means that some internal error happens + // during scheduling, for example due to nodeAffinity parsing errors. + PodGroupReasonSchedulerError string = "SchedulerError" + // PreemptionByScheduler reason in the DisruptionTarget condition indicates the PodGroup was preempted + // to make room for higher-priority PodGroups or Pods. + PodGroupReasonPreemptionByScheduler string = "PreemptionByScheduler" +) + +// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each +// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the +// generated name for the corresponding ResourceClaim. +type PodGroupResourceClaimStatus struct { + // name uniquely identifies this resource claim inside the PodGroup. This + // must match the name of an entry in podgroup.spec.resourceClaims, which + // implies that the string must be a DNS_LABEL. + // + // +required + Name string `json:"name" protobuf:"bytes,1,name=name"` + + // resourceClaimName is the name of the ResourceClaim that was generated for + // the PodGroup in the namespace of the PodGroup. If this is unset, then + // generating a ResourceClaim was not necessary. The + // podgroup.spec.resourceClaims entry can be ignored in this case. + // + // +optional + // +k8s:optional + // +k8s:format=k8s-long-name + ResourceClaimName *string `json:"resourceClaimName,omitempty" protobuf:"bytes,2,opt,name=resourceClaimName"` +} + +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +type WorkloadReference struct { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-long-name + WorkloadName string `json:"workloadName" protobuf:"bytes,1,opt,name=workloadName"` + + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + // + // +required + // +k8s:required + // +k8s:format=k8s-short-name + TemplateName string `json:"templateName" protobuf:"bytes,2,opt,name=templateName"` +} + +// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. +type PodGroupSchedulingConstraints struct { + // topology defines the topology constraints for the pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} + +// TopologyConstraint defines a topology constraint for a PodGroup. +type TopologyConstraint struct { + // key specifies the key of the node label representing the topology domain. + // All pods within the PodGroup must be colocated within the same domain instance. + // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. + // Examples: "topology.kubernetes.io/rack" + // + // +required + // +k8s:required + // +k8s:format=k8s-label-key + Key string `json:"key" protobuf:"bytes,1,opt,name=key"` +} + +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +// +// +union +type CompositePodGroupSchedulingPolicy struct { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + // + // +optional + // +k8s:optional + // +k8s:immutable + // +k8s:unionMember + Basic *CompositeBasicSchedulingPolicy `json:"basic,omitempty" protobuf:"bytes,1,opt,name=basic"` + + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + // + // +optional + // +k8s:optional + // +k8s:unionMember + // +k8s:update=NoSet + // +k8s:update=NoUnset + Gang *CompositeGangSchedulingPolicy `json:"gang,omitempty" protobuf:"bytes,2,opt,name=gang"` +} + +// CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled independently. +type CompositeBasicSchedulingPolicy struct { + // This is intentionally empty. Its presence indicates that the basic group + // scheduling policy should be applied. In the future, new fields may appear, + // describing such constraints on a composite pod group level without "all or + // nothing" (gang) scheduling. +} + +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +type CompositeGangSchedulingPolicy struct { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + // + // +required + // +k8s:required + // +k8s:minimum=1 + MinGroupCount int32 `json:"minGroupCount" protobuf:"varint,1,req,name=minGroupCount"` +} + +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +// +// +union +type CompositeDisruptionMode struct { + // single specifies that children groups can be disrupted independently from each other. + // + // +optional + // +k8s:optional + // +k8s:unionMember + Single *SingleCompositeDisruptionMode `json:"single,omitempty" protobuf:"bytes,1,opt,name=single"` + + // all specifies that all children groups can only be disrupted together. + // + // +optional + // +k8s:optional + // +k8s:unionMember + All *AllCompositeDisruptionMode `json:"all,omitempty" protobuf:"bytes,2,opt,name=all"` +} + +// SingleCompositeDisruptionMode means that individual children of a CompositePodGroup +// can be disrupted or preempted independently. +type SingleCompositeDisruptionMode struct { + // This is intentionally empty. +} + +// AllCompositeDisruptionMode means that children of a CompositePodGroup can only be +// disrupted or preempted together. +type AllCompositeDisruptionMode struct { + // This is intentionally empty. +} + +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +type CompositePodGroupSchedulingConstraints struct { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + // + // +optional + // +k8s:optional + // +k8s:maxItems=1 + // +listType=atomic + // +k8s:listType=atomic + Topology []TopologyConstraint `json:"topology,omitempty" protobuf:"bytes,1,rep,name=topology"` +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/types_swagger_doc_generated.go index f42008eb9..e514c6950 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/types_swagger_doc_generated.go @@ -27,9 +27,219 @@ package v1beta1 // Those methods can be generated by using hack/update-codegen.sh // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. +var map_AllCompositeDisruptionMode = map[string]string{ + "": "AllCompositeDisruptionMode means that children of a CompositePodGroup can only be disrupted or preempted together.", +} + +func (AllCompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_AllCompositeDisruptionMode +} + +var map_AllDisruptionMode = map[string]string{ + "": "AllDisruptionMode specifies that children can only be disrupted together.", +} + +func (AllDisruptionMode) SwaggerDoc() map[string]string { + return map_AllDisruptionMode +} + +var map_BasicSchedulingPolicy = map[string]string{ + "": "BasicSchedulingPolicy indicates that standard Kubernetes scheduling behavior should be used.", +} + +func (BasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_BasicSchedulingPolicy +} + +var map_CompositeBasicSchedulingPolicy = map[string]string{ + "": "CompositeBasicSchedulingPolicy indicates that the groups belonging to the composite group should be scheduled independently.", +} + +func (CompositeBasicSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositeBasicSchedulingPolicy +} + +var map_CompositeDisruptionMode = map[string]string{ + "": "CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. Exactly one mode must be set.", + "single": "single specifies that children groups can be disrupted independently from each other.", + "all": "all specifies that all children groups can only be disrupted together.", +} + +func (CompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_CompositeDisruptionMode +} + +var map_CompositeGangSchedulingPolicy = map[string]string{ + "": "CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group should be scheduled using all-or-nothing semantics.", + "minGroupCount": "minGroupCount is the minimum number of child groups that must be schedulable or scheduled at the same time for the scheduler to admit the entire group. It must be a positive integer.", +} + +func (CompositeGangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositeGangSchedulingPolicy +} + +var map_CompositePodGroupSchedulingConstraints = map[string]string{ + "": "CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup.", + "topology": "topology defines the topology constraints for the composite pod group. Currently only a single topology constraint can be specified. This may change in the future.", +} + +func (CompositePodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_CompositePodGroupSchedulingConstraints +} + +var map_CompositePodGroupSchedulingPolicy = map[string]string{ + "": "CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. Exactly one policy must be set.", + "basic": "basic specifies that the groups of this composite group should be scheduled independently. This field is immutable.", + "gang": "gang specifies that the groups of this composite group should be scheduled using all-or-nothing semantics.", +} + +func (CompositePodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_CompositePodGroupSchedulingPolicy +} + +var map_CompositePodGroupTemplate = map[string]string{ + "": "CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy.", + "name": "name is a unique identifier for the CompositePodGroupTemplate within the Workload. It must be a DNS label. This field is required.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this template.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. This field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. One of Single, All. This field is immutable.", + "priorityClassName": "priorityClassName indicates the priority that should be considered when scheduling a composite pod group created from this template. If no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, composite pod groups created from this template will have the priority set to zero. This field is immutable.", + "priority": "priority is the value of priority of composite pod groups created from this template. Various system components use this field to find the priority of the composite pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", + "podGroupTemplates": "podGroupTemplates is the list of templates for children PodGroups. The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates or PodGroupTemplates must be set.", + "compositePodGroupTemplates": "compositePodGroupTemplates is the list of templates for children CompositePodGroups. The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates or PodGroupTemplates must be set.", +} + +func (CompositePodGroupTemplate) SwaggerDoc() map[string]string { + return map_CompositePodGroupTemplate +} + +var map_DisruptionMode = map[string]string{ + "": "DisruptionMode defines how individual entities within a group can be disrupted. Exactly one mode can be set.", + "single": "single specifies that children can be disrupted independently from each other.", + "all": "all specifies that all children can only be disrupted together.", +} + +func (DisruptionMode) SwaggerDoc() map[string]string { + return map_DisruptionMode +} + +var map_GangSchedulingPolicy = map[string]string{ + "": "GangSchedulingPolicy defines the parameters for gang scheduling.", + "minCount": "minCount is the minimum number of pods that must be schedulable or scheduled at the same time for the scheduler to admit the entire group. It must be a positive integer. This field is mutable to support workload scaling.\n\nNote that the scheduler operates on an eventually consistent model. Updates to minCount may not be immediately reflected in scheduling decisions due to propagation delays. If minCount is updated while a scheduling cycle is in progress for that group, the new value may not take effect until the next cycle. Moreover, minCount is only enforced during scheduling, meaning that modifications to this field do not affect already-scheduled pods, applying only to those evaluated in future cycles.", +} + +func (GangSchedulingPolicy) SwaggerDoc() map[string]string { + return map_GangSchedulingPolicy +} + +var map_PodGroup = map[string]string{ + "": "PodGroup represents a runtime instance of pods grouped together. PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from Workload.podGroupTemplates. PodGroup API enablement is toggled by the GenericWorkload feature gate.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec defines the desired state of the PodGroup.", + "status": "status represents the current observed state of the PodGroup.", +} + +func (PodGroup) SwaggerDoc() map[string]string { + return map_PodGroup +} + +var map_PodGroupList = map[string]string{ + "": "PodGroupList contains a list of PodGroup resources.", + "metadata": "Standard list metadata.", + "items": "Items is the list of PodGroups.", +} + +func (PodGroupList) SwaggerDoc() map[string]string { + return map_PodGroupList +} + +var map_PodGroupResourceClaim = map[string]string{ + "": "PodGroupResourceClaim references exactly one ResourceClaim, either directly or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim for the PodGroup.\n\nIt adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. Pods that need access to the ResourceClaim define a matching reference in its own Spec.ResourceClaims. The Pod's claim must match all fields of the PodGroup's claim exactly.", + "name": "name uniquely identifies this resource claim inside the PodGroup. This must be a DNS_LABEL.", + "resourceClaimName": "resourceClaimName is the name of a ResourceClaim object in the same namespace as this PodGroup. The ResourceClaim will be reserved for the PodGroup instead of its individual pods.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", + "resourceClaimTemplateName": "resourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this PodGroup.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim will also be deleted. The PodGroup name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.\n\nExactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", +} + +func (PodGroupResourceClaim) SwaggerDoc() map[string]string { + return map_PodGroupResourceClaim +} + +var map_PodGroupResourceClaimStatus = map[string]string{ + "": "PodGroupResourceClaimStatus is stored in the PodGroupStatus for each PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the generated name for the corresponding ResourceClaim.", + "name": "name uniquely identifies this resource claim inside the PodGroup. This must match the name of an entry in podgroup.spec.resourceClaims, which implies that the string must be a DNS_LABEL.", + "resourceClaimName": "resourceClaimName is the name of the ResourceClaim that was generated for the PodGroup in the namespace of the PodGroup. If this is unset, then generating a ResourceClaim was not necessary. The podgroup.spec.resourceClaims entry can be ignored in this case.", +} + +func (PodGroupResourceClaimStatus) SwaggerDoc() map[string]string { + return map_PodGroupResourceClaimStatus +} + +var map_PodGroupSchedulingConstraints = map[string]string{ + "": "PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup.", + "topology": "topology defines the topology constraints for the pod group. Currently only a single topology constraint can be specified. This may change in the future.", +} + +func (PodGroupSchedulingConstraints) SwaggerDoc() map[string]string { + return map_PodGroupSchedulingConstraints +} + +var map_PodGroupSchedulingPolicy = map[string]string{ + "": "PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. Exactly one policy must be set. The policy is chosen at creation time by setting either the Basic or Gang field. The PodGroup may not change policy after creation. Fields within chosen policy may be updated after creation when their individual fields allow it.", + "basic": "basic specifies that the pods in this group should be scheduled using standard Kubernetes scheduling behavior. Setting this field at group creation time opts this group to basic scheduling; this field cannot be changed afterward.", + "gang": "gang specifies that the pods in this group should be scheduled using all-or-nothing semantics. Setting this field at group creation time opts this group to gang scheduling; this field cannot be set or unset afterward. The minCount field within Gang scheduling policy remains mutable after group creation.", +} + +func (PodGroupSchedulingPolicy) SwaggerDoc() map[string]string { + return map_PodGroupSchedulingPolicy +} + +var map_PodGroupSpec = map[string]string{ + "": "PodGroupSpec defines the desired state of a PodGroup.", + "parentCompositePodGroupName": "parentCompositePodGroupName contains the name of the parent composite pod group within the same namespace as this pod group. If it's nil, then this pod group is a root of a workload's hierarchy. This field is used only when the CompositePodGroup feature gate is enabled. This field is immutable.", + "workloadRef": "workloadRef references an optional PodGroup template within the Workload object that was used to create the PodGroup. This field is immutable.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this instance of the PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. Controllers are expected to fill this field by copying it from a PodGroupTemplate. This field is immutable. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled.", + "resourceClaims": "resourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is a beta-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given PodGroup can be disrupted. Controllers are expected to fill this field by copying it from a PodGroupTemplate. One of Single, All. Defaults to Single if unset. This field is immutable.", + "priorityClassName": "priorityClassName defines the priority that should be considered when scheduling this pod group. Controllers are expected to fill this field by copying it from a PodGroupTemplate. Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate (i.e. if no priority class is specified, admission control can set this to the global default priority class if it exists. Otherwise, the pod group's priority will be zero). This field is immutable.", + "priority": "priority is the value of priority of this pod group. Various system components use this field to find the priority of the pod group. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. When Priority Admission Controller is enabled, it populates this field from PriorityClassName, and defaults to PreemptLowerPriority if value is unset in PriorityClass. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", +} + +func (PodGroupSpec) SwaggerDoc() map[string]string { + return map_PodGroupSpec +} + +var map_PodGroupStatus = map[string]string{ + "": "PodGroupStatus represents information about the status of a pod group.", + "conditions": "conditions represent the latest observations of the PodGroup's state.\n\nKnown condition types: - \"PodGroupInitiallyScheduled\": Indicates whether the scheduling requirement has been satisfied. Once this condition transitions to True, it serves as a terminal state and will never revert to False, even if pods are subsequently evicted and group constraints are no longer met. - \"DisruptionTarget\": Indicates whether the PodGroup is about to be terminated\n due to disruption such as preemption.\n\nKnown reasons for the PodGroupInitiallyScheduled condition: - \"Unschedulable\": The PodGroup cannot be scheduled due to resource constraints,\n affinity/anti-affinity rules, or insufficient capacity for the gang.\n- \"SchedulerError\": The PodGroup cannot be scheduled due to some internal error\n that happened during scheduling, for example due to nodeAffinity parsing errors.\n\nKnown reasons for the DisruptionTarget condition: - \"PreemptionByScheduler\": The PodGroup was preempted by the scheduler to make room for\n higher-priority PodGroups or Pods.", + "resourceClaimStatuses": "resourceClaimStatuses is status of resource claims.", +} + +func (PodGroupStatus) SwaggerDoc() map[string]string { + return map_PodGroupStatus +} + +var map_PodGroupTemplate = map[string]string{ + "": "PodGroupTemplate represents a template for a set of pods with a scheduling policy.", + "name": "name is a unique identifier for the PodGroupTemplate within the Workload. It must be a DNS label. This field is immutable.", + "schedulingPolicy": "schedulingPolicy defines the scheduling policy for this PodGroupTemplate.", + "schedulingConstraints": "schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. This field is immutable.", + "resourceClaims": "resourceClaims defines which ResourceClaims may be shared among Pods in the group. Pods consume the devices allocated to a PodGroup's claim by defining a claim in its own Spec.ResourceClaims that matches the PodGroup's claim exactly. The claim must have the same name and refer to the same ResourceClaim or ResourceClaimTemplate.\n\nThis is a beta-level field and requires that the DRAWorkloadResourceClaims feature gate is enabled.\n\nThis field is immutable.", + "disruptionMode": "disruptionMode defines the mode in which a given PodGroup can be disrupted. One of Single, All. This field is immutable.", + "priorityClassName": "priorityClassName indicates the priority that should be considered when scheduling a pod group created from this template. This field is immutable.", + "priority": "priority is the value of priority of pod groups created from this template. Various system components use this field to find the priority of the pod group. The higher the value, the higher the priority. This field is immutable.", + "preemptionPolicy": "preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. One of Never, PreemptLowerPriority. This field is immutable. This field is available only when the PodGroupPreemptionPolicy feature gate is enabled.", +} + +func (PodGroupTemplate) SwaggerDoc() map[string]string { + return map_PodGroupTemplate +} + var map_PriorityClass = map[string]string{ "": "DEPRECATED - This group version of PriorityClass is deprecated by scheduling.k8s.io/v1/PriorityClass. PriorityClass defines mapping from a priority class name to the priority integer value. The value can be any valid integer.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "value": "value represents the integer value of this priority class. This is the actual priority that pods receive when they have the name of this class in their pod spec.", "globalDefault": "globalDefault specifies whether this PriorityClass should be considered as the default priority for pods that do not have any priority class. Only one PriorityClass can be marked as `globalDefault`. However, if more than one PriorityClasses exists with their `globalDefault` field set to true, the smallest value of such global default PriorityClasses will be used as the default priority.", "description": "description is an arbitrary string that usually provides guidelines on when this priority class should be used.", @@ -50,4 +260,81 @@ func (PriorityClassList) SwaggerDoc() map[string]string { return map_PriorityClassList } +var map_SingleCompositeDisruptionMode = map[string]string{ + "": "SingleCompositeDisruptionMode means that individual children of a CompositePodGroup can be disrupted or preempted independently.", +} + +func (SingleCompositeDisruptionMode) SwaggerDoc() map[string]string { + return map_SingleCompositeDisruptionMode +} + +var map_SingleDisruptionMode = map[string]string{ + "": "SingleDisruptionMode specifies that children can be disrupted independently.", +} + +func (SingleDisruptionMode) SwaggerDoc() map[string]string { + return map_SingleDisruptionMode +} + +var map_TopologyConstraint = map[string]string{ + "": "TopologyConstraint defines a topology constraint for a PodGroup.", + "key": "key specifies the key of the node label representing the topology domain. All pods within the PodGroup must be colocated within the same domain instance. Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. Examples: \"topology.kubernetes.io/rack\"", +} + +func (TopologyConstraint) SwaggerDoc() map[string]string { + return map_TopologyConstraint +} + +var map_TypedLocalObjectReference = map[string]string{ + "": "TypedLocalObjectReference allows to reference typed object inside the same namespace.", + "apiGroup": "apiGroup is the group for the resource being referenced. If apiGroup is empty, the specified Kind must be in the core API group. For any other third-party types, setting apiGroup is required. It must be a DNS subdomain.", + "kind": "kind is the type of resource being referenced. It must be a path segment name.", + "name": "name is the name of resource being referenced. It must be a path segment name.", +} + +func (TypedLocalObjectReference) SwaggerDoc() map[string]string { + return map_TypedLocalObjectReference +} + +var map_Workload = map[string]string{ + "": "Workload allows for expressing scheduling constraints that should be used when managing the lifecycle of workloads from the scheduling perspective, including scheduling, preemption, eviction and other phases. Workload API enablement is toggled by the GenericWorkload feature gate.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "spec defines the desired behavior of a Workload.", +} + +func (Workload) SwaggerDoc() map[string]string { + return map_Workload +} + +var map_WorkloadList = map[string]string{ + "": "WorkloadList contains a list of Workload resources.", + "metadata": "metadata is the standard list metadata.", + "items": "items is the list of Workloads.", +} + +func (WorkloadList) SwaggerDoc() map[string]string { + return map_WorkloadList +} + +var map_WorkloadReference = map[string]string{ + "": "WorkloadReference references the Workload object together with the template that was used to create a particular PodGroup.", + "workloadName": "workloadName is the name of the Workload object that contains a template that was used when creating a pod group. It must be a DNS name. This field is required.", + "templateName": "templateName is the name of a template within the Workload object that was used to create a pod group. It must be a DNS label. This field is required.", +} + +func (WorkloadReference) SwaggerDoc() map[string]string { + return map_WorkloadReference +} + +var map_WorkloadSpec = map[string]string{ + "": "WorkloadSpec defines the desired state of a Workload.", + "controllerRef": "controllerRef is an optional reference to the controlling object, such as a Deployment or Job. This field is intended for use by tools like CLIs to provide a link back to the original workload definition. This field is immutable.", + "podGroupTemplates": "podGroupTemplates is the list of templates that make up the Workload. The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. Existing templates may still be updated where their individual fields allow it. Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set.", + "compositePodGroupTemplates": "compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. The maximum number of templates is 8. This field is immutable. Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set.\n\nThis field is used only when the CompositePodGroup feature gate is enabled.", +} + +func (WorkloadSpec) SwaggerDoc() map[string]string { + return map_WorkloadSpec +} + // AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.deepcopy.go index ff38c9854..aacc643ad 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.deepcopy.go @@ -22,10 +22,540 @@ limitations under the License. package v1beta1 import ( - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AllCompositeDisruptionMode) DeepCopyInto(out *AllCompositeDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllCompositeDisruptionMode. +func (in *AllCompositeDisruptionMode) DeepCopy() *AllCompositeDisruptionMode { + if in == nil { + return nil + } + out := new(AllCompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AllDisruptionMode) DeepCopyInto(out *AllDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AllDisruptionMode. +func (in *AllDisruptionMode) DeepCopy() *AllDisruptionMode { + if in == nil { + return nil + } + out := new(AllDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BasicSchedulingPolicy) DeepCopyInto(out *BasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicSchedulingPolicy. +func (in *BasicSchedulingPolicy) DeepCopy() *BasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(BasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeBasicSchedulingPolicy) DeepCopyInto(out *CompositeBasicSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeBasicSchedulingPolicy. +func (in *CompositeBasicSchedulingPolicy) DeepCopy() *CompositeBasicSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositeBasicSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeDisruptionMode) DeepCopyInto(out *CompositeDisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(SingleCompositeDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(AllCompositeDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeDisruptionMode. +func (in *CompositeDisruptionMode) DeepCopy() *CompositeDisruptionMode { + if in == nil { + return nil + } + out := new(CompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositeGangSchedulingPolicy) DeepCopyInto(out *CompositeGangSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositeGangSchedulingPolicy. +func (in *CompositeGangSchedulingPolicy) DeepCopy() *CompositeGangSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositeGangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupSchedulingConstraints) DeepCopyInto(out *CompositePodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupSchedulingConstraints. +func (in *CompositePodGroupSchedulingConstraints) DeepCopy() *CompositePodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(CompositePodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupSchedulingPolicy) DeepCopyInto(out *CompositePodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(CompositeBasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(CompositeGangSchedulingPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupSchedulingPolicy. +func (in *CompositePodGroupSchedulingPolicy) DeepCopy() *CompositePodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(CompositePodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CompositePodGroupTemplate) DeepCopyInto(out *CompositePodGroupTemplate) { + *out = *in + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(CompositePodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(CompositeDisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + if in.PodGroupTemplates != nil { + in, out := &in.PodGroupTemplates, &out.PodGroupTemplates + *out = make([]PodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.CompositePodGroupTemplates != nil { + in, out := &in.CompositePodGroupTemplates, &out.CompositePodGroupTemplates + *out = make([]CompositePodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CompositePodGroupTemplate. +func (in *CompositePodGroupTemplate) DeepCopy() *CompositePodGroupTemplate { + if in == nil { + return nil + } + out := new(CompositePodGroupTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DisruptionMode) DeepCopyInto(out *DisruptionMode) { + *out = *in + if in.Single != nil { + in, out := &in.Single, &out.Single + *out = new(SingleDisruptionMode) + **out = **in + } + if in.All != nil { + in, out := &in.All, &out.All + *out = new(AllDisruptionMode) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DisruptionMode. +func (in *DisruptionMode) DeepCopy() *DisruptionMode { + if in == nil { + return nil + } + out := new(DisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GangSchedulingPolicy) DeepCopyInto(out *GangSchedulingPolicy) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GangSchedulingPolicy. +func (in *GangSchedulingPolicy) DeepCopy() *GangSchedulingPolicy { + if in == nil { + return nil + } + out := new(GangSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroup) DeepCopyInto(out *PodGroup) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroup. +func (in *PodGroup) DeepCopy() *PodGroup { + if in == nil { + return nil + } + out := new(PodGroup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodGroup) 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 *PodGroupList) DeepCopyInto(out *PodGroupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodGroup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupList. +func (in *PodGroupList) DeepCopy() *PodGroupList { + if in == nil { + return nil + } + out := new(PodGroupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodGroupList) 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 *PodGroupResourceClaim) DeepCopyInto(out *PodGroupResourceClaim) { + *out = *in + if in.ResourceClaimName != nil { + in, out := &in.ResourceClaimName, &out.ResourceClaimName + *out = new(string) + **out = **in + } + if in.ResourceClaimTemplateName != nil { + in, out := &in.ResourceClaimTemplateName, &out.ResourceClaimTemplateName + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaim. +func (in *PodGroupResourceClaim) DeepCopy() *PodGroupResourceClaim { + if in == nil { + return nil + } + out := new(PodGroupResourceClaim) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupResourceClaimStatus) DeepCopyInto(out *PodGroupResourceClaimStatus) { + *out = *in + if in.ResourceClaimName != nil { + in, out := &in.ResourceClaimName, &out.ResourceClaimName + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupResourceClaimStatus. +func (in *PodGroupResourceClaimStatus) DeepCopy() *PodGroupResourceClaimStatus { + if in == nil { + return nil + } + out := new(PodGroupResourceClaimStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSchedulingConstraints) DeepCopyInto(out *PodGroupSchedulingConstraints) { + *out = *in + if in.Topology != nil { + in, out := &in.Topology, &out.Topology + *out = make([]TopologyConstraint, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingConstraints. +func (in *PodGroupSchedulingConstraints) DeepCopy() *PodGroupSchedulingConstraints { + if in == nil { + return nil + } + out := new(PodGroupSchedulingConstraints) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSchedulingPolicy) DeepCopyInto(out *PodGroupSchedulingPolicy) { + *out = *in + if in.Basic != nil { + in, out := &in.Basic, &out.Basic + *out = new(BasicSchedulingPolicy) + **out = **in + } + if in.Gang != nil { + in, out := &in.Gang, &out.Gang + *out = new(GangSchedulingPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSchedulingPolicy. +func (in *PodGroupSchedulingPolicy) DeepCopy() *PodGroupSchedulingPolicy { + if in == nil { + return nil + } + out := new(PodGroupSchedulingPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupSpec) DeepCopyInto(out *PodGroupSpec) { + *out = *in + if in.ParentCompositePodGroupName != nil { + in, out := &in.ParentCompositePodGroupName, &out.ParentCompositePodGroupName + *out = new(string) + **out = **in + } + if in.WorkloadRef != nil { + in, out := &in.WorkloadRef, &out.WorkloadRef + *out = new(WorkloadReference) + **out = **in + } + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(PodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.ResourceClaims != nil { + in, out := &in.ResourceClaims, &out.ResourceClaims + *out = make([]PodGroupResourceClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(DisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupSpec. +func (in *PodGroupSpec) DeepCopy() *PodGroupSpec { + if in == nil { + return nil + } + out := new(PodGroupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupStatus) DeepCopyInto(out *PodGroupStatus) { + *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.ResourceClaimStatuses != nil { + in, out := &in.ResourceClaimStatuses, &out.ResourceClaimStatuses + *out = make([]PodGroupResourceClaimStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupStatus. +func (in *PodGroupStatus) DeepCopy() *PodGroupStatus { + if in == nil { + return nil + } + out := new(PodGroupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodGroupTemplate) DeepCopyInto(out *PodGroupTemplate) { + *out = *in + in.SchedulingPolicy.DeepCopyInto(&out.SchedulingPolicy) + if in.SchedulingConstraints != nil { + in, out := &in.SchedulingConstraints, &out.SchedulingConstraints + *out = new(PodGroupSchedulingConstraints) + (*in).DeepCopyInto(*out) + } + if in.ResourceClaims != nil { + in, out := &in.ResourceClaims, &out.ResourceClaims + *out = make([]PodGroupResourceClaim, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.DisruptionMode != nil { + in, out := &in.DisruptionMode, &out.DisruptionMode + *out = new(DisruptionMode) + (*in).DeepCopyInto(*out) + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(int32) + **out = **in + } + if in.PreemptionPolicy != nil { + in, out := &in.PreemptionPolicy, &out.PreemptionPolicy + *out = new(PreemptionPolicy) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodGroupTemplate. +func (in *PodGroupTemplate) DeepCopy() *PodGroupTemplate { + if in == nil { + return nil + } + out := new(PodGroupTemplate) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PriorityClass) DeepCopyInto(out *PriorityClass) { *out = *in @@ -33,7 +563,7 @@ func (in *PriorityClass) DeepCopyInto(out *PriorityClass) { in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) if in.PreemptionPolicy != nil { in, out := &in.PreemptionPolicy, &out.PreemptionPolicy - *out = new(v1.PreemptionPolicy) + *out = new(corev1.PreemptionPolicy) **out = **in } return @@ -89,3 +619,178 @@ func (in *PriorityClassList) DeepCopyObject() runtime.Object { } return nil } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SingleCompositeDisruptionMode) DeepCopyInto(out *SingleCompositeDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SingleCompositeDisruptionMode. +func (in *SingleCompositeDisruptionMode) DeepCopy() *SingleCompositeDisruptionMode { + if in == nil { + return nil + } + out := new(SingleCompositeDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SingleDisruptionMode) DeepCopyInto(out *SingleDisruptionMode) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SingleDisruptionMode. +func (in *SingleDisruptionMode) DeepCopy() *SingleDisruptionMode { + if in == nil { + return nil + } + out := new(SingleDisruptionMode) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TopologyConstraint) DeepCopyInto(out *TopologyConstraint) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TopologyConstraint. +func (in *TopologyConstraint) DeepCopy() *TopologyConstraint { + if in == nil { + return nil + } + out := new(TopologyConstraint) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TypedLocalObjectReference) DeepCopyInto(out *TypedLocalObjectReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TypedLocalObjectReference. +func (in *TypedLocalObjectReference) DeepCopy() *TypedLocalObjectReference { + if in == nil { + return nil + } + out := new(TypedLocalObjectReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Workload) DeepCopyInto(out *Workload) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Workload. +func (in *Workload) DeepCopy() *Workload { + if in == nil { + return nil + } + out := new(Workload) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Workload) 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 *WorkloadList) DeepCopyInto(out *WorkloadList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Workload, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadList. +func (in *WorkloadList) DeepCopy() *WorkloadList { + if in == nil { + return nil + } + out := new(WorkloadList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *WorkloadList) 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 *WorkloadReference) DeepCopyInto(out *WorkloadReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadReference. +func (in *WorkloadReference) DeepCopy() *WorkloadReference { + if in == nil { + return nil + } + out := new(WorkloadReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WorkloadSpec) DeepCopyInto(out *WorkloadSpec) { + *out = *in + if in.ControllerRef != nil { + in, out := &in.ControllerRef, &out.ControllerRef + *out = new(TypedLocalObjectReference) + **out = **in + } + if in.PodGroupTemplates != nil { + in, out := &in.PodGroupTemplates, &out.PodGroupTemplates + *out = make([]PodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.CompositePodGroupTemplates != nil { + in, out := &in.CompositePodGroupTemplates, &out.CompositePodGroupTemplates + *out = make([]CompositePodGroupTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadSpec. +func (in *WorkloadSpec) DeepCopy() *WorkloadSpec { + if in == nil { + return nil + } + out := new(WorkloadSpec) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.model_name.go index 16f40100c..be01a4c3e 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.model_name.go @@ -21,6 +21,106 @@ limitations under the License. package v1beta1 +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in AllCompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.AllCompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in AllDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.AllDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in BasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.BasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeBasicSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositeBasicSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositeGangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositeGangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CompositePodGroupTemplate) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.CompositePodGroupTemplate" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in DisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.DisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in GangSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.GangSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroup) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroup" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupList) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupResourceClaim) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupResourceClaim" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupResourceClaimStatus) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupResourceClaimStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSchedulingConstraints) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupSchedulingConstraints" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSchedulingPolicy) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupSchedulingPolicy" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupSpec) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupSpec" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupStatus) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupStatus" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in PodGroupTemplate) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.PodGroupTemplate" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in PriorityClass) OpenAPIModelName() string { return "io.k8s.api.scheduling.v1beta1.PriorityClass" @@ -30,3 +130,43 @@ func (in PriorityClass) OpenAPIModelName() string { func (in PriorityClassList) OpenAPIModelName() string { return "io.k8s.api.scheduling.v1beta1.PriorityClassList" } + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in SingleCompositeDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.SingleCompositeDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in SingleDisruptionMode) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.SingleDisruptionMode" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in TopologyConstraint) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.TopologyConstraint" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in TypedLocalObjectReference) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.TypedLocalObjectReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in Workload) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.Workload" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadList) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.WorkloadList" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadReference) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.WorkloadReference" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in WorkloadSpec) OpenAPIModelName() string { + return "io.k8s.api.scheduling.v1beta1.WorkloadSpec" +} diff --git a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.prerelease-lifecycle.go index 15aefb108..25f113612 100644 --- a/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/scheduling/v1beta1/zz_generated.prerelease-lifecycle.go @@ -25,6 +25,42 @@ import ( schema "k8s.io/apimachinery/pkg/runtime/schema" ) +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *PodGroup) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *PodGroup) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *PodGroup) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *PodGroupList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *PodGroupList) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *PodGroupList) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *PriorityClass) APILifecycleIntroduced() (major, minor int) { @@ -72,3 +108,39 @@ func (in *PriorityClassList) APILifecycleReplacement() schema.GroupVersionKind { func (in *PriorityClassList) APILifecycleRemoved() (major, minor int) { return 1, 22 } + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *Workload) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *Workload) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *Workload) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *WorkloadList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. +func (in *WorkloadList) APILifecycleDeprecated() (major, minor int) { + return 1, 40 +} + +// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. +func (in *WorkloadList) APILifecycleRemoved() (major, minor int) { + return 1, 43 +} diff --git a/constraint/vendor/k8s.io/api/storage/v1/generated.pb.go b/constraint/vendor/k8s.io/api/storage/v1/generated.pb.go index 5fc7d55a5..4a6e5222f 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/storage/v1/generated.pb.go @@ -49,6 +49,8 @@ func (m *CSINodeList) Reset() { *m = CSINodeList{} } func (m *CSINodeSpec) Reset() { *m = CSINodeSpec{} } +func (m *CSINodeStatus) Reset() { *m = CSINodeStatus{} } + func (m *CSIStorageCapacity) Reset() { *m = CSIStorageCapacity{} } func (m *CSIStorageCapacityList) Reset() { *m = CSIStorageCapacityList{} } @@ -57,6 +59,10 @@ func (m *StorageClass) Reset() { *m = StorageClass{} } func (m *StorageClassList) Reset() { *m = StorageClassList{} } +func (m *StorageHealth) Reset() { *m = StorageHealth{} } + +func (m *StorageHealthCondition) Reset() { *m = StorageHealthCondition{} } + func (m *TokenRequest) Reset() { *m = TokenRequest{} } func (m *VolumeAttachment) Reset() { *m = VolumeAttachment{} } @@ -315,6 +321,16 @@ func (m *CSINode) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a { size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -476,6 +492,43 @@ func (m *CSINodeSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *CSINodeStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CSINodeStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CSINodeStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.StorageHealth) > 0 { + for iNdEx := len(m.StorageHealth) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.StorageHealth[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func (m *CSIStorageCapacity) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -753,6 +806,110 @@ func (m *StorageClassList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *StorageHealth) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageHealth) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageHealth) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.HealthConditions) > 0 { + for iNdEx := len(m.HealthConditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.HealthConditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *StorageHealthCondition) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageHealthCondition) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageHealthCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if m.VolumeMode != nil { + i -= len(*m.VolumeMode) + copy(dAtA[i:], *m.VolumeMode) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.VolumeMode))) + i-- + dAtA[i] = 0x2a + } + if m.AccessMode != nil { + i -= len(*m.AccessMode) + copy(dAtA[i:], *m.AccessMode) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.AccessMode))) + i-- + dAtA[i] = 0x22 + } + i -= len(m.Message) + copy(dAtA[i:], m.Message) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) + i-- + dAtA[i] = 0x1a + i -= len(m.Reason) + copy(dAtA[i:], m.Reason) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason))) + i-- + dAtA[i] = 0x12 + i -= len(m.Status) + copy(dAtA[i:], m.Status) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *TokenRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1330,6 +1487,8 @@ func (m *CSINode) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -1388,6 +1547,21 @@ func (m *CSINodeSpec) Size() (n int) { return n } +func (m *CSINodeStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.StorageHealth) > 0 { + for _, e := range m.StorageHealth { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *CSIStorageCapacity) Size() (n int) { if m == nil { return 0 @@ -1491,6 +1665,48 @@ func (m *StorageClassList) Size() (n int) { return n } +func (m *StorageHealth) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.HealthConditions) > 0 { + for _, e := range m.HealthConditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *StorageHealthCondition) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Status) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + if m.AccessMode != nil { + l = len(*m.AccessMode) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.VolumeMode != nil { + l = len(*m.VolumeMode) + n += 1 + l + sovGenerated(uint64(l)) + } + l = m.LastTransitionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *TokenRequest) Size() (n int) { if m == nil { return 0 @@ -1726,6 +1942,7 @@ func (this *CSINode) String() string { s := strings.Join([]string{`&CSINode{`, `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CSINodeSpec", "CSINodeSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CSINodeStatus", "CSINodeStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s @@ -1774,6 +1991,21 @@ func (this *CSINodeSpec) String() string { }, "") return s } +func (this *CSINodeStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForStorageHealth := "[]StorageHealth{" + for _, f := range this.StorageHealth { + repeatedStringForStorageHealth += strings.Replace(strings.Replace(f.String(), "StorageHealth", "StorageHealth", 1), `&`, ``, 1) + "," + } + repeatedStringForStorageHealth += "}" + s := strings.Join([]string{`&CSINodeStatus{`, + `StorageHealth:` + repeatedStringForStorageHealth + `,`, + `}`, + }, "") + return s +} func (this *CSIStorageCapacity) String() string { if this == nil { return "nil" @@ -1852,6 +2084,37 @@ func (this *StorageClassList) String() string { }, "") return s } +func (this *StorageHealth) String() string { + if this == nil { + return "nil" + } + repeatedStringForHealthConditions := "[]StorageHealthCondition{" + for _, f := range this.HealthConditions { + repeatedStringForHealthConditions += strings.Replace(strings.Replace(f.String(), "StorageHealthCondition", "StorageHealthCondition", 1), `&`, ``, 1) + "," + } + repeatedStringForHealthConditions += "}" + s := strings.Join([]string{`&StorageHealth{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `HealthConditions:` + repeatedStringForHealthConditions + `,`, + `}`, + }, "") + return s +} +func (this *StorageHealthCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StorageHealthCondition{`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `AccessMode:` + valueToStringGenerated(this.AccessMode) + `,`, + `VolumeMode:` + valueToStringGenerated(this.VolumeMode) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *TokenRequest) String() string { if this == nil { return "nil" @@ -2649,6 +2912,39 @@ func (m *CSINode) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -3053,7 +3349,7 @@ func (m *CSINodeSpec) Unmarshal(dAtA []byte) error { } return nil } -func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { +func (m *CSINodeStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3076,15 +3372,15 @@ func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CSIStorageCapacity: wiretype end group for non-group") + return fmt.Errorf("proto: CSINodeStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CSIStorageCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: CSINodeStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StorageHealth", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3111,30 +3407,114 @@ func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.StorageHealth = append(m.StorageHealth, StorageHealth{}) + if err := m.StorageHealth[len(m.StorageHealth)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeTopology", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - if msglen < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CSIStorageCapacity: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CSIStorageCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeTopology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen @@ -3905,6 +4285,367 @@ func (m *StorageClassList) Unmarshal(dAtA []byte) error { } return nil } +func (m *StorageHealth) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageHealth: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageHealth: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field HealthConditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.HealthConditions = append(m.HealthConditions, StorageHealthCondition{}) + if err := m.HealthConditions[len(m.HealthConditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageHealthCondition) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageHealthCondition: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageHealthCondition: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Status = StorageHealthStatusType(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Reason = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccessMode", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := k8s_io_api_core_v1.PersistentVolumeAccessMode(dAtA[iNdEx:postIndex]) + m.AccessMode = &s + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VolumeMode", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := k8s_io_api_core_v1.PersistentVolumeMode(dAtA[iNdEx:postIndex]) + m.VolumeMode = &s + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *TokenRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/constraint/vendor/k8s.io/api/storage/v1/generated.proto b/constraint/vendor/k8s.io/api/storage/v1/generated.proto index d6bc969bb..dc3855e23 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/generated.proto +++ b/constraint/vendor/k8s.io/api/storage/v1/generated.proto @@ -36,7 +36,7 @@ option go_package = "k8s.io/api/storage/v1"; // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. message CSIDriver { - // Standard object metadata. + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. @@ -124,6 +124,8 @@ message CSIDriverSpec { // // +optional // +listType=set + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable repeated string volumeLifecycleModes = 3; // storageCapacity indicates that the CSI volume driver wants pod scheduling to consider the storage @@ -250,7 +252,7 @@ message CSIDriverSpec { // +optional optional bool serviceAccountTokenInSecrets = 10; - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -265,7 +267,7 @@ message CSIDriverSpec { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". // +featureGate=VolumeLimitScaling // +optional @@ -282,12 +284,16 @@ message CSIDriverSpec { // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. message CSINode { - // Standard object's metadata. + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec is the specification of CSINode optional CSINodeSpec spec = 2; + + // status contains health and status information for the node's storage. + // +optional + optional CSINodeStatus status = 3; } // CSINodeDriver holds information about the specification of one CSI driver installed on a node @@ -350,6 +356,18 @@ message CSINodeSpec { repeated CSINodeDriver drivers = 1; } +// CSINodeStatus contains health and status information for storage on a node. +message CSINodeStatus { + // storageHealth contains backend health reports for CSI drivers registered on the node. + // +optional + // +listType=map + // +listMapKey=name + // +patchMergeKey=name + // +patchStrategy=merge + // +featureGate=CSIVolumeHealth + repeated StorageHealth storageHealth = 1; +} + // CSIStorageCapacity stores the result of one CSI GetCapacity call. // For a given StorageClass, this describes the available capacity in a // particular topology segment. This can be used when considering where to @@ -375,7 +393,7 @@ message CSINodeSpec { // the scheduler assumes that capacity is insufficient and tries some other // node. message CSIStorageCapacity { - // Standard object's metadata. + // metadata is the standard object metadata. // The name has no particular meaning. It must be a DNS subdomain (dots allowed, 253 characters). // To ensure that there are no conflicts with other CSI drivers on the cluster, // the recommendation is to use csisc-, a generated name, or a reverse-domain name @@ -448,29 +466,29 @@ message CSIStorageCapacityList { // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. message StorageClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // provisioner indicates the type of the provisioner. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional string provisioner = 2; // parameters holds the parameters for the provisioner that should // create volumes of this storage class. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional map parameters = 3; // reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. // Defaults to Delete. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional optional string reclaimPolicy = 4; // mountOptions controls the mountOptions for dynamically provisioned PersistentVolumes of this storage class. @@ -488,8 +506,8 @@ message StorageClass { // provisioned and bound. When unset, VolumeBindingImmediate is used. // This field is only honored by servers that enable the VolumeScheduling feature. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional optional string volumeBindingMode = 7; // allowedTopologies restrict the node topologies where volumes can be dynamically provisioned. @@ -512,6 +530,50 @@ message StorageClassList { repeated StorageClass items = 2; } +// StorageHealth contains storage backend health reported by a CSI driver on a node. +message StorageHealth { + // name is the CSI driver name, matching CSINodeDriver.name. + // +required + optional string name = 1; + + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + // +optional + // +listType=atomic + repeated StorageHealthCondition healthConditions = 2; +} + +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +message StorageHealthCondition { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + // +required + optional string status = 1; + + // reason is a brief CamelCase machine-parseable reason. + // Maximum permitted length of a reason is 256 characters. + // +required + optional string reason = 2; + + // message is a human-readable description. + // +optional + // Maximum permitted length of a message is 1024 characters. + optional string message = 3; + + // accessMode is the access mode affected. Nil means all access modes are affected. + // +optional + optional string accessMode = 4; + + // volumeMode is the volume mode affected. Nil means both are affected. + // +optional + optional string volumeMode = 5; + + // lastTransitionTime is when this condition first appeared at its current state. + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 6; +} + // TokenRequest contains parameters of a service account token. message TokenRequest { // audience is the intended audience of the token in "TokenRequestSpec". @@ -530,14 +592,14 @@ message TokenRequest { // // VolumeAttachment objects are non-namespaced. message VolumeAttachment { - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required optional VolumeAttachmentSpec spec = 2; @@ -583,9 +645,9 @@ message VolumeAttachmentSpec { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string attacher = 1; // source represents the volume that should be attached. @@ -627,12 +689,12 @@ message VolumeAttachmentStatus { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. message VolumeAttributesClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. optional string driverName = 2; diff --git a/constraint/vendor/k8s.io/api/storage/v1/types.go b/constraint/vendor/k8s.io/api/storage/v1/types.go index c65ebed4e..f5499b810 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/types.go +++ b/constraint/vendor/k8s.io/api/storage/v1/types.go @@ -33,31 +33,31 @@ import ( // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. type StorageClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // provisioner indicates the type of the provisioner. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable Provisioner string `json:"provisioner" protobuf:"bytes,2,opt,name=provisioner"` // parameters holds the parameters for the provisioner that should // create volumes of this storage class. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional Parameters map[string]string `json:"parameters,omitempty" protobuf:"bytes,3,rep,name=parameters"` // reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. // Defaults to Delete. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional ReclaimPolicy *v1.PersistentVolumeReclaimPolicy `json:"reclaimPolicy,omitempty" protobuf:"bytes,4,opt,name=reclaimPolicy,casttype=k8s.io/api/core/v1.PersistentVolumeReclaimPolicy"` // mountOptions controls the mountOptions for dynamically provisioned PersistentVolumes of this storage class. @@ -75,8 +75,8 @@ type StorageClass struct { // provisioned and bound. When unset, VolumeBindingImmediate is used. // This field is only honored by servers that enable the VolumeScheduling feature. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional VolumeBindingMode *VolumeBindingMode `json:"volumeBindingMode,omitempty" protobuf:"bytes,7,opt,name=volumeBindingMode"` // allowedTopologies restrict the node topologies where volumes can be dynamically provisioned. @@ -93,7 +93,7 @@ type StorageClass struct { // StorageClassList is a collection of storage classes. type StorageClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -131,16 +131,16 @@ const ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required Spec VolumeAttachmentSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` @@ -156,7 +156,7 @@ type VolumeAttachment struct { // VolumeAttachmentList is a collection of VolumeAttachment objects. type VolumeAttachmentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -172,9 +172,9 @@ type VolumeAttachmentSpec struct { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Attacher string `json:"attacher" protobuf:"bytes,1,opt,name=attacher"` // source represents the volume that should be attached. @@ -263,9 +263,9 @@ type VolumeError struct { // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. type CSIDriver struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object metadata. + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. @@ -284,7 +284,7 @@ type CSIDriver struct { // CSIDriverList is a collection of CSIDriver objects. type CSIDriverList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -358,6 +358,8 @@ type CSIDriverSpec struct { // // +optional // +listType=set + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable VolumeLifecycleModes []VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty" protobuf:"bytes,3,opt,name=volumeLifecycleModes"` // storageCapacity indicates that the CSI volume driver wants pod scheduling to consider the storage @@ -484,7 +486,7 @@ type CSIDriverSpec struct { // +optional ServiceAccountTokenInSecrets *bool `json:"serviceAccountTokenInSecrets,omitempty" protobuf:"varint,10,opt,name=serviceAccountTokenInSecrets"` - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -499,7 +501,7 @@ type CSIDriverSpec struct { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". // +featureGate=VolumeLimitScaling // +optional @@ -580,6 +582,7 @@ const ( // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.17 +// +k8s:supportsSubresource="/status" // CSINode holds information about all CSI drivers installed on a node. // CSI drivers do not need to create the CSINode object directly. As long as @@ -591,14 +594,18 @@ const ( // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. type CSINode struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec is the specification of CSINode Spec CSINodeSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status contains health and status information for the node's storage. + // +optional + Status CSINodeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // CSINodeSpec holds information about the specification of all CSI drivers installed on a node @@ -660,12 +667,73 @@ type VolumeNodeResources struct { Count *int32 `json:"count,omitempty" protobuf:"varint,1,opt,name=count"` } +// StorageHealthStatusType describes the health status category of a storage backend. +// +enum +type StorageHealthStatusType string + +const ( + // StorageUnreachable indicates the storage backend is unreachable. + StorageUnreachable StorageHealthStatusType = "StorageUnreachable" + // StorageDegraded indicates the storage backend is functioning with reduced capability. + StorageDegraded StorageHealthStatusType = "StorageDegraded" +) + +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +type StorageHealthCondition struct { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + // +required + Status StorageHealthStatusType `json:"status" protobuf:"bytes,1,opt,name=status,casttype=StorageHealthStatusType"` + // reason is a brief CamelCase machine-parseable reason. + // Maximum permitted length of a reason is 256 characters. + // +required + Reason string `json:"reason" protobuf:"bytes,2,opt,name=reason"` + // message is a human-readable description. + // +optional + // Maximum permitted length of a message is 1024 characters. + Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` + // accessMode is the access mode affected. Nil means all access modes are affected. + // +optional + AccessMode *v1.PersistentVolumeAccessMode `json:"accessMode,omitempty" protobuf:"bytes,4,opt,name=accessMode,casttype=k8s.io/api/core/v1.PersistentVolumeAccessMode"` + // volumeMode is the volume mode affected. Nil means both are affected. + // +optional + VolumeMode *v1.PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,5,opt,name=volumeMode,casttype=k8s.io/api/core/v1.PersistentVolumeMode"` + // lastTransitionTime is when this condition first appeared at its current state. + // +optional + LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,6,opt,name=lastTransitionTime"` +} + +// StorageHealth contains storage backend health reported by a CSI driver on a node. +type StorageHealth struct { + // name is the CSI driver name, matching CSINodeDriver.name. + // +required + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + // +optional + // +listType=atomic + HealthConditions []StorageHealthCondition `json:"healthConditions,omitempty" protobuf:"bytes,2,rep,name=healthConditions"` +} + +// CSINodeStatus contains health and status information for storage on a node. +type CSINodeStatus struct { + // storageHealth contains backend health reports for CSI drivers registered on the node. + // +optional + // +listType=map + // +listMapKey=name + // +patchMergeKey=name + // +patchStrategy=merge + // +featureGate=CSIVolumeHealth + StorageHealth []StorageHealth `json:"storageHealth,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,1,rep,name=storageHealth"` +} + // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.17 // CSINodeList is a collection of CSINode objects. type CSINodeList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -705,9 +773,9 @@ type CSINodeList struct { // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacity struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // The name has no particular meaning. It must be a DNS subdomain (dots allowed, 253 characters). // To ensure that there are no conflicts with other CSI drivers on the cluster, // the recommendation is to use csisc-, a generated name, or a reverse-domain name @@ -768,7 +836,7 @@ type CSIStorageCapacity struct { // CSIStorageCapacityList is a collection of CSIStorageCapacity objects. type CSIStorageCapacityList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -788,14 +856,14 @@ type CSIStorageCapacityList struct { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName string `json:"driverName" protobuf:"bytes,2,opt,name=driverName"` @@ -820,7 +888,7 @@ type VolumeAttributesClass struct { // VolumeAttributesClassList is a collection of VolumeAttributesClass objects. type VolumeAttributesClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/storage/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/storage/v1/types_swagger_doc_generated.go index 47a7e9249..62a910422 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/storage/v1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_CSIDriver = map[string]string{ "": "CSIDriver captures information about a Container Storage Interface (CSI) volume driver deployed on the cluster. Kubernetes attach detach controller uses this object to determine whether attach is required. Kubelet uses this object to determine whether pod information needs to be passed on mount. CSIDriver objects are non-namespaced.", - "metadata": "Standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents the specification of the CSI Driver.", } @@ -59,7 +59,7 @@ var map_CSIDriverSpec = map[string]string{ "seLinuxMount": "seLinuxMount specifies if the CSI driver supports \"-o context\" mount option.\n\nWhen \"true\", the CSI driver must ensure that all volumes provided by this CSI driver can be mounted separately with different `-o context` options. This is typical for storage backends that provide volumes as filesystems on block devices or as independent shared volumes. Kubernetes will call NodeStage / NodePublish with \"-o context=xyz\" mount option when mounting a ReadWriteOncePod volume used in Pod that has explicitly set SELinux context. In the future, it may be expanded to other volume AccessModes. In any case, Kubernetes will ensure that the volume is mounted only with a single SELinux context.\n\nWhen \"false\", Kubernetes won't pass any special SELinux mount options to the driver. This is typical for volumes that represent subdirectories of a bigger shared filesystem.\n\nDefault is \"false\".", "nodeAllocatableUpdatePeriodSeconds": "nodeAllocatableUpdatePeriodSeconds specifies the interval between periodic updates of the CSINode allocatable capacity for this driver. When set, both periodic updates and updates triggered by capacity-related failures are enabled. If not set, no updates occur (neither periodic nor upon detecting capacity-related failures), and the allocatable.count remains static. The minimum allowed value for this field is 10 seconds.\n\nThis feature requires the MutableCSINodeAllocatableCount feature gate to be enabled.\n\nThis field is mutable.", "serviceAccountTokenInSecrets": "serviceAccountTokenInSecrets is an opt-in for CSI drivers to indicate that service account tokens should be passed via the Secrets field in NodePublishVolumeRequest instead of the VolumeContext field. The CSI specification provides a dedicated Secrets field for sensitive information like tokens, which is the appropriate mechanism for handling credentials. This addresses security concerns where sensitive tokens were being logged as part of volume context.\n\nWhen \"true\", kubelet will pass the tokens only in the Secrets field with the key \"csi.storage.k8s.io/serviceAccount.tokens\". The CSI driver must be updated to read tokens from the Secrets field instead of VolumeContext.\n\nWhen \"false\" or not set, kubelet will pass the tokens in VolumeContext with the key \"csi.storage.k8s.io/serviceAccount.tokens\" (existing behavior). This maintains backward compatibility with existing CSI drivers.\n\nThis field can only be set when TokenRequests is configured. The API server will reject CSIDriver specs that set this field without TokenRequests.\n\nDefault behavior if unset is to pass tokens in the VolumeContext field.", - "preventPodSchedulingIfMissing": "PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod scheduling if the CSI driver on the node is missing.\n\nEnabling this option will prevent the scheduler (or any other component which embeds default scheduler such as cluster-autoscaler) from scheduling pods to nodes where CSI driver is not installed.\n\nFor components(such as cluster-autoscaler) that embed the scheduler and run pod placement simulations using scheduler plugins, they MUST be aware of CSI driver registration information via CSINode object. They must create simulated CSINode objects in addition to Node objects during scheduling simulation, otherwise if PreventPodSchedulingIfMissing is enabled globally for CSIDriver object, any newly created node may be rejected by the scheduler because of missing CSI driver information from the node.\n\nThis is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. Default is \"false\".", + "preventPodSchedulingIfMissing": "preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod scheduling if the CSI driver on the node is missing.\n\nEnabling this option will prevent the scheduler (or any other component which embeds default scheduler such as cluster-autoscaler) from scheduling pods to nodes where CSI driver is not installed.\n\nFor components(such as cluster-autoscaler) that embed the scheduler and run pod placement simulations using scheduler plugins, they MUST be aware of CSI driver registration information via CSINode object. They must create simulated CSINode objects in addition to Node objects during scheduling simulation, otherwise if PreventPodSchedulingIfMissing is enabled globally for CSIDriver object, any newly created node may be rejected by the scheduler because of missing CSI driver information from the node.\n\nThis is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. Default is \"false\".", } func (CSIDriverSpec) SwaggerDoc() map[string]string { @@ -68,8 +68,9 @@ func (CSIDriverSpec) SwaggerDoc() map[string]string { var map_CSINode = map[string]string{ "": "CSINode holds information about all CSI drivers installed on a node. CSI drivers do not need to create the CSINode object directly. As long as they use the node-driver-registrar sidecar container, the kubelet will automatically populate the CSINode object for the CSI driver as part of kubelet plugin registration. CSINode has the same name as a node. If the object is missing, it means either there are no CSI Drivers available on the node, or the Kubelet version is low enough that it doesn't create this object. CSINode has an OwnerReference that points to the corresponding node object.", - "metadata": "Standard object's metadata. metadata.name must be the Kubernetes node name.", + "metadata": "metadata is the standard object metadata. metadata.name must be the Kubernetes node name.", "spec": "spec is the specification of CSINode", + "status": "status contains health and status information for the node's storage.", } func (CSINode) SwaggerDoc() map[string]string { @@ -107,9 +108,18 @@ func (CSINodeSpec) SwaggerDoc() map[string]string { return map_CSINodeSpec } +var map_CSINodeStatus = map[string]string{ + "": "CSINodeStatus contains health and status information for storage on a node.", + "storageHealth": "storageHealth contains backend health reports for CSI drivers registered on the node.", +} + +func (CSINodeStatus) SwaggerDoc() map[string]string { + return map_CSINodeStatus +} + var map_CSIStorageCapacity = map[string]string{ "": "CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.\n\nFor example this can express things like: - StorageClass \"standard\" has \"1234 GiB\" available in \"topology.kubernetes.io/zone=us-east1\" - StorageClass \"localssd\" has \"10 GiB\" available in \"kubernetes.io/hostname=knode-abc123\"\n\nThe following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero\n\nThe producer of these objects can decide which approach is more suitable.\n\nThey are consumed by the kube-scheduler when a CSI driver opts into capacity-aware scheduling with CSIDriverSpec.StorageCapacity. The scheduler compares the MaximumVolumeSize against the requested size of pending volumes to filter out unsuitable nodes. If MaximumVolumeSize is unset, it falls back to a comparison against the less precise Capacity. If that is also unset, the scheduler assumes that capacity is insufficient and tries some other node.", - "metadata": "Standard object's metadata. The name has no particular meaning. It must be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. The name has no particular meaning. It must be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "nodeTopology": "nodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.", "storageClassName": "storageClassName represents the name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.", "capacity": "capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.\n\nThe semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable.", @@ -132,7 +142,7 @@ func (CSIStorageCapacityList) SwaggerDoc() map[string]string { var map_StorageClass = map[string]string{ "": "StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.\n\nStorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "provisioner": "provisioner indicates the type of the provisioner.", "parameters": "parameters holds the parameters for the provisioner that should create volumes of this storage class.", "reclaimPolicy": "reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. Defaults to Delete.", @@ -156,6 +166,30 @@ func (StorageClassList) SwaggerDoc() map[string]string { return map_StorageClassList } +var map_StorageHealth = map[string]string{ + "": "StorageHealth contains storage backend health reported by a CSI driver on a node.", + "name": "name is the CSI driver name, matching CSINodeDriver.name.", + "healthConditions": "healthConditions are the adverse storage backend conditions reported by the CSI driver. At most 16 conditions may be reported.", +} + +func (StorageHealth) SwaggerDoc() map[string]string { + return map_StorageHealth +} + +var map_StorageHealthCondition = map[string]string{ + "": "StorageHealthCondition represents an adverse health condition reported by a CSI driver for its storage backend on a node.", + "status": "status is the health status category. One of \"StorageUnreachable\", \"StorageDegraded\".", + "reason": "reason is a brief CamelCase machine-parseable reason. Maximum permitted length of a reason is 256 characters.", + "message": "message is a human-readable description. Maximum permitted length of a message is 1024 characters.", + "accessMode": "accessMode is the access mode affected. Nil means all access modes are affected.", + "volumeMode": "volumeMode is the volume mode affected. Nil means both are affected.", + "lastTransitionTime": "lastTransitionTime is when this condition first appeared at its current state.", +} + +func (StorageHealthCondition) SwaggerDoc() map[string]string { + return map_StorageHealthCondition +} + var map_TokenRequest = map[string]string{ "": "TokenRequest contains parameters of a service account token.", "audience": "audience is the intended audience of the token in \"TokenRequestSpec\". It will default to the audiences of kube apiserver.", @@ -168,7 +202,7 @@ func (TokenRequest) SwaggerDoc() map[string]string { var map_VolumeAttachment = map[string]string{ "": "VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.\n\nVolumeAttachment objects are non-namespaced.", - "metadata": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.", "status": "status represents status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.", } @@ -190,6 +224,7 @@ func (VolumeAttachmentList) SwaggerDoc() map[string]string { var map_VolumeAttachmentSource = map[string]string{ "": "VolumeAttachmentSource represents a volume that should be attached. Right now only PersistentVolumes can be attached via external attacher, in the future we may allow also inline volumes in pods. Exactly one member can be set.", "persistentVolumeName": "persistentVolumeName represents the name of the persistent volume to attach.", + "inlineVolumeSpec": "inlineVolumeSpec contains all the information necessary to attach a persistent volume defined by a pod's inline VolumeSource. This field is populated only for the CSIMigration feature. It contains translated fields from a pod's inline VolumeSource to a PersistentVolumeSpec. This field is beta-level and is only honored by servers that enabled the CSIMigration feature.", } func (VolumeAttachmentSource) SwaggerDoc() map[string]string { @@ -221,8 +256,8 @@ func (VolumeAttachmentStatus) SwaggerDoc() map[string]string { var map_VolumeAttributesClass = map[string]string{ "": "VolumeAttributesClass represents a specification of mutable volume attributes defined by the CSI driver. The class can be specified during dynamic provisioning of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "driverName": "Name of the CSI driver This field is immutable.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "driverName": "driverName is the name of the CSI driver This field is immutable.", "parameters": "parameters hold volume attributes defined by the CSI driver. These values are opaque to the Kubernetes and are passed directly to the CSI driver. The underlying storage provider supports changing these attributes on an existing volume, however the parameters field itself is immutable. To invoke a volume update, a new VolumeAttributesClass should be created with new parameters, and the PersistentVolumeClaim should be updated to reference the new VolumeAttributesClass.\n\nThis field is required and must contain at least one key/value pair. The keys cannot be empty, and the maximum number of parameters is 512, with a cumulative max size of 256K. If the CSI driver rejects invalid parameters, the target PersistentVolumeClaim will be set to an \"Infeasible\" state in the modifyVolumeStatus field.", } diff --git a/constraint/vendor/k8s.io/api/storage/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/storage/v1/zz_generated.deepcopy.go index aa3ffd068..1df3b4755 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/storage/v1/zz_generated.deepcopy.go @@ -166,6 +166,7 @@ func (in *CSINode) DeepCopyInto(out *CSINode) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) return } @@ -269,6 +270,29 @@ func (in *CSINodeSpec) DeepCopy() *CSINodeSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CSINodeStatus) DeepCopyInto(out *CSINodeStatus) { + *out = *in + if in.StorageHealth != nil { + in, out := &in.StorageHealth, &out.StorageHealth + *out = make([]StorageHealth, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CSINodeStatus. +func (in *CSINodeStatus) DeepCopy() *CSINodeStatus { + if in == nil { + return nil + } + out := new(CSINodeStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CSIStorageCapacity) DeepCopyInto(out *CSIStorageCapacity) { *out = *in @@ -436,6 +460,56 @@ func (in *StorageClassList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageHealth) DeepCopyInto(out *StorageHealth) { + *out = *in + if in.HealthConditions != nil { + in, out := &in.HealthConditions, &out.HealthConditions + *out = make([]StorageHealthCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageHealth. +func (in *StorageHealth) DeepCopy() *StorageHealth { + if in == nil { + return nil + } + out := new(StorageHealth) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageHealthCondition) DeepCopyInto(out *StorageHealthCondition) { + *out = *in + if in.AccessMode != nil { + in, out := &in.AccessMode, &out.AccessMode + *out = new(corev1.PersistentVolumeAccessMode) + **out = **in + } + if in.VolumeMode != nil { + in, out := &in.VolumeMode, &out.VolumeMode + *out = new(corev1.PersistentVolumeMode) + **out = **in + } + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageHealthCondition. +func (in *StorageHealthCondition) DeepCopy() *StorageHealthCondition { + if in == nil { + return nil + } + out := new(StorageHealthCondition) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TokenRequest) DeepCopyInto(out *TokenRequest) { *out = *in diff --git a/constraint/vendor/k8s.io/api/storage/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/storage/v1/zz_generated.model_name.go index 6ef637100..4eaabcbc3 100644 --- a/constraint/vendor/k8s.io/api/storage/v1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/storage/v1/zz_generated.model_name.go @@ -56,6 +56,11 @@ func (in CSINodeSpec) OpenAPIModelName() string { return "io.k8s.api.storage.v1.CSINodeSpec" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CSINodeStatus) OpenAPIModelName() string { + return "io.k8s.api.storage.v1.CSINodeStatus" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in CSIStorageCapacity) OpenAPIModelName() string { return "io.k8s.api.storage.v1.CSIStorageCapacity" @@ -76,6 +81,16 @@ func (in StorageClassList) OpenAPIModelName() string { return "io.k8s.api.storage.v1.StorageClassList" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in StorageHealth) OpenAPIModelName() string { + return "io.k8s.api.storage.v1.StorageHealth" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in StorageHealthCondition) OpenAPIModelName() string { + return "io.k8s.api.storage.v1.StorageHealthCondition" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in TokenRequest) OpenAPIModelName() string { return "io.k8s.api.storage.v1.TokenRequest" diff --git a/constraint/vendor/k8s.io/api/storage/v1alpha1/generated.proto b/constraint/vendor/k8s.io/api/storage/v1alpha1/generated.proto index 837d01164..dae07a701 100644 --- a/constraint/vendor/k8s.io/api/storage/v1alpha1/generated.proto +++ b/constraint/vendor/k8s.io/api/storage/v1alpha1/generated.proto @@ -55,7 +55,7 @@ option go_package = "k8s.io/api/storage/v1alpha1"; // the scheduler assumes that capacity is insufficient and tries some other // node. message CSIStorageCapacity { - // Standard object's metadata. The name has no particular meaning. It must be + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends @@ -127,14 +127,14 @@ message CSIStorageCapacityList { // // VolumeAttachment objects are non-namespaced. message VolumeAttachment { - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required optional VolumeAttachmentSpec spec = 2; @@ -180,9 +180,9 @@ message VolumeAttachmentSpec { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string attacher = 1; // source represents the volume that should be attached. @@ -224,12 +224,12 @@ message VolumeAttachmentStatus { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. message VolumeAttributesClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. optional string driverName = 2; diff --git a/constraint/vendor/k8s.io/api/storage/v1alpha1/types.go b/constraint/vendor/k8s.io/api/storage/v1alpha1/types.go index 286ac42aa..655dea198 100644 --- a/constraint/vendor/k8s.io/api/storage/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/api/storage/v1alpha1/types.go @@ -35,16 +35,16 @@ import ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required Spec VolumeAttachmentSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` @@ -62,7 +62,7 @@ type VolumeAttachment struct { // VolumeAttachmentList is a collection of VolumeAttachment objects. type VolumeAttachmentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -78,9 +78,9 @@ type VolumeAttachmentSpec struct { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Attacher string `json:"attacher" protobuf:"bytes,1,opt,name=attacher"` // source represents the volume that should be attached. @@ -189,9 +189,9 @@ type VolumeError struct { // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacity struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. The name has no particular meaning. It must be + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends @@ -254,7 +254,7 @@ type CSIStorageCapacity struct { // CSIStorageCapacityList is a collection of CSIStorageCapacity objects. type CSIStorageCapacityList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -276,14 +276,14 @@ type CSIStorageCapacityList struct { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName string `json:"driverName" protobuf:"bytes,2,opt,name=driverName"` @@ -310,7 +310,7 @@ type VolumeAttributesClass struct { // VolumeAttributesClassList is a collection of VolumeAttributesClass objects. type VolumeAttributesClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/storage/v1alpha1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/storage/v1alpha1/types_swagger_doc_generated.go index 713498b37..ff86ad26e 100644 --- a/constraint/vendor/k8s.io/api/storage/v1alpha1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/storage/v1alpha1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1alpha1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_CSIStorageCapacity = map[string]string{ "": "CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.\n\nFor example this can express things like: - StorageClass \"standard\" has \"1234 GiB\" available in \"topology.kubernetes.io/zone=us-east1\" - StorageClass \"localssd\" has \"10 GiB\" available in \"kubernetes.io/hostname=knode-abc123\"\n\nThe following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero\n\nThe producer of these objects can decide which approach is more suitable.\n\nThey are consumed by the kube-scheduler when a CSI driver opts into capacity-aware scheduling with CSIDriverSpec.StorageCapacity. The scheduler compares the MaximumVolumeSize against the requested size of pending volumes to filter out unsuitable nodes. If MaximumVolumeSize is unset, it falls back to a comparison against the less precise Capacity. If that is also unset, the scheduler assumes that capacity is insufficient and tries some other node.", - "metadata": "Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "nodeTopology": "nodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.", "storageClassName": "storageClassName represents the name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.", "capacity": "capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.\n\nThe semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable.", @@ -52,7 +52,7 @@ func (CSIStorageCapacityList) SwaggerDoc() map[string]string { var map_VolumeAttachment = map[string]string{ "": "VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.\n\nVolumeAttachment objects are non-namespaced.", - "metadata": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.", "status": "status represents status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.", } @@ -74,6 +74,7 @@ func (VolumeAttachmentList) SwaggerDoc() map[string]string { var map_VolumeAttachmentSource = map[string]string{ "": "VolumeAttachmentSource represents a volume that should be attached. Right now only PersistentVolumes can be attached via external attacher, in the future we may allow also inline volumes in pods. Exactly one member can be set.", "persistentVolumeName": "persistentVolumeName represents the name of the persistent volume to attach.", + "inlineVolumeSpec": "inlineVolumeSpec contains all the information necessary to attach a persistent volume defined by a pod's inline VolumeSource. This field is populated only for the CSIMigration feature. It contains translated fields from a pod's inline VolumeSource to a PersistentVolumeSpec. This field is alpha-level and is only honored by servers that enabled the CSIMigration feature.", } func (VolumeAttachmentSource) SwaggerDoc() map[string]string { @@ -105,8 +106,8 @@ func (VolumeAttachmentStatus) SwaggerDoc() map[string]string { var map_VolumeAttributesClass = map[string]string{ "": "VolumeAttributesClass represents a specification of mutable volume attributes defined by the CSI driver. The class can be specified during dynamic provisioning of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "driverName": "Name of the CSI driver This field is immutable.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "driverName": "driverName is the name of the CSI driver This field is immutable.", "parameters": "parameters hold volume attributes defined by the CSI driver. These values are opaque to the Kubernetes and are passed directly to the CSI driver. The underlying storage provider supports changing these attributes on an existing volume, however the parameters field itself is immutable. To invoke a volume update, a new VolumeAttributesClass should be created with new parameters, and the PersistentVolumeClaim should be updated to reference the new VolumeAttributesClass.\n\nThis field is required and must contain at least one key/value pair. The keys cannot be empty, and the maximum number of parameters is 512, with a cumulative max size of 256K. If the CSI driver rejects invalid parameters, the target PersistentVolumeClaim will be set to an \"Infeasible\" state in the modifyVolumeStatus field.", } diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/generated.pb.go b/constraint/vendor/k8s.io/api/storage/v1beta1/generated.pb.go index 7fd08783a..dff4bae5e 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/generated.pb.go +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/generated.pb.go @@ -49,6 +49,8 @@ func (m *CSINodeList) Reset() { *m = CSINodeList{} } func (m *CSINodeSpec) Reset() { *m = CSINodeSpec{} } +func (m *CSINodeStatus) Reset() { *m = CSINodeStatus{} } + func (m *CSIStorageCapacity) Reset() { *m = CSIStorageCapacity{} } func (m *CSIStorageCapacityList) Reset() { *m = CSIStorageCapacityList{} } @@ -57,6 +59,10 @@ func (m *StorageClass) Reset() { *m = StorageClass{} } func (m *StorageClassList) Reset() { *m = StorageClassList{} } +func (m *StorageHealth) Reset() { *m = StorageHealth{} } + +func (m *StorageHealthCondition) Reset() { *m = StorageHealthCondition{} } + func (m *TokenRequest) Reset() { *m = TokenRequest{} } func (m *VolumeAttachment) Reset() { *m = VolumeAttachment{} } @@ -315,6 +321,16 @@ func (m *CSINode) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a { size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -476,6 +492,43 @@ func (m *CSINodeSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *CSINodeStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CSINodeStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CSINodeStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.StorageHealth) > 0 { + for iNdEx := len(m.StorageHealth) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.StorageHealth[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + func (m *CSIStorageCapacity) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -753,6 +806,110 @@ func (m *StorageClassList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *StorageHealth) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageHealth) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageHealth) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.HealthConditions) > 0 { + for iNdEx := len(m.HealthConditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.HealthConditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *StorageHealthCondition) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageHealthCondition) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageHealthCondition) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.LastTransitionTime.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if m.VolumeMode != nil { + i -= len(*m.VolumeMode) + copy(dAtA[i:], *m.VolumeMode) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.VolumeMode))) + i-- + dAtA[i] = 0x2a + } + if m.AccessMode != nil { + i -= len(*m.AccessMode) + copy(dAtA[i:], *m.AccessMode) + i = encodeVarintGenerated(dAtA, i, uint64(len(*m.AccessMode))) + i-- + dAtA[i] = 0x22 + } + i -= len(m.Message) + copy(dAtA[i:], m.Message) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Message))) + i-- + dAtA[i] = 0x1a + i -= len(m.Reason) + copy(dAtA[i:], m.Reason) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Reason))) + i-- + dAtA[i] = 0x12 + i -= len(m.Status) + copy(dAtA[i:], m.Status) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Status))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *TokenRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1330,6 +1487,8 @@ func (m *CSINode) Size() (n int) { n += 1 + l + sovGenerated(uint64(l)) l = m.Spec.Size() n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -1388,6 +1547,21 @@ func (m *CSINodeSpec) Size() (n int) { return n } +func (m *CSINodeStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.StorageHealth) > 0 { + for _, e := range m.StorageHealth { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *CSIStorageCapacity) Size() (n int) { if m == nil { return 0 @@ -1491,6 +1665,48 @@ func (m *StorageClassList) Size() (n int) { return n } +func (m *StorageHealth) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Name) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.HealthConditions) > 0 { + for _, e := range m.HealthConditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *StorageHealthCondition) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Status) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + if m.AccessMode != nil { + l = len(*m.AccessMode) + n += 1 + l + sovGenerated(uint64(l)) + } + if m.VolumeMode != nil { + l = len(*m.VolumeMode) + n += 1 + l + sovGenerated(uint64(l)) + } + l = m.LastTransitionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *TokenRequest) Size() (n int) { if m == nil { return 0 @@ -1726,6 +1942,7 @@ func (this *CSINode) String() string { s := strings.Join([]string{`&CSINode{`, `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CSINodeSpec", "CSINodeSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CSINodeStatus", "CSINodeStatus", 1), `&`, ``, 1) + `,`, `}`, }, "") return s @@ -1774,6 +1991,21 @@ func (this *CSINodeSpec) String() string { }, "") return s } +func (this *CSINodeStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForStorageHealth := "[]StorageHealth{" + for _, f := range this.StorageHealth { + repeatedStringForStorageHealth += strings.Replace(strings.Replace(f.String(), "StorageHealth", "StorageHealth", 1), `&`, ``, 1) + "," + } + repeatedStringForStorageHealth += "}" + s := strings.Join([]string{`&CSINodeStatus{`, + `StorageHealth:` + repeatedStringForStorageHealth + `,`, + `}`, + }, "") + return s +} func (this *CSIStorageCapacity) String() string { if this == nil { return "nil" @@ -1852,6 +2084,37 @@ func (this *StorageClassList) String() string { }, "") return s } +func (this *StorageHealth) String() string { + if this == nil { + return "nil" + } + repeatedStringForHealthConditions := "[]StorageHealthCondition{" + for _, f := range this.HealthConditions { + repeatedStringForHealthConditions += strings.Replace(strings.Replace(f.String(), "StorageHealthCondition", "StorageHealthCondition", 1), `&`, ``, 1) + "," + } + repeatedStringForHealthConditions += "}" + s := strings.Join([]string{`&StorageHealth{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `HealthConditions:` + repeatedStringForHealthConditions + `,`, + `}`, + }, "") + return s +} +func (this *StorageHealthCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StorageHealthCondition{`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `AccessMode:` + valueToStringGenerated(this.AccessMode) + `,`, + `VolumeMode:` + valueToStringGenerated(this.VolumeMode) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.LastTransitionTime), "Time", "v1.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} func (this *TokenRequest) String() string { if this == nil { return "nil" @@ -2649,6 +2912,39 @@ func (m *CSINode) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -3053,7 +3349,7 @@ func (m *CSINodeSpec) Unmarshal(dAtA []byte) error { } return nil } -func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { +func (m *CSINodeStatus) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3076,15 +3372,15 @@ func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: CSIStorageCapacity: wiretype end group for non-group") + return fmt.Errorf("proto: CSINodeStatus: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: CSIStorageCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: CSINodeStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field StorageHealth", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -3111,30 +3407,114 @@ func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.StorageHealth = append(m.StorageHealth, StorageHealth{}) + if err := m.StorageHealth[len(m.StorageHealth)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NodeTopology", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err } - if msglen < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CSIStorageCapacity) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CSIStorageCapacity: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CSIStorageCapacity: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NodeTopology", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen @@ -3905,6 +4285,367 @@ func (m *StorageClassList) Unmarshal(dAtA []byte) error { } return nil } +func (m *StorageHealth) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageHealth: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageHealth: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field HealthConditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.HealthConditions = append(m.HealthConditions, StorageHealthCondition{}) + if err := m.HealthConditions[len(m.HealthConditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageHealthCondition) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageHealthCondition: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageHealthCondition: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Status = StorageHealthStatusType(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Reason = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AccessMode", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := k8s_io_api_core_v1.PersistentVolumeAccessMode(dAtA[iNdEx:postIndex]) + m.AccessMode = &s + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field VolumeMode", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + s := k8s_io_api_core_v1.PersistentVolumeMode(dAtA[iNdEx:postIndex]) + m.VolumeMode = &s + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastTransitionTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastTransitionTime.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *TokenRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/storage/v1beta1/generated.proto index 3cae755fb..6c8595706 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/generated.proto @@ -39,7 +39,7 @@ option go_package = "k8s.io/api/storage/v1beta1"; // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. message CSIDriver { - // Standard object metadata. + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. @@ -127,6 +127,8 @@ message CSIDriverSpec { // // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable repeated string volumeLifecycleModes = 3; // storageCapacity indicates that the CSI volume driver wants pod scheduling to consider the storage @@ -252,7 +254,7 @@ message CSIDriverSpec { // +optional optional bool serviceAccountTokenInSecrets = 10; - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -267,7 +269,7 @@ message CSIDriverSpec { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". // +featureGate=VolumeLimitScaling // +optional @@ -286,11 +288,16 @@ message CSIDriverSpec { // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. message CSINode { + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec is the specification of CSINode optional CSINodeSpec spec = 2; + + // status contains health and status information for the node's storage. + // +optional + optional CSINodeStatus status = 3; } // CSINodeDriver holds information about the specification of one CSI driver installed on a node @@ -352,6 +359,18 @@ message CSINodeSpec { repeated CSINodeDriver drivers = 1; } +// CSINodeStatus contains health and status information for storage on a node. +message CSINodeStatus { + // storageHealth contains backend health reports for CSI drivers registered on the node. + // +optional + // +listType=map + // +listMapKey=name + // +patchMergeKey=name + // +patchStrategy=merge + // +featureGate=CSIVolumeHealth + repeated StorageHealth storageHealth = 1; +} + // CSIStorageCapacity stores the result of one CSI GetCapacity call. // For a given StorageClass, this describes the available capacity in a // particular topology segment. This can be used when considering where to @@ -377,7 +396,7 @@ message CSINodeSpec { // the scheduler assumes that capacity is insufficient and tries some other // node. message CSIStorageCapacity { - // Standard object's metadata. The name has no particular meaning. It must be + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends @@ -450,29 +469,29 @@ message CSIStorageCapacityList { // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. message StorageClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // provisioner indicates the type of the provisioner. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable optional string provisioner = 2; // parameters holds the parameters for the provisioner that should // create volumes of this storage class. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional map parameters = 3; // reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. // Defaults to Delete. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional optional string reclaimPolicy = 4; // mountOptions controls the mountOptions for dynamically provisioned PersistentVolumes of this storage class. @@ -490,8 +509,8 @@ message StorageClass { // provisioned and bound. When unset, VolumeBindingImmediate is used. // This field is only honored by servers that enable the VolumeScheduling feature. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional optional string volumeBindingMode = 7; // allowedTopologies restrict the node topologies where volumes can be dynamically provisioned. @@ -514,6 +533,50 @@ message StorageClassList { repeated StorageClass items = 2; } +// StorageHealth contains storage backend health reported by a CSI driver on a node. +message StorageHealth { + // name is the CSI driver name, matching CSINodeDriver.name. + // +required + optional string name = 1; + + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + // +optional + // +listType=atomic + repeated StorageHealthCondition healthConditions = 2; +} + +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +message StorageHealthCondition { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + // +required + optional string status = 1; + + // reason is a brief CamelCase machine-parseable reason. + // +required + // Maximum permitted length of a reason is 256 characters. + optional string reason = 2; + + // message is a human-readable description. + // +optional + // Maximum permitted length of a message is 1024 characters. + optional string message = 3; + + // accessMode is the access mode affected. Nil means all access modes are affected. + // +optional + optional string accessMode = 4; + + // volumeMode is the volume mode affected. Nil means both are affected. + // +optional + optional string volumeMode = 5; + + // lastTransitionTime is when this condition first appeared at its current state. + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 6; +} + // TokenRequest contains parameters of a service account token. message TokenRequest { // audience is the intended audience of the token in "TokenRequestSpec". @@ -532,14 +595,14 @@ message TokenRequest { // // VolumeAttachment objects are non-namespaced. message VolumeAttachment { - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required optional VolumeAttachmentSpec spec = 2; @@ -585,9 +648,9 @@ message VolumeAttachmentSpec { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 optional string attacher = 1; // source represents the volume that should be attached. @@ -629,12 +692,12 @@ message VolumeAttachmentStatus { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. message VolumeAttributesClass { - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. optional string driverName = 2; diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/types.go b/constraint/vendor/k8s.io/api/storage/v1beta1/types.go index 0c33e218e..3a05ad4b3 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/types.go @@ -35,31 +35,31 @@ import ( // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. type StorageClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // provisioner indicates the type of the provisioner. // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:immutable Provisioner string `json:"provisioner" protobuf:"bytes,2,opt,name=provisioner"` // parameters holds the parameters for the provisioner that should // create volumes of this storage class. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional Parameters map[string]string `json:"parameters,omitempty" protobuf:"bytes,3,rep,name=parameters"` // reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. // Defaults to Delete. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional ReclaimPolicy *v1.PersistentVolumeReclaimPolicy `json:"reclaimPolicy,omitempty" protobuf:"bytes,4,opt,name=reclaimPolicy,casttype=k8s.io/api/core/v1.PersistentVolumeReclaimPolicy"` // mountOptions controls the mountOptions for dynamically provisioned PersistentVolumes of this storage class. @@ -77,8 +77,8 @@ type StorageClass struct { // provisioned and bound. When unset, VolumeBindingImmediate is used. // This field is only honored by servers that enable the VolumeScheduling feature. // +optional - // +k8s:alpha(since: "1.36")=+k8s:immutable - // +k8s:alpha(since: "1.36")=+k8s:optional + // +k8s:beta(since: "1.37")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:optional VolumeBindingMode *VolumeBindingMode `json:"volumeBindingMode,omitempty" protobuf:"bytes,7,opt,name=volumeBindingMode"` // allowedTopologies restrict the node topologies where volumes can be dynamically provisioned. @@ -97,7 +97,7 @@ type StorageClass struct { // StorageClassList is a collection of storage classes. type StorageClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -136,16 +136,16 @@ const ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachment struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec represents specification of the desired attach/detach volume behavior. // Populated by the Kubernetes system. - // +k8s:alpha(since: "1.36")=+k8s:immutable + // +k8s:beta(since: "1.37")=+k8s:immutable // +required Spec VolumeAttachmentSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` @@ -163,7 +163,7 @@ type VolumeAttachment struct { // VolumeAttachmentList is a collection of VolumeAttachment objects. type VolumeAttachmentList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -179,9 +179,9 @@ type VolumeAttachmentSpec struct { // attacher indicates the name of the volume driver that MUST handle this // request. This is the name returned by GetPluginName(). // +required - // +k8s:alpha(since: "1.36")=+k8s:required - // +k8s:alpha(since: "1.36")=+k8s:format="k8s-long-name-caseless" - // +k8s:alpha(since: "1.36")=+k8s:maxLength=63 + // +k8s:beta(since: "1.37")=+k8s:required + // +k8s:beta(since: "1.37")=+k8s:format="k8s-long-name-caseless" + // +k8s:beta(since: "1.37")=+k8s:maxLength=63 Attacher string `json:"attacher" protobuf:"bytes,1,opt,name=attacher"` // source represents the volume that should be attached. @@ -275,9 +275,9 @@ type VolumeError struct { // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. type CSIDriver struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object metadata. + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. @@ -298,7 +298,7 @@ type CSIDriver struct { // CSIDriverList is a collection of CSIDriver objects. type CSIDriverList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -372,6 +372,8 @@ type CSIDriverSpec struct { // // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable VolumeLifecycleModes []VolumeLifecycleMode `json:"volumeLifecycleModes,omitempty" protobuf:"bytes,3,opt,name=volumeLifecycleModes"` // storageCapacity indicates that the CSI volume driver wants pod scheduling to consider the storage @@ -497,7 +499,7 @@ type CSIDriverSpec struct { // +optional ServiceAccountTokenInSecrets *bool `json:"serviceAccountTokenInSecrets,omitempty" protobuf:"varint,10,opt,name=serviceAccountTokenInSecrets"` - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -512,7 +514,7 @@ type CSIDriverSpec struct { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". // +featureGate=VolumeLimitScaling // +optional @@ -591,6 +593,7 @@ const ( // +k8s:prerelease-lifecycle-gen:deprecated=1.17 // +k8s:prerelease-lifecycle-gen:removed=1.22 // +k8s:prerelease-lifecycle-gen:replacement=storage.k8s.io,v1,CSINode +// +k8s:supportsSubresource="/status" // DEPRECATED - This group version of CSINode is deprecated by storage/v1/CSINode. // See the release notes for more information. @@ -604,13 +607,18 @@ const ( // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. type CSINode struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec is the specification of CSINode Spec CSINodeSpec `json:"spec" protobuf:"bytes,2,opt,name=spec"` + + // status contains health and status information for the node's storage. + // +optional + Status CSINodeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // CSINodeSpec holds information about the specification of all CSI drivers installed on a node @@ -671,6 +679,67 @@ type VolumeNodeResources struct { Count *int32 `json:"count,omitempty" protobuf:"varint,1,opt,name=count"` } +// StorageHealthStatusType describes the health status category of a storage backend. +// +enum +type StorageHealthStatusType string + +const ( + // StorageUnreachable indicates the storage backend is unreachable. + StorageUnreachable StorageHealthStatusType = "StorageUnreachable" + // StorageDegraded indicates the storage backend is functioning with reduced capability. + StorageDegraded StorageHealthStatusType = "StorageDegraded" +) + +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +type StorageHealthCondition struct { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + // +required + Status StorageHealthStatusType `json:"status" protobuf:"bytes,1,opt,name=status,casttype=StorageHealthStatusType"` + // reason is a brief CamelCase machine-parseable reason. + // +required + // Maximum permitted length of a reason is 256 characters. + Reason string `json:"reason" protobuf:"bytes,2,opt,name=reason"` + // message is a human-readable description. + // +optional + // Maximum permitted length of a message is 1024 characters. + Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` + // accessMode is the access mode affected. Nil means all access modes are affected. + // +optional + AccessMode *v1.PersistentVolumeAccessMode `json:"accessMode,omitempty" protobuf:"bytes,4,opt,name=accessMode,casttype=k8s.io/api/core/v1.PersistentVolumeAccessMode"` + // volumeMode is the volume mode affected. Nil means both are affected. + // +optional + VolumeMode *v1.PersistentVolumeMode `json:"volumeMode,omitempty" protobuf:"bytes,5,opt,name=volumeMode,casttype=k8s.io/api/core/v1.PersistentVolumeMode"` + // lastTransitionTime is when this condition first appeared at its current state. + // +optional + LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,6,opt,name=lastTransitionTime"` +} + +// StorageHealth contains storage backend health reported by a CSI driver on a node. +type StorageHealth struct { + // name is the CSI driver name, matching CSINodeDriver.name. + // +required + Name string `json:"name" protobuf:"bytes,1,opt,name=name"` + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + // +optional + // +listType=atomic + HealthConditions []StorageHealthCondition `json:"healthConditions,omitempty" protobuf:"bytes,2,rep,name=healthConditions"` +} + +// CSINodeStatus contains health and status information for storage on a node. +type CSINodeStatus struct { + // storageHealth contains backend health reports for CSI drivers registered on the node. + // +optional + // +listType=map + // +listMapKey=name + // +patchMergeKey=name + // +patchStrategy=merge + // +featureGate=CSIVolumeHealth + StorageHealth []StorageHealth `json:"storageHealth,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,1,rep,name=storageHealth"` +} + // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.14 // +k8s:prerelease-lifecycle-gen:deprecated=1.17 @@ -679,7 +748,7 @@ type VolumeNodeResources struct { // CSINodeList is a collection of CSINode objects. type CSINodeList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -721,9 +790,9 @@ type CSINodeList struct { // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacity struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. The name has no particular meaning. It must be + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends @@ -786,7 +855,7 @@ type CSIStorageCapacity struct { // CSIStorageCapacityList is a collection of CSIStorageCapacity objects. type CSIStorageCapacityList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -808,14 +877,14 @@ type CSIStorageCapacityList struct { // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClass struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` - // Standard object's metadata. + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName string `json:"driverName" protobuf:"bytes,2,opt,name=driverName"` @@ -842,7 +911,7 @@ type VolumeAttributesClass struct { // VolumeAttributesClassList is a collection of VolumeAttributesClass objects. type VolumeAttributesClassList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/storage/v1beta1/types_swagger_doc_generated.go index 80b68839b..8a12d1f8c 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/types_swagger_doc_generated.go +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/types_swagger_doc_generated.go @@ -29,7 +29,7 @@ package v1beta1 // AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. var map_CSIDriver = map[string]string{ "": "CSIDriver captures information about a Container Storage Interface (CSI) volume driver deployed on the cluster. CSI drivers do not need to create the CSIDriver object directly. Instead they may use the cluster-driver-registrar sidecar container. When deployed with a CSI driver it automatically creates a CSIDriver object representing the driver. Kubernetes attach detach controller uses this object to determine whether attach is required. Kubelet uses this object to determine whether pod information needs to be passed on mount. CSIDriver objects are non-namespaced.", - "metadata": "Standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents the specification of the CSI Driver.", } @@ -59,7 +59,7 @@ var map_CSIDriverSpec = map[string]string{ "seLinuxMount": "seLinuxMount specifies if the CSI driver supports \"-o context\" mount option.\n\nWhen \"true\", the CSI driver must ensure that all volumes provided by this CSI driver can be mounted separately with different `-o context` options. This is typical for storage backends that provide volumes as filesystems on block devices or as independent shared volumes. Kubernetes will call NodeStage / NodePublish with \"-o context=xyz\" mount option when mounting a ReadWriteOncePod volume used in Pod that has explicitly set SELinux context. In the future, it may be expanded to other volume AccessModes. In any case, Kubernetes will ensure that the volume is mounted only with a single SELinux context.\n\nWhen \"false\", Kubernetes won't pass any special SELinux mount options to the driver. This is typical for volumes that represent subdirectories of a bigger shared filesystem.\n\nDefault is \"false\".", "nodeAllocatableUpdatePeriodSeconds": "nodeAllocatableUpdatePeriodSeconds specifies the interval between periodic updates of the CSINode allocatable capacity for this driver. When set, both periodic updates and updates triggered by capacity-related failures are enabled. If not set, no updates occur (neither periodic nor upon detecting capacity-related failures), and the allocatable.count remains static. The minimum allowed value for this field is 10 seconds.\n\nThis is a beta feature and requires the MutableCSINodeAllocatableCount feature gate to be enabled.\n\nThis field is mutable.", "serviceAccountTokenInSecrets": "serviceAccountTokenInSecrets is an opt-in for CSI drivers to indicate that service account tokens should be passed via the Secrets field in NodePublishVolumeRequest instead of the VolumeContext field. The CSI specification provides a dedicated Secrets field for sensitive information like tokens, which is the appropriate mechanism for handling credentials. This addresses security concerns where sensitive tokens were being logged as part of volume context.\n\nWhen \"true\", kubelet will pass the tokens only in the Secrets field with the key \"csi.storage.k8s.io/serviceAccount.tokens\". The CSI driver must be updated to read tokens from the Secrets field instead of VolumeContext.\n\nWhen \"false\" or not set, kubelet will pass the tokens in VolumeContext with the key \"csi.storage.k8s.io/serviceAccount.tokens\" (existing behavior). This maintains backward compatibility with existing CSI drivers.\n\nThis field can only be set when TokenRequests is configured. The API server will reject CSIDriver specs that set this field without TokenRequests.\n\nDefault behavior if unset is to pass tokens in the VolumeContext field.", - "preventPodSchedulingIfMissing": "PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod scheduling if the CSI driver on the node is missing.\n\nEnabling this option will prevent the scheduler (or any other component which embeds default scheduler such as cluster-autoscaler) from scheduling pods to nodes where CSI driver is not installed.\n\nFor components(such as cluster-autoscaler) that embed the scheduler and run pod placement simulations using scheduler plugins, they MUST be aware of CSI driver registration information via CSINode object. They must create simulated CSINode objects in addition to Node objects during scheduling simulation, otherwise if PreventPodSchedulingIfMissing is enabled globally for CSIDriver object, any newly created node may be rejected by the scheduler because of missing CSI driver information from the node.\n\nThis is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. Default is \"false\".", + "preventPodSchedulingIfMissing": "preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod scheduling if the CSI driver on the node is missing.\n\nEnabling this option will prevent the scheduler (or any other component which embeds default scheduler such as cluster-autoscaler) from scheduling pods to nodes where CSI driver is not installed.\n\nFor components(such as cluster-autoscaler) that embed the scheduler and run pod placement simulations using scheduler plugins, they MUST be aware of CSI driver registration information via CSINode object. They must create simulated CSINode objects in addition to Node objects during scheduling simulation, otherwise if PreventPodSchedulingIfMissing is enabled globally for CSIDriver object, any newly created node may be rejected by the scheduler because of missing CSI driver information from the node.\n\nThis is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. Default is \"false\".", } func (CSIDriverSpec) SwaggerDoc() map[string]string { @@ -68,8 +68,9 @@ func (CSIDriverSpec) SwaggerDoc() map[string]string { var map_CSINode = map[string]string{ "": "DEPRECATED - This group version of CSINode is deprecated by storage/v1/CSINode. See the release notes for more information. CSINode holds information about all CSI drivers installed on a node. CSI drivers do not need to create the CSINode object directly. As long as they use the node-driver-registrar sidecar container, the kubelet will automatically populate the CSINode object for the CSI driver as part of kubelet plugin registration. CSINode has the same name as a node. If the object is missing, it means either there are no CSI Drivers available on the node, or the Kubelet version is low enough that it doesn't create this object. CSINode has an OwnerReference that points to the corresponding node object.", - "metadata": "metadata.name must be the Kubernetes node name.", + "metadata": "metadata is the standard object metadata. metadata.name must be the Kubernetes node name.", "spec": "spec is the specification of CSINode", + "status": "status contains health and status information for the node's storage.", } func (CSINode) SwaggerDoc() map[string]string { @@ -107,9 +108,18 @@ func (CSINodeSpec) SwaggerDoc() map[string]string { return map_CSINodeSpec } +var map_CSINodeStatus = map[string]string{ + "": "CSINodeStatus contains health and status information for storage on a node.", + "storageHealth": "storageHealth contains backend health reports for CSI drivers registered on the node.", +} + +func (CSINodeStatus) SwaggerDoc() map[string]string { + return map_CSINodeStatus +} + var map_CSIStorageCapacity = map[string]string{ "": "CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.\n\nFor example this can express things like: - StorageClass \"standard\" has \"1234 GiB\" available in \"topology.kubernetes.io/zone=us-east1\" - StorageClass \"localssd\" has \"10 GiB\" available in \"kubernetes.io/hostname=knode-abc123\"\n\nThe following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero\n\nThe producer of these objects can decide which approach is more suitable.\n\nThey are consumed by the kube-scheduler when a CSI driver opts into capacity-aware scheduling with CSIDriverSpec.StorageCapacity. The scheduler compares the MaximumVolumeSize against the requested size of pending volumes to filter out unsuitable nodes. If MaximumVolumeSize is unset, it falls back to a comparison against the less precise Capacity. If that is also unset, the scheduler assumes that capacity is insufficient and tries some other node.", - "metadata": "Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-, a generated name, or a reverse-domain name which ends with the unique CSI driver name.\n\nObjects are namespaced.\n\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "nodeTopology": "nodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.", "storageClassName": "storageClassName represents the name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.", "capacity": "capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.\n\nThe semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable.", @@ -132,7 +142,7 @@ func (CSIStorageCapacityList) SwaggerDoc() map[string]string { var map_StorageClass = map[string]string{ "": "StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.\n\nStorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "provisioner": "provisioner indicates the type of the provisioner.", "parameters": "parameters holds the parameters for the provisioner that should create volumes of this storage class.", "reclaimPolicy": "reclaimPolicy controls the reclaimPolicy for dynamically provisioned PersistentVolumes of this storage class. Defaults to Delete.", @@ -156,6 +166,30 @@ func (StorageClassList) SwaggerDoc() map[string]string { return map_StorageClassList } +var map_StorageHealth = map[string]string{ + "": "StorageHealth contains storage backend health reported by a CSI driver on a node.", + "name": "name is the CSI driver name, matching CSINodeDriver.name.", + "healthConditions": "healthConditions are the adverse storage backend conditions reported by the CSI driver. At most 16 conditions may be reported.", +} + +func (StorageHealth) SwaggerDoc() map[string]string { + return map_StorageHealth +} + +var map_StorageHealthCondition = map[string]string{ + "": "StorageHealthCondition represents an adverse health condition reported by a CSI driver for its storage backend on a node.", + "status": "status is the health status category. One of \"StorageUnreachable\", \"StorageDegraded\".", + "reason": "reason is a brief CamelCase machine-parseable reason. Maximum permitted length of a reason is 256 characters.", + "message": "message is a human-readable description. Maximum permitted length of a message is 1024 characters.", + "accessMode": "accessMode is the access mode affected. Nil means all access modes are affected.", + "volumeMode": "volumeMode is the volume mode affected. Nil means both are affected.", + "lastTransitionTime": "lastTransitionTime is when this condition first appeared at its current state.", +} + +func (StorageHealthCondition) SwaggerDoc() map[string]string { + return map_StorageHealthCondition +} + var map_TokenRequest = map[string]string{ "": "TokenRequest contains parameters of a service account token.", "audience": "audience is the intended audience of the token in \"TokenRequestSpec\". It will default to the audiences of kube apiserver.", @@ -168,7 +202,7 @@ func (TokenRequest) SwaggerDoc() map[string]string { var map_VolumeAttachment = map[string]string{ "": "VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.\n\nVolumeAttachment objects are non-namespaced.", - "metadata": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", "spec": "spec represents specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.", "status": "status represents status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.", } @@ -190,6 +224,7 @@ func (VolumeAttachmentList) SwaggerDoc() map[string]string { var map_VolumeAttachmentSource = map[string]string{ "": "VolumeAttachmentSource represents a volume that should be attached. Right now only PersistentVolumes can be attached via external attacher, in the future we may allow also inline volumes in pods. Exactly one member can be set.", "persistentVolumeName": "persistentVolumeName represents the name of the persistent volume to attach.", + "inlineVolumeSpec": "inlineVolumeSpec contains all the information necessary to attach a persistent volume defined by a pod's inline VolumeSource. This field is populated only for the CSIMigration feature. It contains translated fields from a pod's inline VolumeSource to a PersistentVolumeSpec. This field is beta-level and is only honored by servers that enabled the CSIMigration feature.", } func (VolumeAttachmentSource) SwaggerDoc() map[string]string { @@ -221,8 +256,8 @@ func (VolumeAttachmentStatus) SwaggerDoc() map[string]string { var map_VolumeAttributesClass = map[string]string{ "": "VolumeAttributesClass represents a specification of mutable volume attributes defined by the CSI driver. The class can be specified during dynamic provisioning of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning.", - "metadata": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - "driverName": "Name of the CSI driver This field is immutable.", + "metadata": "metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "driverName": "driverName is the name of the CSI driver This field is immutable.", "parameters": "parameters hold volume attributes defined by the CSI driver. These values are opaque to the Kubernetes and are passed directly to the CSI driver. The underlying storage provider supports changing these attributes on an existing volume, however the parameters field itself is immutable. To invoke a volume update, a new VolumeAttributesClass should be created with new parameters, and the PersistentVolumeClaim should be updated to reference the new VolumeAttributesClass.\n\nThis field is required and must contain at least one key/value pair. The keys cannot be empty, and the maximum number of parameters is 512, with a cumulative max size of 256K. If the CSI driver rejects invalid parameters, the target PersistentVolumeClaim will be set to an \"Infeasible\" state in the modifyVolumeStatus field.", } diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.deepcopy.go index ca28e0340..88b058178 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.deepcopy.go +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.deepcopy.go @@ -166,6 +166,7 @@ func (in *CSINode) DeepCopyInto(out *CSINode) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) return } @@ -269,6 +270,29 @@ func (in *CSINodeSpec) DeepCopy() *CSINodeSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CSINodeStatus) DeepCopyInto(out *CSINodeStatus) { + *out = *in + if in.StorageHealth != nil { + in, out := &in.StorageHealth, &out.StorageHealth + *out = make([]StorageHealth, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CSINodeStatus. +func (in *CSINodeStatus) DeepCopy() *CSINodeStatus { + if in == nil { + return nil + } + out := new(CSINodeStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CSIStorageCapacity) DeepCopyInto(out *CSIStorageCapacity) { *out = *in @@ -436,6 +460,56 @@ func (in *StorageClassList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageHealth) DeepCopyInto(out *StorageHealth) { + *out = *in + if in.HealthConditions != nil { + in, out := &in.HealthConditions, &out.HealthConditions + *out = make([]StorageHealthCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageHealth. +func (in *StorageHealth) DeepCopy() *StorageHealth { + if in == nil { + return nil + } + out := new(StorageHealth) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageHealthCondition) DeepCopyInto(out *StorageHealthCondition) { + *out = *in + if in.AccessMode != nil { + in, out := &in.AccessMode, &out.AccessMode + *out = new(corev1.PersistentVolumeAccessMode) + **out = **in + } + if in.VolumeMode != nil { + in, out := &in.VolumeMode, &out.VolumeMode + *out = new(corev1.PersistentVolumeMode) + **out = **in + } + in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageHealthCondition. +func (in *StorageHealthCondition) DeepCopy() *StorageHealthCondition { + if in == nil { + return nil + } + out := new(StorageHealthCondition) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TokenRequest) DeepCopyInto(out *TokenRequest) { *out = *in diff --git a/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.model_name.go index 8453d86b2..fe654676b 100644 --- a/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/storage/v1beta1/zz_generated.model_name.go @@ -56,6 +56,11 @@ func (in CSINodeSpec) OpenAPIModelName() string { return "io.k8s.api.storage.v1beta1.CSINodeSpec" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in CSINodeStatus) OpenAPIModelName() string { + return "io.k8s.api.storage.v1beta1.CSINodeStatus" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in CSIStorageCapacity) OpenAPIModelName() string { return "io.k8s.api.storage.v1beta1.CSIStorageCapacity" @@ -76,6 +81,16 @@ func (in StorageClassList) OpenAPIModelName() string { return "io.k8s.api.storage.v1beta1.StorageClassList" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in StorageHealth) OpenAPIModelName() string { + return "io.k8s.api.storage.v1beta1.StorageHealth" +} + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in StorageHealthCondition) OpenAPIModelName() string { + return "io.k8s.api.storage.v1beta1.StorageHealthCondition" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in TokenRequest) OpenAPIModelName() string { return "io.k8s.api.storage.v1beta1.TokenRequest" diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/doc.go b/constraint/vendor/k8s.io/api/storagemigration/v1/doc.go similarity index 81% rename from constraint/vendor/k8s.io/api/apidiscovery/v2beta1/doc.go rename to constraint/vendor/k8s.io/api/storagemigration/v1/doc.go index 244986bb4..4c122fa5c 100644 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/doc.go +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kubernetes Authors. +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. @@ -18,8 +18,8 @@ limitations under the License. // +k8s:protobuf-gen=package // +k8s:openapi-gen=true // +k8s:prerelease-lifecycle-gen=true -// +k8s:openapi-model-package=io.k8s.api.apidiscovery.v2beta1 +// +k8s:openapi-model-package=io.k8s.api.storagemigration.v1 -// +groupName=apidiscovery.k8s.io +// +groupName=storagemigration.k8s.io -package v2beta1 +package v1 diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/generated.pb.go b/constraint/vendor/k8s.io/api/storagemigration/v1/generated.pb.go new file mode 100644 index 000000000..9f4e58652 --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/generated.pb.go @@ -0,0 +1,904 @@ +/* +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 protoc-gen-gogo. DO NOT EDIT. +// source: k8s.io/api/storagemigration/v1/generated.proto + +package v1 + +import ( + fmt "fmt" + + io "io" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + math_bits "math/bits" + reflect "reflect" + strings "strings" +) + +func (m *StorageVersionMigration) Reset() { *m = StorageVersionMigration{} } + +func (m *StorageVersionMigrationList) Reset() { *m = StorageVersionMigrationList{} } + +func (m *StorageVersionMigrationSpec) Reset() { *m = StorageVersionMigrationSpec{} } + +func (m *StorageVersionMigrationStatus) Reset() { *m = StorageVersionMigrationStatus{} } + +func (m *StorageVersionMigration) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageVersionMigration) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageVersionMigration) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Status.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.Spec.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.ObjectMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *StorageVersionMigrationList) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageVersionMigrationList) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageVersionMigrationList) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Items) > 0 { + for iNdEx := len(m.Items) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Items[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.ListMeta.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *StorageVersionMigrationSpec) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageVersionMigrationSpec) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageVersionMigrationSpec) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Resource.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *StorageVersionMigrationStatus) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StorageVersionMigrationStatus) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StorageVersionMigrationStatus) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.ResourceVersion) + copy(dAtA[i:], m.ResourceVersion) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.ResourceVersion))) + i-- + dAtA[i] = 0x12 + if len(m.Conditions) > 0 { + for iNdEx := len(m.Conditions) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Conditions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *StorageVersionMigration) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *StorageVersionMigrationList) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *StorageVersionMigrationSpec) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Resource.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *StorageVersionMigrationStatus) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + l = len(m.ResourceVersion) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func sovGenerated(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *StorageVersionMigration) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StorageVersionMigration{`, + `ObjectMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ObjectMeta), "ObjectMeta", "v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "StorageVersionMigrationSpec", "StorageVersionMigrationSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "StorageVersionMigrationStatus", "StorageVersionMigrationStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *StorageVersionMigrationList) String() string { + if this == nil { + return "nil" + } + repeatedStringForItems := "[]StorageVersionMigration{" + for _, f := range this.Items { + repeatedStringForItems += strings.Replace(strings.Replace(f.String(), "StorageVersionMigration", "StorageVersionMigration", 1), `&`, ``, 1) + "," + } + repeatedStringForItems += "}" + s := strings.Join([]string{`&StorageVersionMigrationList{`, + `ListMeta:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ListMeta), "ListMeta", "v1.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + repeatedStringForItems + `,`, + `}`, + }, "") + return s +} +func (this *StorageVersionMigrationSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StorageVersionMigrationSpec{`, + `Resource:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Resource), "GroupResource", "v1.GroupResource", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *StorageVersionMigrationStatus) String() string { + if this == nil { + return "nil" + } + repeatedStringForConditions := "[]Condition{" + for _, f := range this.Conditions { + repeatedStringForConditions += fmt.Sprintf("%v", f) + "," + } + repeatedStringForConditions += "}" + s := strings.Join([]string{`&StorageVersionMigrationStatus{`, + `Conditions:` + repeatedStringForConditions + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *StorageVersionMigration) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageVersionMigration: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageVersionMigration: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageVersionMigrationList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageVersionMigrationList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageVersionMigrationList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, StorageVersionMigration{}) + if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageVersionMigrationSpec) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageVersionMigrationSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageVersionMigrationSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Resource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageVersionMigrationStatus) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageVersionMigrationStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageVersionMigrationStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, v1.Condition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ResourceVersion", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenerated + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ResourceVersion = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenerated(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenerated + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenerated + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenerated + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") +) diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/generated.proto b/constraint/vendor/k8s.io/api/storagemigration/v1/generated.proto new file mode 100644 index 000000000..ada3c1511 --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/generated.proto @@ -0,0 +1,86 @@ +/* +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. +*/ + + +// This file was autogenerated by go-to-protobuf. Do not edit it manually! + +syntax = "proto2"; + +package k8s.io.api.storagemigration.v1; + +import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/generated.proto"; +import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; + +// Package-wide variables from generator "generated". +option go_package = "k8s.io/api/storagemigration/v1"; + +// StorageVersionMigration represents a migration of stored data to the latest +// storage version. +// +k8s:supportsSubresource="/status" +message StorageVersionMigration { + // Standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; + + // Specification of the migration. + // +optional + optional StorageVersionMigrationSpec spec = 2; + + // Status of the migration. + // +optional + optional StorageVersionMigrationStatus status = 3; +} + +// StorageVersionMigrationList is a collection of storage version migrations. +message StorageVersionMigrationList { + // Standard list metadata + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + optional .k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; + + // Items is the list of StorageVersionMigration + repeated StorageVersionMigration items = 2; +} + +// Spec of the storage version migration. +message StorageVersionMigrationSpec { + // The resource that is being migrated. The migrator sends requests to + // the endpoint serving the resource. + // Immutable. + optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupResource resource = 1; +} + +// Status of the storage version migration. +message StorageVersionMigrationStatus { + // The latest available observations of the migration's current state. + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; + + // ResourceVersion to compare with the GC cache for performing the migration. + // This is the current resource version of given group, version and resource when + // kube-controller-manager first observes this StorageVersionMigration resource. + optional string resourceVersion = 2; +} + diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/register.go b/constraint/vendor/k8s.io/api/storagemigration/v1/register.go similarity index 77% rename from constraint/vendor/k8s.io/api/apidiscovery/v2beta1/register.go rename to constraint/vendor/k8s.io/api/storagemigration/v1/register.go index f7cef1081..d03db0c4d 100644 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/register.go +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kubernetes Authors. +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. @@ -14,19 +14,20 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v2beta1 +package v1 import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// GroupName is the group name for this API. -const GroupName = "apidiscovery.k8s.io" +// GroupName is the group name use in this package +const GroupName = "storagemigration.k8s.io" // SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v2beta1"} +var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"} // Kind takes an unqualified kind and returns a Group qualified GroupKind func Kind(kind string) schema.GroupKind { @@ -39,18 +40,19 @@ func Resource(resource string) schema.GroupResource { } var ( - // SchemeBuilder installs the api group to a scheme - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - // AddToScheme adds api to a scheme - AddToScheme = SchemeBuilder.AddToScheme + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + localSchemeBuilder = &SchemeBuilder + AddToScheme = localSchemeBuilder.AddToScheme ) // Adds the list of known types to the given scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, - &APIGroupDiscoveryList{}, - &APIGroupDiscovery{}, + &StorageVersionMigration{}, + &StorageVersionMigrationList{}, ) + + // Add the watch version that applies metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil } diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/types.go b/constraint/vendor/k8s.io/api/storagemigration/v1/types.go new file mode 100644 index 000000000..cead67439 --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/types.go @@ -0,0 +1,95 @@ +/* +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 v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +genclient +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// StorageVersionMigration represents a migration of stored data to the latest +// storage version. +// +k8s:supportsSubresource="/status" +type StorageVersionMigration struct { + metav1.TypeMeta `json:""` + // Standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + // Specification of the migration. + // +optional + Spec StorageVersionMigrationSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` + // Status of the migration. + // +optional + Status StorageVersionMigrationStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// Spec of the storage version migration. +type StorageVersionMigrationSpec struct { + // The resource that is being migrated. The migrator sends requests to + // the endpoint serving the resource. + // Immutable. + Resource metav1.GroupResource `json:"resource" protobuf:"bytes,1,opt,name=resource"` +} + +type MigrationConditionType string + +const ( + // Indicates that the migration is running. + MigrationRunning MigrationConditionType = "Running" + // Indicates that the migration has completed successfully. + MigrationSucceeded MigrationConditionType = "Succeeded" + // Indicates that the migration has failed. + MigrationFailed MigrationConditionType = "Failed" +) + +// Status of the storage version migration. +type StorageVersionMigrationStatus struct { + // The latest available observations of the migration's current state. + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` + // ResourceVersion to compare with the GC cache for performing the migration. + // This is the current resource version of given group, version and resource when + // kube-controller-manager first observes this StorageVersionMigration resource. + ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,2,opt,name=resourceVersion"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:prerelease-lifecycle-gen:introduced=1.37 + +// StorageVersionMigrationList is a collection of storage version migrations. +type StorageVersionMigrationList struct { + metav1.TypeMeta `json:""` + + // Standard list metadata + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + // Items is the list of StorageVersionMigration + Items []StorageVersionMigration `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/types_swagger_doc_generated.go b/constraint/vendor/k8s.io/api/storagemigration/v1/types_swagger_doc_generated.go new file mode 100644 index 000000000..a9ff380d8 --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/types_swagger_doc_generated.go @@ -0,0 +1,70 @@ +/* +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 v1 + +// This file contains a collection of methods that can be used from go-restful to +// generate Swagger API documentation for its models. Please read this PR for more +// information on the implementation: https://github.com/emicklei/go-restful/pull/215 +// +// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if +// they are on one line! For multiple line or blocks that you want to ignore use ---. +// Any context after a --- is ignored. +// +// Those methods can be generated by using hack/update-codegen.sh + +// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. +var map_StorageVersionMigration = map[string]string{ + "": "StorageVersionMigration represents a migration of stored data to the latest storage version.", + "metadata": "Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "spec": "Specification of the migration.", + "status": "Status of the migration.", +} + +func (StorageVersionMigration) SwaggerDoc() map[string]string { + return map_StorageVersionMigration +} + +var map_StorageVersionMigrationList = map[string]string{ + "": "StorageVersionMigrationList is a collection of storage version migrations.", + "metadata": "Standard list metadata More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", + "items": "Items is the list of StorageVersionMigration", +} + +func (StorageVersionMigrationList) SwaggerDoc() map[string]string { + return map_StorageVersionMigrationList +} + +var map_StorageVersionMigrationSpec = map[string]string{ + "": "Spec of the storage version migration.", + "resource": "The resource that is being migrated. The migrator sends requests to the endpoint serving the resource. Immutable.", +} + +func (StorageVersionMigrationSpec) SwaggerDoc() map[string]string { + return map_StorageVersionMigrationSpec +} + +var map_StorageVersionMigrationStatus = map[string]string{ + "": "Status of the storage version migration.", + "conditions": "The latest available observations of the migration's current state.", + "resourceVersion": "ResourceVersion to compare with the GC cache for performing the migration. This is the current resource version of given group, version and resource when kube-controller-manager first observes this StorageVersionMigration resource.", +} + +func (StorageVersionMigrationStatus) SwaggerDoc() map[string]string { + return map_StorageVersionMigrationStatus +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.deepcopy.go b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.deepcopy.go new file mode 100644 index 000000000..10ef04a08 --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.deepcopy.go @@ -0,0 +1,128 @@ +//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 deepcopy-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageVersionMigration) DeepCopyInto(out *StorageVersionMigration) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageVersionMigration. +func (in *StorageVersionMigration) DeepCopy() *StorageVersionMigration { + if in == nil { + return nil + } + out := new(StorageVersionMigration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *StorageVersionMigration) 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 *StorageVersionMigrationList) DeepCopyInto(out *StorageVersionMigrationList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]StorageVersionMigration, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageVersionMigrationList. +func (in *StorageVersionMigrationList) DeepCopy() *StorageVersionMigrationList { + if in == nil { + return nil + } + out := new(StorageVersionMigrationList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *StorageVersionMigrationList) 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 *StorageVersionMigrationSpec) DeepCopyInto(out *StorageVersionMigrationSpec) { + *out = *in + out.Resource = in.Resource + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageVersionMigrationSpec. +func (in *StorageVersionMigrationSpec) DeepCopy() *StorageVersionMigrationSpec { + if in == nil { + return nil + } + out := new(StorageVersionMigrationSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StorageVersionMigrationStatus) DeepCopyInto(out *StorageVersionMigrationStatus) { + *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]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageVersionMigrationStatus. +func (in *StorageVersionMigrationStatus) DeepCopy() *StorageVersionMigrationStatus { + if in == nil { + return nil + } + out := new(StorageVersionMigrationStatus) + in.DeepCopyInto(out) + return out +} diff --git a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.model_name.go b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.model_name.go similarity index 57% rename from constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.model_name.go rename to constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.model_name.go index 8054db78a..3c5ff9ded 100644 --- a/constraint/vendor/k8s.io/api/apidiscovery/v2beta1/zz_generated.model_name.go +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.model_name.go @@ -19,29 +19,24 @@ limitations under the License. // Code generated by openapi-gen. DO NOT EDIT. -package v2beta1 +package v1 // OpenAPIModelName returns the OpenAPI model name for this type. -func (in APIGroupDiscovery) OpenAPIModelName() string { - return "io.k8s.api.apidiscovery.v2beta1.APIGroupDiscovery" +func (in StorageVersionMigration) OpenAPIModelName() string { + return "io.k8s.api.storagemigration.v1.StorageVersionMigration" } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in APIGroupDiscoveryList) OpenAPIModelName() string { - return "io.k8s.api.apidiscovery.v2beta1.APIGroupDiscoveryList" +func (in StorageVersionMigrationList) OpenAPIModelName() string { + return "io.k8s.api.storagemigration.v1.StorageVersionMigrationList" } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in APIResourceDiscovery) OpenAPIModelName() string { - return "io.k8s.api.apidiscovery.v2beta1.APIResourceDiscovery" +func (in StorageVersionMigrationSpec) OpenAPIModelName() string { + return "io.k8s.api.storagemigration.v1.StorageVersionMigrationSpec" } // OpenAPIModelName returns the OpenAPI model name for this type. -func (in APISubresourceDiscovery) OpenAPIModelName() string { - return "io.k8s.api.apidiscovery.v2beta1.APISubresourceDiscovery" -} - -// OpenAPIModelName returns the OpenAPI model name for this type. -func (in APIVersionDiscovery) OpenAPIModelName() string { - return "io.k8s.api.apidiscovery.v2beta1.APIVersionDiscovery" +func (in StorageVersionMigrationStatus) OpenAPIModelName() string { + return "io.k8s.api.storagemigration.v1.StorageVersionMigrationStatus" } diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.prerelease-lifecycle.go new file mode 100644 index 000000000..64eaaedde --- /dev/null +++ b/constraint/vendor/k8s.io/api/storagemigration/v1/zz_generated.prerelease-lifecycle.go @@ -0,0 +1,34 @@ +//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 prerelease-lifecycle-gen. DO NOT EDIT. + +package v1 + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *StorageVersionMigration) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} + +// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. +// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. +func (in *StorageVersionMigrationList) APILifecycleIntroduced() (major, minor int) { + return 1, 37 +} diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/generated.proto b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/generated.proto index d7d08d88c..21fc7eab6 100644 --- a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/generated.proto +++ b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/generated.proto @@ -30,6 +30,7 @@ option go_package = "k8s.io/api/storagemigration/v1beta1"; // StorageVersionMigration represents a migration of stored data to the latest // storage version. +// +k8s:supportsSubresource="/status" message StorageVersionMigration { // Standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -72,6 +73,9 @@ message StorageVersionMigrationStatus { // +listType=map // +listMapKey=type // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type repeated .k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 1; // ResourceVersion to compare with the GC cache for performing the migration. diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/types.go b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/types.go index 9655f737a..bbbbe9f54 100644 --- a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/types.go +++ b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/types.go @@ -24,11 +24,14 @@ import ( // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.35 +// +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=storagemigration.k8s.io,v1,StorageVersionMigration // StorageVersionMigration represents a migration of stored data to the latest // storage version. +// +k8s:supportsSubresource="/status" type StorageVersionMigration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -68,6 +71,9 @@ type StorageVersionMigrationStatus struct { // +listType=map // +listMapKey=type // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:listType=map + // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // ResourceVersion to compare with the GC cache for performing the migration. // This is the current resource version of given group, version and resource when @@ -77,10 +83,12 @@ type StorageVersionMigrationStatus struct { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:prerelease-lifecycle-gen:introduced=1.35 +// +k8s:prerelease-lifecycle-gen:deprecated=1.37 +// +k8s:prerelease-lifecycle-gen:replacement=storagemigration.k8s.io,v1,StorageVersionMigrationList // StorageVersionMigrationList is a collection of storage version migrations. type StorageVersionMigrationList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard list metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/zz_generated.prerelease-lifecycle.go b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/zz_generated.prerelease-lifecycle.go index f52614f7d..5962412fb 100644 --- a/constraint/vendor/k8s.io/api/storagemigration/v1beta1/zz_generated.prerelease-lifecycle.go +++ b/constraint/vendor/k8s.io/api/storagemigration/v1beta1/zz_generated.prerelease-lifecycle.go @@ -21,6 +21,10 @@ limitations under the License. package v1beta1 +import ( + schema "k8s.io/apimachinery/pkg/runtime/schema" +) + // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. func (in *StorageVersionMigration) APILifecycleIntroduced() (major, minor int) { @@ -30,13 +34,19 @@ func (in *StorageVersionMigration) APILifecycleIntroduced() (major, minor int) { // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *StorageVersionMigration) APILifecycleDeprecated() (major, minor int) { - return 1, 38 + return 1, 37 +} + +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *StorageVersionMigration) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "storagemigration.k8s.io", Version: "v1", Kind: "StorageVersionMigration"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *StorageVersionMigration) APILifecycleRemoved() (major, minor int) { - return 1, 41 + return 1, 40 } // APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. @@ -48,11 +58,17 @@ func (in *StorageVersionMigrationList) APILifecycleIntroduced() (major, minor in // APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. func (in *StorageVersionMigrationList) APILifecycleDeprecated() (major, minor int) { - return 1, 38 + return 1, 37 +} + +// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. +// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. +func (in *StorageVersionMigrationList) APILifecycleReplacement() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "storagemigration.k8s.io", Version: "v1", Kind: "StorageVersionMigrationList"} } // APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. // It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. func (in *StorageVersionMigrationList) APILifecycleRemoved() (major, minor int) { - return 1, 41 + return 1, 40 } diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go index b3a8ce7ef..c0e968886 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types.go @@ -402,7 +402,7 @@ const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s. // CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format // <.spec.name>.<.spec.group>. type CustomResourceDefinition struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -420,7 +420,7 @@ type CustomResourceDefinition struct { // CustomResourceDefinitionList is a list of CustomResourceDefinition objects. type CustomResourceDefinitionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -489,7 +489,7 @@ type CustomResourceSubresourceScale struct { // ConversionReview describes a conversion request/response. type ConversionReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // request describes the attributes for the conversion request. // +optional Request *ConversionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go index 4d02c8df0..29639388d 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/zz_generated.conversion.go @@ -276,12 +276,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -291,12 +286,7 @@ func Convert_v1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceCo } func autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -351,12 +341,7 @@ func Convert_apiextensions_CustomResourceDefinition_To_v1_CustomResourceDefiniti } func autoConvert_v1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = apiextensions.CustomResourceDefinitionConditionType(in.Type) - out.Status = apiextensions.ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -366,12 +351,7 @@ func Convert_v1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourc } func autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = CustomResourceDefinitionConditionType(in.Type) - out.Status = ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -423,12 +403,7 @@ func Convert_apiextensions_CustomResourceDefinitionList_To_v1_CustomResourceDefi } func autoConvert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*apiextensions.CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -438,12 +413,7 @@ func Convert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDef } func autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -522,12 +492,7 @@ func autoConvert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResource } func autoConvert_v1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_v1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -537,12 +502,7 @@ func Convert_v1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDe } func autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -604,9 +564,7 @@ func Convert_apiextensions_CustomResourceDefinitionVersion_To_v1_CustomResourceD } func autoConvert_v1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -616,9 +574,7 @@ func Convert_v1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSu } func autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -628,6 +584,7 @@ func Convert_apiextensions_CustomResourceSubresourceScale_To_v1_CustomResourceSu } func autoConvert_v1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -637,6 +594,7 @@ func Convert_v1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceS } func autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -646,8 +604,7 @@ func Convert_apiextensions_CustomResourceSubresourceStatus_To_v1_CustomResourceS } func autoConvert_v1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -657,8 +614,7 @@ func Convert_v1_CustomResourceSubresources_To_apiextensions_CustomResourceSubres } func autoConvert_apiextensions_CustomResourceSubresources_To_v1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -704,8 +660,7 @@ func Convert_apiextensions_CustomResourceValidation_To_v1_CustomResourceValidati } func autoConvert_v1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*apiextensions.ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -715,8 +670,7 @@ func Convert_v1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in } func autoConvert_apiextensions_ExternalDocumentation_To_v1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -1243,7 +1197,7 @@ func Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1_JSONSchemaPropsOrS } func autoConvert_v1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*apiextensions.SelectableField)(unsafe.Pointer(in)) return nil } @@ -1253,7 +1207,7 @@ func Convert_v1_SelectableField_To_apiextensions_SelectableField(in *SelectableF } func autoConvert_apiextensions_SelectableField_To_v1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*SelectableField)(unsafe.Pointer(in)) return nil } @@ -1293,12 +1247,7 @@ func Convert_apiextensions_ServiceReference_To_v1_ServiceReference(in *apiextens } func autoConvert_v1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*apiextensions.FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*apiextensions.ValidationRule)(unsafe.Pointer(in)) return nil } @@ -1308,12 +1257,7 @@ func Convert_v1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRul } func autoConvert_apiextensions_ValidationRule_To_v1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*ValidationRule)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go index fb844903e..e92c715a7 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types.go @@ -442,7 +442,7 @@ const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s. // <.spec.name>.<.spec.group>. // Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead. type CustomResourceDefinition struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional @@ -463,7 +463,7 @@ type CustomResourceDefinition struct { // CustomResourceDefinitionList is a list of CustomResourceDefinition objects. type CustomResourceDefinitionList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata @@ -536,7 +536,7 @@ type CustomResourceSubresourceScale struct { // ConversionReview describes a conversion request/response. type ConversionReview struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // request describes the attributes for the conversion request. // +optional Request *ConversionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go index 5e388dc69..85e1836c1 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/zz_generated.conversion.go @@ -271,12 +271,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResourceColumnDefinition(in *CustomResourceColumnDefinition, out *apiextensions.CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*apiextensions.CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -286,12 +281,7 @@ func Convert_v1beta1_CustomResourceColumnDefinition_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceColumnDefinition_To_v1beta1_CustomResourceColumnDefinition(in *apiextensions.CustomResourceColumnDefinition, out *CustomResourceColumnDefinition, s conversion.Scope) error { - out.Name = in.Name - out.Type = in.Type - out.Format = in.Format - out.Description = in.Description - out.Priority = in.Priority - out.JSONPath = in.JSONPath + *out = *(*CustomResourceColumnDefinition)(unsafe.Pointer(in)) return nil } @@ -373,12 +363,7 @@ func Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDef } func autoConvert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomResourceDefinitionCondition(in *CustomResourceDefinitionCondition, out *apiextensions.CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = apiextensions.CustomResourceDefinitionConditionType(in.Type) - out.Status = apiextensions.ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -388,12 +373,7 @@ func Convert_v1beta1_CustomResourceDefinitionCondition_To_apiextensions_CustomRe } func autoConvert_apiextensions_CustomResourceDefinitionCondition_To_v1beta1_CustomResourceDefinitionCondition(in *apiextensions.CustomResourceDefinitionCondition, out *CustomResourceDefinitionCondition, s conversion.Scope) error { - out.Type = CustomResourceDefinitionConditionType(in.Type) - out.Status = ConditionStatus(in.Status) - out.LastTransitionTime = in.LastTransitionTime - out.Reason = in.Reason - out.Message = in.Message - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionCondition)(unsafe.Pointer(in)) return nil } @@ -445,12 +425,7 @@ func Convert_apiextensions_CustomResourceDefinitionList_To_v1beta1_CustomResourc } func autoConvert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(in *CustomResourceDefinitionNames, out *apiextensions.CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*apiextensions.CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -460,12 +435,7 @@ func Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResour } func autoConvert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(in *apiextensions.CustomResourceDefinitionNames, out *CustomResourceDefinitionNames, s conversion.Scope) error { - out.Plural = in.Plural - out.Singular = in.Singular - out.ShortNames = *(*[]string)(unsafe.Pointer(&in.ShortNames)) - out.Kind = in.Kind - out.ListKind = in.ListKind - out.Categories = *(*[]string)(unsafe.Pointer(&in.Categories)) + *out = *(*CustomResourceDefinitionNames)(unsafe.Pointer(in)) return nil } @@ -571,12 +541,7 @@ func Convert_apiextensions_CustomResourceDefinitionSpec_To_v1beta1_CustomResourc } func autoConvert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResourceDefinitionStatus(in *CustomResourceDefinitionStatus, out *apiextensions.CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]apiextensions.CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_v1beta1_CustomResourceDefinitionNames_To_apiextensions_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*apiextensions.CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -586,12 +551,7 @@ func Convert_v1beta1_CustomResourceDefinitionStatus_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceDefinitionStatus_To_v1beta1_CustomResourceDefinitionStatus(in *apiextensions.CustomResourceDefinitionStatus, out *CustomResourceDefinitionStatus, s conversion.Scope) error { - out.Conditions = *(*[]CustomResourceDefinitionCondition)(unsafe.Pointer(&in.Conditions)) - if err := Convert_apiextensions_CustomResourceDefinitionNames_To_v1beta1_CustomResourceDefinitionNames(&in.AcceptedNames, &out.AcceptedNames, s); err != nil { - return err - } - out.StoredVersions = *(*[]string)(unsafe.Pointer(&in.StoredVersions)) - out.ObservedGeneration = in.ObservedGeneration + *out = *(*CustomResourceDefinitionStatus)(unsafe.Pointer(in)) return nil } @@ -653,9 +613,7 @@ func Convert_apiextensions_CustomResourceDefinitionVersion_To_v1beta1_CustomReso } func autoConvert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(in *CustomResourceSubresourceScale, out *apiextensions.CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -665,9 +623,7 @@ func Convert_v1beta1_CustomResourceSubresourceScale_To_apiextensions_CustomResou } func autoConvert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResourceSubresourceScale(in *apiextensions.CustomResourceSubresourceScale, out *CustomResourceSubresourceScale, s conversion.Scope) error { - out.SpecReplicasPath = in.SpecReplicasPath - out.StatusReplicasPath = in.StatusReplicasPath - out.LabelSelectorPath = (*string)(unsafe.Pointer(in.LabelSelectorPath)) + *out = *(*CustomResourceSubresourceScale)(unsafe.Pointer(in)) return nil } @@ -677,6 +633,7 @@ func Convert_apiextensions_CustomResourceSubresourceScale_To_v1beta1_CustomResou } func autoConvert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(in *CustomResourceSubresourceStatus, out *apiextensions.CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -686,6 +643,7 @@ func Convert_v1beta1_CustomResourceSubresourceStatus_To_apiextensions_CustomReso } func autoConvert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomResourceSubresourceStatus(in *apiextensions.CustomResourceSubresourceStatus, out *CustomResourceSubresourceStatus, s conversion.Scope) error { + *out = *(*CustomResourceSubresourceStatus)(unsafe.Pointer(in)) return nil } @@ -695,8 +653,7 @@ func Convert_apiextensions_CustomResourceSubresourceStatus_To_v1beta1_CustomReso } func autoConvert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceSubresources(in *CustomResourceSubresources, out *apiextensions.CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*apiextensions.CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*apiextensions.CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*apiextensions.CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -706,8 +663,7 @@ func Convert_v1beta1_CustomResourceSubresources_To_apiextensions_CustomResourceS } func autoConvert_apiextensions_CustomResourceSubresources_To_v1beta1_CustomResourceSubresources(in *apiextensions.CustomResourceSubresources, out *CustomResourceSubresources, s conversion.Scope) error { - out.Status = (*CustomResourceSubresourceStatus)(unsafe.Pointer(in.Status)) - out.Scale = (*CustomResourceSubresourceScale)(unsafe.Pointer(in.Scale)) + *out = *(*CustomResourceSubresources)(unsafe.Pointer(in)) return nil } @@ -753,8 +709,7 @@ func Convert_apiextensions_CustomResourceValidation_To_v1beta1_CustomResourceVal } func autoConvert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentation(in *ExternalDocumentation, out *apiextensions.ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*apiextensions.ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -764,8 +719,7 @@ func Convert_v1beta1_ExternalDocumentation_To_apiextensions_ExternalDocumentatio } func autoConvert_apiextensions_ExternalDocumentation_To_v1beta1_ExternalDocumentation(in *apiextensions.ExternalDocumentation, out *ExternalDocumentation, s conversion.Scope) error { - out.Description = in.Description - out.URL = in.URL + *out = *(*ExternalDocumentation)(unsafe.Pointer(in)) return nil } @@ -1292,7 +1246,7 @@ func Convert_apiextensions_JSONSchemaPropsOrStringArray_To_v1beta1_JSONSchemaPro } func autoConvert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *SelectableField, out *apiextensions.SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*apiextensions.SelectableField)(unsafe.Pointer(in)) return nil } @@ -1302,7 +1256,7 @@ func Convert_v1beta1_SelectableField_To_apiextensions_SelectableField(in *Select } func autoConvert_apiextensions_SelectableField_To_v1beta1_SelectableField(in *apiextensions.SelectableField, out *SelectableField, s conversion.Scope) error { - out.JSONPath = in.JSONPath + *out = *(*SelectableField)(unsafe.Pointer(in)) return nil } @@ -1342,12 +1296,7 @@ func Convert_apiextensions_ServiceReference_To_v1beta1_ServiceReference(in *apie } func autoConvert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *ValidationRule, out *apiextensions.ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*apiextensions.FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*apiextensions.ValidationRule)(unsafe.Pointer(in)) return nil } @@ -1357,12 +1306,7 @@ func Convert_v1beta1_ValidationRule_To_apiextensions_ValidationRule(in *Validati } func autoConvert_apiextensions_ValidationRule_To_v1beta1_ValidationRule(in *apiextensions.ValidationRule, out *ValidationRule, s conversion.Scope) error { - out.Rule = in.Rule - out.Message = in.Message - out.MessageExpression = in.MessageExpression - out.Reason = (*FieldValueErrorReason)(unsafe.Pointer(in.Reason)) - out.FieldPath = in.FieldPath - out.OptionalOldSelf = (*bool)(unsafe.Pointer(in.OptionalOldSelf)) + *out = *(*ValidationRule)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go index 89051e2af..0775833f3 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go @@ -38,6 +38,7 @@ import ( structuraldefaulting "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting" apiservervalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" apiequality "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/operation" genericvalidation "k8s.io/apimachinery/pkg/api/validation" "k8s.io/apimachinery/pkg/util/sets" utilvalidation "k8s.io/apimachinery/pkg/util/validation" @@ -45,6 +46,8 @@ import ( celconfig "k8s.io/apiserver/pkg/apis/cel" apiservercel "k8s.io/apiserver/pkg/cel" "k8s.io/apiserver/pkg/cel/environment" + "k8s.io/apiserver/pkg/features" + utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/apiserver/pkg/util/webhook" ) @@ -71,7 +74,6 @@ var supportedValidationReason = sets.NewString( ) // ValidateCustomResourceDefinition statically validates -// context is passed for supporting context cancellation during cel validation when validating defaults func ValidateCustomResourceDefinition(ctx context.Context, obj *apiextensions.CustomResourceDefinition) field.ErrorList { nameValidationFn := func(name string, prefix bool) []string { ret := genericvalidation.NameIsDNSSubdomain(name, prefix) @@ -97,7 +99,7 @@ func ValidateCustomResourceDefinition(ctx context.Context, obj *apiextensions.Cu allowInvalidCABundle: true, } - allErrs := genericvalidation.ValidateObjectMeta(&obj.ObjectMeta, false, nameValidationFn, field.NewPath("metadata")) + allErrs := genericvalidation.ValidateObjectMetaDeclaratively(ctx, operation.Create, &obj.ObjectMeta, nil, false, nameValidationFn, field.NewPath("metadata"), utilfeature.DefaultFeatureGate.Enabled(features.DeclarativeValidationBeta)) allErrs = append(allErrs, validateCustomResourceDefinitionSpec(ctx, &obj.Spec, opts, field.NewPath("spec"))...) allErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(&obj.Status, field.NewPath("status"))...) allErrs = append(allErrs, ValidateCustomResourceDefinitionStoredVersions(obj.Status.StoredVersions, obj.Spec.Versions, field.NewPath("status").Child("storedVersions"))...) @@ -248,7 +250,7 @@ func ValidateCustomResourceDefinitionUpdate(ctx context.Context, obj, oldObj *ap } func validateCustomResourceDefinitionUpdate(ctx context.Context, obj, oldObj *apiextensions.CustomResourceDefinition, opts validationOptions) field.ErrorList { - allErrs := genericvalidation.ValidateObjectMetaUpdate(&obj.ObjectMeta, &oldObj.ObjectMeta, field.NewPath("metadata")) + allErrs := genericvalidation.ValidateObjectMetaDeclaratively(ctx, operation.Update, &obj.ObjectMeta, &oldObj.ObjectMeta, false, nil, field.NewPath("metadata"), utilfeature.DefaultFeatureGate.Enabled(features.DeclarativeValidationBeta)) allErrs = append(allErrs, validateCustomResourceDefinitionSpecUpdate(ctx, &obj.Spec, &oldObj.Spec, opts, field.NewPath("spec"))...) allErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(&obj.Status, field.NewPath("status"))...) allErrs = append(allErrs, ValidateCustomResourceDefinitionStoredVersions(obj.Status.StoredVersions, obj.Spec.Versions, field.NewPath("status").Child("storedVersions"))...) @@ -284,9 +286,9 @@ func ValidateCustomResourceDefinitionStoredVersions(storedVersions []string, ver return allErrs } -// ValidateUpdateCustomResourceDefinitionStatus statically validates -func ValidateUpdateCustomResourceDefinitionStatus(obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList { - allErrs := genericvalidation.ValidateObjectMetaUpdate(&obj.ObjectMeta, &oldObj.ObjectMeta, field.NewPath("metadata")) +// ValidateUpdateCustomResourceDefinitionStatus statically validates custom resource definition status update. +func ValidateUpdateCustomResourceDefinitionStatus(ctx context.Context, obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList { + allErrs := genericvalidation.ValidateObjectMetaDeclaratively(ctx, operation.Update, &obj.ObjectMeta, &oldObj.ObjectMeta, false, nil, field.NewPath("metadata"), utilfeature.DefaultFeatureGate.Enabled(features.DeclarativeValidationBeta)) allErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(&obj.Status, field.NewPath("status"))...) return allErrs } diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go index f1c5ad9e9..1a548e2c6 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go @@ -17,6 +17,7 @@ limitations under the License. package model import ( + apimachineryvalidation "k8s.io/apimachinery/pkg/util/validation" apiservercel "k8s.io/apiserver/pkg/cel" "k8s.io/apiserver/pkg/cel/common" @@ -62,14 +63,32 @@ func WithTypeAndObjectMeta(s *schema.Structural) *schema.Structural { stringType := schema.Structural{Generic: schema.Generic{Type: "string"}} props["kind"] = stringType props["apiVersion"] = stringType + metadataProps := s.Properties["metadata"].Properties props["metadata"] = schema.Structural{ Generic: schema.Generic{Type: "object"}, Properties: map[string]schema.Structural{ - "name": stringType, - "generateName": stringType, + "name": cappedLengthStringType(metadataProps["name"], nameMaxLength), + "generateName": cappedLengthStringType(metadataProps["generateName"], nameMaxLength-1), // The generated suffix is at least 1 byte }, } result.Properties = props return result } + +// nameMaxLength is the default maxLength applied to metadata.name. +const nameMaxLength = int64(apimachineryvalidation.DNS1123SubdomainMaxLength) + +// cappedLengthStringType returns a string type whose max length is capped at maxLength, +// using the existing schema's maxLength instead when it is shorter. +func cappedLengthStringType(existing schema.Structural, maxLength int64) schema.Structural { + if existing.ValueValidation != nil && existing.ValueValidation.MaxLength != nil { + if *existing.ValueValidation.MaxLength < maxLength { + maxLength = *existing.ValueValidation.MaxLength + } + } + return schema.Structural{ + Generic: schema.Generic{Type: "string"}, + ValueValidation: &schema.ValueValidation{MaxLength: &maxLength}, + } +} diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go index e529d5a3e..830df17be 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go @@ -87,7 +87,7 @@ func validate(ctx context.Context, pth *field.Path, s *structuralschema.Structur // check ObjectMeta/TypeMeta and everything else if err := schemaobjectmeta.Coerce(nil, obj, rootSchema, true, false); err != nil { allErrs = append(allErrs, field.Invalid(pth.Child("default"), s.Default.Object, fmt.Sprintf("must result in valid metadata: %v", err))) - } else if errs := schemaobjectmeta.Validate(nil, obj, rootSchema, true); len(errs) > 0 { + } else if errs := schemaobjectmeta.Validate(ctx, nil, obj, rootSchema, true); len(errs) > 0 { allErrs = append(allErrs, field.Invalid(pth.Child("default"), s.Default.Object, fmt.Sprintf("must result in valid metadata: %v", errs.ToAggregate()))) } else if errs := apiservervalidation.ValidateCustomResource(pth.Child("default"), s.Default.Object, validator); len(errs) > 0 { allErrs = append(allErrs, errs...) @@ -131,7 +131,7 @@ func validate(ctx context.Context, pth *field.Path, s *structuralschema.Structur // check ObjectMeta/TypeMeta and everything else if err := schemaobjectmeta.Coerce(pth.Child("default"), s.Default.Object, s, s.XEmbeddedResource, false); err != nil { allErrs = append(allErrs, err) - } else if errs := schemaobjectmeta.Validate(pth.Child("default"), s.Default.Object, s, s.XEmbeddedResource); len(errs) > 0 { + } else if errs := schemaobjectmeta.Validate(ctx, pth.Child("default"), s.Default.Object, s, s.XEmbeddedResource); len(errs) > 0 { allErrs = append(allErrs, errs...) } else if errs := apiservervalidation.ValidateCustomResource(pth.Child("default"), s.Default.Object, validator); len(errs) > 0 { allErrs = append(allErrs, errs...) diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go index ce4a6036d..b0999261e 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go @@ -17,19 +17,23 @@ limitations under the License. package objectmeta import ( + "context" "strings" structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/api/validate/content" metavalidation "k8s.io/apimachinery/pkg/api/validation" "k8s.io/apimachinery/pkg/runtime/schema" utilvalidation "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/features" + utilfeature "k8s.io/apiserver/pkg/util/feature" ) // Validate validates embedded ObjectMeta and TypeMeta. // It also validate those at the root if isResourceRoot is true. -func Validate(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool) field.ErrorList { +func Validate(ctx context.Context, pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool) field.ErrorList { if isResourceRoot { if s == nil { s = &structuralschema.Structural{} @@ -40,10 +44,10 @@ func Validate(pth *field.Path, obj interface{}, s *structuralschema.Structural, s = &clone } } - return validate(pth, obj, s) + return validate(ctx, pth, obj, s) } -func validate(pth *field.Path, x interface{}, s *structuralschema.Structural) field.ErrorList { +func validate(ctx context.Context, pth *field.Path, x interface{}, s *structuralschema.Structural) field.ErrorList { if s == nil { return nil } @@ -53,20 +57,20 @@ func validate(pth *field.Path, x interface{}, s *structuralschema.Structural) fi switch x := x.(type) { case map[string]interface{}: if s.XEmbeddedResource { - allErrs = append(allErrs, validateEmbeddedResource(pth, x, s)...) + allErrs = append(allErrs, validateEmbeddedResource(ctx, pth, x, s)...) } for k, v := range x { prop, ok := s.Properties[k] if ok { - allErrs = append(allErrs, validate(pth.Child(k), v, &prop)...) + allErrs = append(allErrs, validate(ctx, pth.Child(k), v, &prop)...) } else if s.AdditionalProperties != nil { - allErrs = append(allErrs, validate(pth.Key(k), v, s.AdditionalProperties.Structural)...) + allErrs = append(allErrs, validate(ctx, pth.Key(k), v, s.AdditionalProperties.Structural)...) } } case []interface{}: for i, v := range x { - allErrs = append(allErrs, validate(pth.Index(i), v, s.Items)...) + allErrs = append(allErrs, validate(ctx, pth.Index(i), v, s.Items)...) } default: // scalars, do nothing @@ -82,7 +86,7 @@ func validatePathSegment(name string, prefix bool) []string { return content.IsPathSegmentName(name) } -func validateEmbeddedResource(pth *field.Path, x map[string]interface{}, s *structuralschema.Structural) field.ErrorList { +func validateEmbeddedResource(ctx context.Context, pth *field.Path, x map[string]interface{}, s *structuralschema.Structural) field.ErrorList { var allErrs field.ErrorList // require apiVersion and kind, but not metadata @@ -119,7 +123,7 @@ func validateEmbeddedResource(pth *field.Path, x map[string]interface{}, s *stru if len(meta.Name) == 0 { meta.Name = "fakename" // we have to set something to avoid an error } - allErrs = append(allErrs, metavalidation.ValidateObjectMeta(meta, len(meta.Namespace) > 0, validatePathSegment, pth.Child("metadata"))...) + allErrs = append(allErrs, metavalidation.ValidateObjectMetaDeclaratively(ctx, operation.Create, meta, nil, len(meta.Namespace) > 0, validatePathSegment, pth.Child("metadata"), utilfeature.DefaultFeatureGate.Enabled(features.DeclarativeValidationBeta))...) } } } diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/metrics.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/metrics.go index 7dcc7938e..b5920af68 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/metrics.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/metrics.go @@ -17,6 +17,7 @@ limitations under the License. package validation import ( + "sync" "time" "k8s.io/component-base/metrics" @@ -45,8 +46,15 @@ var Metrics ValidationMetrics = &validationMetrics{ }), } -func init() { - legacyregistry.MustRegister(Metrics.(*validationMetrics).RatchetingTime) +var registerMetricsOnce sync.Once + +// RegisterMetrics registers the validation metrics with the legacy registry. It is invoked when the validation +// metrics are installed into the handler chain (rather than from an init() function), so that metric feature gates +// such as NativeHistograms have been applied before these histogram metrics are created. +func RegisterMetrics() { + registerMetricsOnce.Do(func() { + legacyregistry.MustRegister(Metrics.(*validationMetrics).RatchetingTime) + }) } type validationMetrics struct { diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go index 4884c2523..0fd3d5369 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1/customresourcedefinition.go @@ -19,8 +19,11 @@ limitations under the License. package v1 import ( + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + internal "k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal" apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" metav1 "k8s.io/client-go/applyconfigurations/meta/v1" ) @@ -30,7 +33,7 @@ import ( // CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format // <.spec.name>.<.spec.group>. type CustomResourceDefinitionApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` @@ -50,6 +53,46 @@ func CustomResourceDefinition(name string) *CustomResourceDefinitionApplyConfigu return b } +// ExtractCustomResourceDefinitionFrom extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinitionFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinitionFrom(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string, subresource string) (*CustomResourceDefinitionApplyConfiguration, error) { + b := &CustomResourceDefinitionApplyConfiguration{} + err := managedfields.ExtractInto(customResourceDefinition, internal.Parser().Type("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(customResourceDefinition.Name) + + b.WithKind("CustomResourceDefinition") + b.WithAPIVersion("apiextensions.k8s.io/v1") + return b, nil +} + +// ExtractCustomResourceDefinition extracts the applied configuration owned by fieldManager from +// customResourceDefinition. If no managedFields are found in customResourceDefinition for fieldManager, a +// CustomResourceDefinitionApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinition provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinition(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "") +} + +// ExtractCustomResourceDefinitionStatus extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the status subresource. +func ExtractCustomResourceDefinitionStatus(customResourceDefinition *apiextensionsv1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "status") +} + func (b CustomResourceDefinitionApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go index 4838dafcb..19a7711af 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1/customresourcedefinition.go @@ -19,8 +19,11 @@ limitations under the License. package v1beta1 import ( + apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + internal "k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" v1 "k8s.io/client-go/applyconfigurations/meta/v1" ) @@ -31,7 +34,7 @@ import ( // <.spec.name>.<.spec.group>. // Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead. type CustomResourceDefinitionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` @@ -51,6 +54,46 @@ func CustomResourceDefinition(name string) *CustomResourceDefinitionApplyConfigu return b } +// ExtractCustomResourceDefinitionFrom extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinitionFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinitionFrom(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string, subresource string) (*CustomResourceDefinitionApplyConfiguration, error) { + b := &CustomResourceDefinitionApplyConfiguration{} + err := managedfields.ExtractInto(customResourceDefinition, internal.Parser().Type("io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinition"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(customResourceDefinition.Name) + + b.WithKind("CustomResourceDefinition") + b.WithAPIVersion("apiextensions.k8s.io/v1beta1") + return b, nil +} + +// ExtractCustomResourceDefinition extracts the applied configuration owned by fieldManager from +// customResourceDefinition. If no managedFields are found in customResourceDefinition for fieldManager, a +// CustomResourceDefinitionApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// customResourceDefinition must be a unmodified CustomResourceDefinition API object that was retrieved from the Kubernetes API. +// ExtractCustomResourceDefinition provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCustomResourceDefinition(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "") +} + +// ExtractCustomResourceDefinitionStatus extracts the applied configuration owned by fieldManager from +// customResourceDefinition for the status subresource. +func ExtractCustomResourceDefinitionStatus(customResourceDefinition *apiextensionsv1beta1.CustomResourceDefinition, fieldManager string) (*CustomResourceDefinitionApplyConfiguration, error) { + return ExtractCustomResourceDefinitionFrom(customResourceDefinition, fieldManager, "status") +} + func (b CustomResourceDefinitionApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go new file mode 100644 index 000000000..04927b835 --- /dev/null +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal/internal.go @@ -0,0 +1,1250 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package internal + +import ( + fmt "fmt" + sync "sync" + + typed "sigs.k8s.io/structured-merge-diff/v6/typed" +) + +func Parser() *typed.Parser { + parserOnce.Do(func() { + var err error + parser, err = typed.NewParser(schemaYAML) + if err != nil { + panic(fmt.Sprintf("Failed to parse schema: %v", err)) + } + }) + return parser +} + +var parserOnce sync.Once +var parser *typed.Parser +var schemaYAML = typed.YAMLObject(`types: +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceColumnDefinition + map: + fields: + - name: description + type: + scalar: string + - name: format + type: + scalar: string + - name: jsonPath + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceConversion + map: + fields: + - name: strategy + type: + scalar: string + default: "" + - name: webhook + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionSpec + default: {} + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionStatus + default: {} +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionCondition + map: + fields: + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: observedGeneration + type: + scalar: numeric + - name: reason + type: + scalar: string + - name: status + type: + scalar: string + default: "" + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + map: + fields: + - name: categories + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: kind + type: + scalar: string + default: "" + - name: listKind + type: + scalar: string + - name: plural + type: + scalar: string + default: "" + - name: shortNames + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: singular + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionSpec + map: + fields: + - name: conversion + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceConversion + - name: group + type: + scalar: string + default: "" + - name: names + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + default: {} + - name: preserveUnknownFields + type: + scalar: boolean + - name: scope + type: + scalar: string + default: "" + - name: versions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionVersion + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionStatus + map: + fields: + - name: acceptedNames + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionNames + default: {} + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionCondition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric + - name: storedVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionVersion + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: deprecated + type: + scalar: boolean + - name: deprecationWarning + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceValidation + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.SelectableField + elementRelationship: atomic + - name: served + type: + scalar: boolean + default: false + - name: storage + type: + scalar: boolean + default: false + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresources +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceScale + map: + fields: + - name: labelSelectorPath + type: + scalar: string + - name: specReplicasPath + type: + scalar: string + default: "" + - name: statusReplicasPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceStatus + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresources + map: + fields: + - name: scale + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceScale + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceSubresourceStatus +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceValidation + map: + fields: + - name: openAPIV3Schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ExternalDocumentation + map: + fields: + - name: description + type: + scalar: string + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + map: + fields: + - name: $ref + type: + scalar: string + - name: $schema + type: + scalar: string + - name: additionalItems + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + - name: additionalProperties + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + - name: allOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: anyOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: default + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + - name: definitions + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: dependencies + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrStringArray + - name: description + type: + scalar: string + - name: enum + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + elementRelationship: atomic + - name: example + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSON + - name: exclusiveMaximum + type: + scalar: boolean + - name: exclusiveMinimum + type: + scalar: boolean + - name: externalDocs + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ExternalDocumentation + - name: format + type: + scalar: string + - name: id + type: + scalar: string + - name: items + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrArray + - name: maxItems + type: + scalar: numeric + - name: maxLength + type: + scalar: numeric + - name: maxProperties + type: + scalar: numeric + - name: maximum + type: + scalar: numeric + - name: minItems + type: + scalar: numeric + - name: minLength + type: + scalar: numeric + - name: minProperties + type: + scalar: numeric + - name: minimum + type: + scalar: numeric + - name: multipleOf + type: + scalar: numeric + - name: not + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: nullable + type: + scalar: boolean + - name: oneOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + elementRelationship: atomic + - name: pattern + type: + scalar: string + - name: patternProperties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: properties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaProps + - name: required + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: title + type: + scalar: string + - name: type + type: + scalar: string + - name: uniqueItems + type: + scalar: boolean + - name: x-kubernetes-embedded-resource + type: + scalar: boolean + - name: x-kubernetes-int-or-string + type: + scalar: boolean + - name: x-kubernetes-list-map-keys + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: x-kubernetes-list-type + type: + scalar: string + - name: x-kubernetes-map-type + type: + scalar: string + - name: x-kubernetes-preserve-unknown-fields + type: + scalar: boolean + - name: x-kubernetes-validations + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ValidationRule + elementRelationship: associative + keys: + - rule +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrBool + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.JSONSchemaPropsOrStringArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.SelectableField + map: + fields: + - name: jsonPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ServiceReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: namespace + type: + scalar: string + default: "" + - name: path + type: + scalar: string + - name: port + type: + scalar: numeric +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ValidationRule + map: + fields: + - name: fieldPath + type: + scalar: string + - name: message + type: + scalar: string + - name: messageExpression + type: + scalar: string + - name: optionalOldSelf + type: + scalar: boolean + - name: reason + type: + scalar: string + - name: rule + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookClientConfig + map: + fields: + - name: caBundle + type: + scalar: string + - name: service + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.ServiceReference + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion + map: + fields: + - name: clientConfig + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookClientConfig + - name: conversionReviewVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + map: + fields: + - name: JSONPath + type: + scalar: string + default: "" + - name: description + type: + scalar: string + - name: format + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceConversion + map: + fields: + - name: conversionReviewVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: strategy + type: + scalar: string + default: "" + - name: webhookClientConfig + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.WebhookClientConfig +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinition + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionSpec + default: {} + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus + default: {} +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionCondition + map: + fields: + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: observedGeneration + type: + scalar: numeric + - name: reason + type: + scalar: string + - name: status + type: + scalar: string + default: "" + - name: type + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + map: + fields: + - name: categories + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: kind + type: + scalar: string + default: "" + - name: listKind + type: + scalar: string + - name: plural + type: + scalar: string + default: "" + - name: shortNames + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: singular + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionSpec + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: conversion + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceConversion + - name: group + type: + scalar: string + default: "" + - name: names + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + default: {} + - name: preserveUnknownFields + type: + scalar: boolean + - name: scope + type: + scalar: string + default: "" + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + elementRelationship: atomic + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources + - name: validation + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + - name: version + type: + scalar: string + - name: versions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionVersion + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus + map: + fields: + - name: acceptedNames + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionNames + default: {} + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionCondition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric + - name: storedVersions + type: + list: + elementType: + scalar: string + elementRelationship: atomic +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionVersion + map: + fields: + - name: additionalPrinterColumns + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceColumnDefinition + elementRelationship: atomic + - name: deprecated + type: + scalar: boolean + - name: deprecationWarning + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + - name: selectableFields + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + elementRelationship: atomic + - name: served + type: + scalar: boolean + default: false + - name: storage + type: + scalar: boolean + default: false + - name: subresources + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceScale + map: + fields: + - name: labelSelectorPath + type: + scalar: string + - name: specReplicasPath + type: + scalar: string + default: "" + - name: statusReplicasPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceStatus + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresources + map: + fields: + - name: scale + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceScale + - name: status + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceSubresourceStatus +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceValidation + map: + fields: + - name: openAPIV3Schema + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ExternalDocumentation + map: + fields: + - name: description + type: + scalar: string + - name: url + type: + scalar: string +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + map: + fields: + - name: $ref + type: + scalar: string + - name: $schema + type: + scalar: string + - name: additionalItems + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + - name: additionalProperties + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + - name: allOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: anyOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: default + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + - name: definitions + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: dependencies + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrStringArray + - name: description + type: + scalar: string + - name: enum + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + elementRelationship: atomic + - name: example + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSON + - name: exclusiveMaximum + type: + scalar: boolean + - name: exclusiveMinimum + type: + scalar: boolean + - name: externalDocs + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ExternalDocumentation + - name: format + type: + scalar: string + - name: id + type: + scalar: string + - name: items + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrArray + - name: maxItems + type: + scalar: numeric + - name: maxLength + type: + scalar: numeric + - name: maxProperties + type: + scalar: numeric + - name: maximum + type: + scalar: numeric + - name: minItems + type: + scalar: numeric + - name: minLength + type: + scalar: numeric + - name: minProperties + type: + scalar: numeric + - name: minimum + type: + scalar: numeric + - name: multipleOf + type: + scalar: numeric + - name: not + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: nullable + type: + scalar: boolean + - name: oneOf + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + elementRelationship: atomic + - name: pattern + type: + scalar: string + - name: patternProperties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: properties + type: + map: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps + - name: required + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: title + type: + scalar: string + - name: type + type: + scalar: string + - name: uniqueItems + type: + scalar: boolean + - name: x-kubernetes-embedded-resource + type: + scalar: boolean + - name: x-kubernetes-int-or-string + type: + scalar: boolean + - name: x-kubernetes-list-map-keys + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: x-kubernetes-list-type + type: + scalar: string + - name: x-kubernetes-map-type + type: + scalar: string + - name: x-kubernetes-preserve-unknown-fields + type: + scalar: boolean + - name: x-kubernetes-validations + type: + list: + elementType: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ValidationRule + elementRelationship: associative + keys: + - rule +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrBool + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaPropsOrStringArray + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.SelectableField + map: + fields: + - name: jsonPath + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ServiceReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: namespace + type: + scalar: string + default: "" + - name: path + type: + scalar: string + - name: port + type: + scalar: numeric +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ValidationRule + map: + fields: + - name: fieldPath + type: + scalar: string + - name: message + type: + scalar: string + - name: messageExpression + type: + scalar: string + - name: optionalOldSelf + type: + scalar: boolean + - name: reason + type: + scalar: string + - name: rule + type: + scalar: string + default: "" +- name: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.WebhookClientConfig + map: + fields: + - name: caBundle + type: + scalar: string + - name: service + type: + namedType: io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.ServiceReference + - name: url + type: + scalar: string +- name: io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1 + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry + map: + fields: + - name: apiVersion + type: + scalar: string + - name: fieldsType + type: + scalar: string + - name: fieldsV1 + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1 + - name: manager + type: + scalar: string + - name: operation + type: + scalar: string + - name: subresource + type: + scalar: string + - name: time + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time +- name: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + map: + fields: + - name: annotations + type: + map: + elementType: + scalar: string + - name: creationTimestamp + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: deletionGracePeriodSeconds + type: + scalar: numeric + - name: deletionTimestamp + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: finalizers + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: generateName + type: + scalar: string + - name: generation + type: + scalar: numeric + - name: labels + type: + map: + elementType: + scalar: string + - name: managedFields + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry + elementRelationship: atomic + - name: name + type: + scalar: string + - name: namespace + type: + scalar: string + - name: ownerReferences + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference + elementRelationship: associative + keys: + - uid + - name: resourceVersion + type: + scalar: string + - name: selfLink + type: + scalar: string + - name: uid + type: + scalar: string +- name: io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference + map: + fields: + - name: apiVersion + type: + scalar: string + default: "" + - name: blockOwnerDeletion + type: + scalar: boolean + - name: controller + type: + scalar: boolean + - name: kind + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + - name: uid + type: + scalar: string + default: "" + elementRelationship: atomic +- name: io.k8s.apimachinery.pkg.apis.meta.v1.Time + scalar: untyped +- name: __untyped_atomic_ + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic +- name: __untyped_deduced_ + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +`) diff --git a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go index 93dd79d63..8e13f11bb 100644 --- a/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go +++ b/constraint/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go @@ -30,7 +30,7 @@ import ( ) type Interface interface { - Discovery() discovery.DiscoveryInterface + Discovery() discovery.DiscoveryInterfaces ApiextensionsV1() apiextensionsv1.ApiextensionsV1Interface ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1beta1Interface } @@ -53,7 +53,7 @@ func (c *Clientset) ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1b } // Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { +func (c *Clientset) Discovery() discovery.DiscoveryInterfaces { if c == nil { return nil } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go index a35ce3bd0..628187eee 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/interfaces.go @@ -17,6 +17,8 @@ limitations under the License. package meta import ( + "context" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -109,7 +111,9 @@ type RESTMapping struct { // to API groups. In other words, kinds and resources should not be assumed to be // unique across groups. // -// TODO: split into sub-interfaces +// RESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use RESTMapperWithContext instead. type RESTMapper interface { // KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) @@ -133,11 +137,114 @@ type RESTMapper interface { ResourceSingularizer(resource string) (singular string, err error) } +// RESTMapperWithContext allows clients to map resources to kind, and map kind and version +// to interfaces for manipulating those objects. It is primarily intended for +// consumers of Kubernetes compatible REST APIs as defined in docs/devel/api-conventions.md. +// +// The Kubernetes API provides versioned resources and object kinds which are scoped +// to API groups. In other words, kinds and resources should not be assumed to be +// unique across groups. +type RESTMapperWithContext interface { + // KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches + KindForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionKind, error) + + // KindsFor takes a partial resource and returns the list of potential kinds in priority order + KindsForWithContext(ctx context.Context, resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) + + // ResourceFor takes a partial resource and returns the single match. Returns an error if there are multiple matches + ResourceForWithContext(ctx context.Context, input schema.GroupVersionResource) (schema.GroupVersionResource, error) + + // ResourcesFor takes a partial resource and returns the list of potential resource in priority order + ResourcesForWithContext(ctx context.Context, input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) + + // RESTMapping identifies a preferred resource mapping for the provided group kind. + RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (*RESTMapping, error) + // RESTMappings returns all resource mappings for the provided group kind if no + // version search is provided. Otherwise identifies a preferred resource mapping for + // the provided version(s). + RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) + + ResourceSingularizerWithContext(ctx context.Context, resource string) (singular string, err error) +} + +func ToRESTMapperWithContext(m RESTMapper) RESTMapperWithContext { + if m == nil { + return nil + } + if m, ok := m.(RESTMapperWithContext); ok { + return m + } + return &restMapperWrapper{ + delegate: m, + } +} + +type restMapperWrapper struct { + delegate RESTMapper +} + +func (m *restMapperWrapper) KindForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return m.delegate.KindFor(resource) +} +func (m *restMapperWrapper) KindsForWithContext(ctx context.Context, resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { + return m.delegate.KindsFor(resource) +} +func (m *restMapperWrapper) ResourceForWithContext(ctx context.Context, input schema.GroupVersionResource) (schema.GroupVersionResource, error) { + return m.delegate.ResourceFor(input) +} +func (m *restMapperWrapper) ResourcesForWithContext(ctx context.Context, input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return m.delegate.ResourcesFor(input) +} +func (m *restMapperWrapper) RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (*RESTMapping, error) { + return m.delegate.RESTMapping(gk, versions...) +} +func (m *restMapperWrapper) RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { + return m.delegate.RESTMappings(gk, versions...) +} +func (m *restMapperWrapper) ResourceSingularizerWithContext(ctx context.Context, resource string) (singular string, err error) { + return m.delegate.ResourceSingularizer(resource) +} + // ResettableRESTMapper is a RESTMapper which is capable of resetting itself // from discovery. // All rest mappers that delegate to other rest mappers must implement this interface and dynamically // check if the delegate mapper supports the Reset() operation. +// +// ResettableRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResettableRESTMapperWithContext instead. type ResettableRESTMapper interface { RESTMapper Reset() } + +// ResettableRESTMapperWithContext is a RESTMapper which is capable of resetting itself +// from discovery. +// All rest mappers that delegate to other rest mappers must implement this interface and dynamically +// check if the delegate mapper supports the ResetWithContext() operation. +type ResettableRESTMapperWithContext interface { + RESTMapperWithContext + ResetWithContext(ctx context.Context) +} + +func ToResettableRESTMapperWithContext(m ResettableRESTMapper) ResettableRESTMapperWithContext { + if m == nil { + return nil + } + if m, ok := m.(ResettableRESTMapperWithContext); ok { + return m + } + return &resettableRESTMapperWrapper{ + RESTMapperWithContext: ToRESTMapperWithContext(m), + delegate: m, + } +} + +type resettableRESTMapperWrapper struct { + RESTMapperWithContext + delegate ResettableRESTMapper +} + +func (m *resettableRESTMapperWrapper) ResetWithContext(ctx context.Context) { + m.delegate.Reset() +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go index 2551f07f5..4bf24da52 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/meta.go @@ -600,6 +600,7 @@ func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference { var ret []metav1.OwnerReference s := a.ownerReferences if s.Kind() != reflect.Pointer || s.Elem().Kind() != reflect.Slice { + //nolint:logcheck // Should not happen. klog.Errorf("expect %v to be a pointer to slice", s) return ret } @@ -608,6 +609,7 @@ func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference { ret = make([]metav1.OwnerReference, s.Len(), s.Len()+1) for i := 0; i < s.Len(); i++ { if err := extractFromOwnerReference(s.Index(i), &ret[i]); err != nil { + //nolint:logcheck // Should not happen. klog.Errorf("extractFromOwnerReference failed: %v", err) return ret } @@ -618,12 +620,14 @@ func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference { func (a genericAccessor) SetOwnerReferences(references []metav1.OwnerReference) { s := a.ownerReferences if s.Kind() != reflect.Pointer || s.Elem().Kind() != reflect.Slice { + //nolint:logcheck // Should not happen. klog.Errorf("expect %v to be a pointer to slice", s) } s = s.Elem() newReferences := reflect.MakeSlice(s.Type(), len(references), len(references)) for i := 0; i < len(references); i++ { if err := setOwnerReference(newReferences.Index(i), &references[i]); err != nil { + //nolint:logcheck // Should not happen. klog.Errorf("setOwnerReference failed: %v", err) return } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go index b7e971250..2b2c143ce 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go @@ -17,6 +17,7 @@ limitations under the License. package meta import ( + "context" "fmt" "strings" @@ -25,13 +26,31 @@ import ( ) var ( - _ ResettableRESTMapper = MultiRESTMapper{} + _ ResettableRESTMapper = MultiRESTMapper{} + _ fmt.Stringer = MultiRESTMapper{} + _ ResettableRESTMapperWithContext = MultiRESTMapperWithContext{} + _ fmt.Stringer = MultiRESTMapperWithContext{} ) // MultiRESTMapper is a wrapper for multiple RESTMappers. +// +// MultiRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext instead. type MultiRESTMapper []RESTMapper +// MultiRESTMapperWithContext is a wrapper for multiple RESTMapperWithContext instances. +type MultiRESTMapperWithContext []RESTMapperWithContext + func (m MultiRESTMapper) String() string { + return stringifyMapper("MultiRESTMapper", m) +} + +func (m MultiRESTMapperWithContext) String() string { + return stringifyMapper("MultiRESTMapperWithContext", m) +} + +func stringifyMapper[T any](typeName string, m []T) string { nested := make([]string, 0, len(m)) for _, t := range m { currString := fmt.Sprintf("%v", t) @@ -39,14 +58,93 @@ func (m MultiRESTMapper) String() string { nested = append(nested, strings.Join(splitStrings, "\n\t")) } - return fmt.Sprintf("MultiRESTMapper{\n\t%s\n}", strings.Join(nested, "\n\t")) + return fmt.Sprintf("%s{\n\t%s\n}", typeName, strings.Join(nested, "\n\t")) +} + +func ToMultiRESTMapperWithContext(m MultiRESTMapper) MultiRESTMapperWithContext { + if m == nil { + return nil + } + mc := make(MultiRESTMapperWithContext, len(m)) + for i, m := range m { + mc[i] = ToRESTMapperWithContext(m) + } + return mc } // ResourceSingularizer converts a REST resource name from plural to singular (e.g., from pods to pod) // This implementation supports multiple REST schemas and return the first match. +// +// MultiRESTMapperWithContext.ResourceSingularizerWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.ResourceSingularizerWithContext instead. func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { + return ToMultiRESTMapperWithContext(m).ResourceSingularizerWithContext(context.Background(), resource) +} + +// MultiRESTMapperWithContext.ResourcesForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.ResourcesForWithContext instead. +func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return ToMultiRESTMapperWithContext(m).ResourcesForWithContext(context.Background(), resource) +} + +// MultiRESTMapperWithContext.KindsForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.KindsForWithContext instead. +func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { + return ToMultiRESTMapperWithContext(m).KindsForWithContext(context.Background(), resource) +} + +// MultiRESTMapperWithContext.ResourceForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.ResourceForWithContext instead. +func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { + return ToMultiRESTMapperWithContext(m).ResourceForWithContext(context.Background(), resource) +} + +// MultiRESTMapperWithContext.KindForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.KindForWithContext instead. +func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return ToMultiRESTMapperWithContext(m).KindForWithContext(context.Background(), resource) +} + +// RESTMapping provides the REST mapping for the resource based on the +// kind and version. This implementation supports multiple REST schemas and +// return the first match. +// +// MultiRESTMapperWithContext.RESTMappingWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.RESTMappingWithContext instead. +func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) { + return ToMultiRESTMapperWithContext(m).RESTMappingWithContext(context.Background(), gk, versions...) +} + +// RESTMappings returns all possible RESTMappings for the provided group kind, or an error +// if the type is not recognized. +// +// MultiRESTMapperWithContext.RESTMappingsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.RESTMappingsWithContext instead. +func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { + return ToMultiRESTMapperWithContext(m).RESTMappingsWithContext(context.Background(), gk, versions...) +} + +// MultiRESTMapperWithContext.Reset is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MultiRESTMapperWithContext.Reset instead. +func (m MultiRESTMapper) Reset() { for _, t := range m { - singular, err = t.ResourceSingularizer(resource) + MaybeResetRESTMapper(t) + } +} + +// ResourceSingularizer converts a REST resource name from plural to singular (e.g., from pods to pod) +// This implementation supports multiple REST schemas and return the first match. +func (m MultiRESTMapperWithContext) ResourceSingularizerWithContext(ctx context.Context, resource string) (singular string, err error) { + for _, t := range m { + singular, err = t.ResourceSingularizerWithContext(ctx, resource) if err == nil { return } @@ -54,10 +152,10 @@ func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, return } -func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { +func (m MultiRESTMapperWithContext) ResourcesForWithContext(ctx context.Context, resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { allGVRs := []schema.GroupVersionResource{} for _, t := range m { - gvrs, err := t.ResourcesFor(resource) + gvrs, err := t.ResourcesForWithContext(ctx, resource) // ignore "no match" errors, but any other error percolates back up if IsNoMatchError(err) { continue @@ -89,10 +187,10 @@ func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]s return allGVRs, nil } -func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { +func (m MultiRESTMapperWithContext) KindsForWithContext(ctx context.Context, resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { allGVKs := []schema.GroupVersionKind{} for _, t := range m { - gvks, err := t.KindsFor(resource) + gvks, err := t.KindsForWithContext(ctx, resource) // ignore "no match" errors, but any other error percolates back up if IsNoMatchError(err) { continue @@ -124,8 +222,8 @@ func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []s return allGVKs, nil } -func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { - resources, err := m.ResourcesFor(resource) +func (m MultiRESTMapperWithContext) ResourceForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { + resources, err := m.ResourcesForWithContext(ctx, resource) if err != nil { return schema.GroupVersionResource{}, err } @@ -136,8 +234,8 @@ func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (sche return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources} } -func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { - kinds, err := m.KindsFor(resource) +func (m MultiRESTMapperWithContext) KindForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + kinds, err := m.KindsForWithContext(ctx, resource) if err != nil { return schema.GroupVersionKind{}, err } @@ -151,12 +249,12 @@ func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.G // RESTMapping provides the REST mapping for the resource based on the // kind and version. This implementation supports multiple REST schemas and // return the first match. -func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) { +func (m MultiRESTMapperWithContext) RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (*RESTMapping, error) { allMappings := []*RESTMapping{} errors := []error{} for _, t := range m { - currMapping, err := t.RESTMapping(gk, versions...) + currMapping, err := t.RESTMappingWithContext(ctx, gk, versions...) // ignore "no match" errors, but any other error percolates back up if IsNoMatchError(err) { continue @@ -188,12 +286,12 @@ func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (* // RESTMappings returns all possible RESTMappings for the provided group kind, or an error // if the type is not recognized. -func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { +func (m MultiRESTMapperWithContext) RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { var allMappings []*RESTMapping var errors []error for _, t := range m { - currMappings, err := t.RESTMappings(gk, versions...) + currMappings, err := t.RESTMappingsWithContext(ctx, gk, versions...) // ignore "no match" errors, but any other error percolates back up if IsNoMatchError(err) { continue @@ -213,8 +311,8 @@ func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ( return allMappings, nil } -func (m MultiRESTMapper) Reset() { +func (m MultiRESTMapperWithContext) ResetWithContext(ctx context.Context) { for _, t := range m { - MaybeResetRESTMapper(t) + MaybeResetRESTMapperWithContext(ctx, t) } } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go index 4f097c9c9..d152e7e32 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/priority.go @@ -17,6 +17,7 @@ limitations under the License. package meta import ( + "context" "fmt" "k8s.io/apimachinery/pkg/runtime/schema" @@ -30,11 +31,17 @@ const ( ) var ( - _ ResettableRESTMapper = PriorityRESTMapper{} + _ ResettableRESTMapper = PriorityRESTMapper{} + _ ResettableRESTMapperWithContext = PriorityRESTMapperWithContext{} + _ fmt.Stringer = PriorityRESTMapperWithContext{} ) // PriorityRESTMapper is a wrapper for automatically choosing a particular Resource or Kind // when multiple matches are possible +// +// PriorityRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext instead. type PriorityRESTMapper struct { // Delegate is the RESTMapper to use to locate all the Kind and Resource matches Delegate RESTMapper @@ -56,9 +63,100 @@ func (m PriorityRESTMapper) String() string { return fmt.Sprintf("PriorityRESTMapper{\n\t%v\n\t%v\n\t%v\n}", m.ResourcePriority, m.KindPriority, m.Delegate) } +// PriorityRESTMapperWithContext is a wrapper for automatically choosing a particular Resource or Kind +// when multiple matches are possible +type PriorityRESTMapperWithContext struct { + // Delegate is the RESTMapperWithContext to use to locate all the Kind and Resource matches + Delegate RESTMapperWithContext + + // ResourcePriority is a list of priority patterns to apply to matching resources. + // The list of all matching resources is narrowed based on the patterns until only one remains. + // A pattern with no matches is skipped. A pattern with more than one match uses its + // matches as the list to continue matching against. + ResourcePriority []schema.GroupVersionResource + + // KindPriority is a list of priority patterns to apply to matching kinds. + // The list of all matching kinds is narrowed based on the patterns until only one remains. + // A pattern with no matches is skipped. A pattern with more than one match uses its + // matches as the list to continue matching against. + KindPriority []schema.GroupVersionKind +} + +func (m PriorityRESTMapperWithContext) String() string { + return fmt.Sprintf("PriorityRESTMapperWithContext{\n\t%v\n\t%v\n\t%v\n}", m.ResourcePriority, m.KindPriority, m.Delegate) +} + +func ToPriorityRESTMapperWithContext(m PriorityRESTMapper) PriorityRESTMapperWithContext { + return PriorityRESTMapperWithContext{ + Delegate: ToRESTMapperWithContext(m.Delegate), + ResourcePriority: m.ResourcePriority, + KindPriority: m.KindPriority, + } +} + // ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit. +// +// PriorityRESTMapperWithContext.ResourceForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.ResourceForWithContext instead. func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error) { - originalGVRs, originalErr := m.Delegate.ResourcesFor(partiallySpecifiedResource) + return ToPriorityRESTMapperWithContext(m).ResourceForWithContext(context.Background(), partiallySpecifiedResource) +} + +// KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit. +// +// PriorityRESTMapperWithContext.KindForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.KindForWithContext instead. +func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return ToPriorityRESTMapperWithContext(m).KindForWithContext(context.Background(), partiallySpecifiedResource) +} + +// PriorityRESTMapperWithContext.RESTMappingWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.RESTMappingWithContext instead. +func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) { + return ToPriorityRESTMapperWithContext(m).RESTMappingWithContext(context.Background(), gk, versions...) +} + +// PriorityRESTMapperWithContext.RESTMappingsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.RESTMappingsWithContext instead. +func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { + return m.Delegate.RESTMappings(gk, versions...) +} + +// PriorityRESTMapperWithContext.ResourceSingularizerWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.ResourceSingularizerWithContext instead. +func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { + return m.Delegate.ResourceSingularizer(resource) +} + +// PriorityRESTMapperWithContext.ResourcesForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.ResourcesForWithContext instead. +func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return m.Delegate.ResourcesFor(partiallySpecifiedResource) +} + +// PriorityRESTMapperWithContext.KindsForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.KindsForWithContext instead. +func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { + return m.Delegate.KindsFor(partiallySpecifiedResource) +} + +// PriorityRESTMapperWithContext.ResetWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PriorityRESTMapperWithContext.ResetWithContext instead. +func (m PriorityRESTMapper) Reset() { + MaybeResetRESTMapper(m.Delegate) +} + +// ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit. +func (m PriorityRESTMapperWithContext) ResourceForWithContext(ctx context.Context, partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error) { + originalGVRs, originalErr := m.Delegate.ResourcesForWithContext(ctx, partiallySpecifiedResource) if originalErr != nil && len(originalGVRs) == 0 { return schema.GroupVersionResource{}, originalErr } @@ -93,8 +191,8 @@ func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupV } // KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit. -func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) { - originalGVKs, originalErr := m.Delegate.KindsFor(partiallySpecifiedResource) +func (m PriorityRESTMapperWithContext) KindForWithContext(ctx context.Context, partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + originalGVKs, originalErr := m.Delegate.KindsForWithContext(ctx, partiallySpecifiedResource) if originalErr != nil && len(originalGVKs) == 0 { return schema.GroupVersionKind{}, originalErr } @@ -156,8 +254,8 @@ func kindMatches(pattern schema.GroupVersionKind, kind schema.GroupVersionKind) return true } -func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) { - mappings, originalErr := m.Delegate.RESTMappings(gk, versions...) +func (m PriorityRESTMapperWithContext) RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) { + mappings, originalErr := m.Delegate.RESTMappingsWithContext(ctx, gk, versions...) if originalErr != nil && len(mappings) == 0 { return nil, originalErr } @@ -209,22 +307,22 @@ func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds} } -func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { - return m.Delegate.RESTMappings(gk, versions...) +func (m PriorityRESTMapperWithContext) RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { + return m.Delegate.RESTMappingsWithContext(ctx, gk, versions...) } -func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { - return m.Delegate.ResourceSingularizer(resource) +func (m PriorityRESTMapperWithContext) ResourceSingularizerWithContext(ctx context.Context, resource string) (singular string, err error) { + return m.Delegate.ResourceSingularizerWithContext(ctx, resource) } -func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { - return m.Delegate.ResourcesFor(partiallySpecifiedResource) +func (m PriorityRESTMapperWithContext) ResourcesForWithContext(ctx context.Context, partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return m.Delegate.ResourcesForWithContext(ctx, partiallySpecifiedResource) } -func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { - return m.Delegate.KindsFor(partiallySpecifiedResource) +func (m PriorityRESTMapperWithContext) KindsForWithContext(ctx context.Context, partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { + return m.Delegate.KindsForWithContext(ctx, partiallySpecifiedResource) } -func (m PriorityRESTMapper) Reset() { - MaybeResetRESTMapper(m.Delegate) +func (m PriorityRESTMapperWithContext) ResetWithContext(ctx context.Context) { + MaybeResetRESTMapperWithContext(ctx, m.Delegate) } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go index 91cb98cae..d64db33d4 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper.go @@ -18,6 +18,7 @@ limitations under the License. package meta import ( + "context" "fmt" "sort" "strings" @@ -72,6 +73,8 @@ func (m *DefaultRESTMapper) String() string { } var _ RESTMapper = &DefaultRESTMapper{} +var _ RESTMapperWithContext = &DefaultRESTMapper{} +var _ fmt.Stringer = &DefaultRESTMapper{} // NewDefaultRESTMapper initializes a mapping between Kind and APIVersion // to a resource name and back based on the objects in a runtime.Scheme @@ -179,6 +182,10 @@ func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, e return singular.Resource, nil } +func (m *DefaultRESTMapper) ResourceSingularizerWithContext(_ context.Context, resourceType string) (string, error) { + return m.ResourceSingularizer(resourceType) +} + // coerceResourceForMatching makes the resource lower case and converts internal versions to unspecified (legacy behavior) func coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource { resource.Resource = strings.ToLower(resource.Resource) @@ -276,6 +283,10 @@ func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]s return ret, nil } +func (m *DefaultRESTMapper) ResourcesForWithContext(_ context.Context, input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return m.ResourcesFor(input) +} + func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { resources, err := m.ResourcesFor(resource) if err != nil { @@ -288,6 +299,10 @@ func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (s return schema.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources} } +func (m *DefaultRESTMapper) ResourceForWithContext(_ context.Context, resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { + return m.ResourceFor(resource) +} + func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { resource := coerceResourceForMatching(input) @@ -355,6 +370,10 @@ func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schem return ret, nil } +func (m *DefaultRESTMapper) KindsForWithContext(_ context.Context, input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { + return m.KindsFor(input) +} + func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { kinds, err := m.KindsFor(resource) if err != nil { @@ -367,6 +386,10 @@ func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schem return schema.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds} } +func (m *DefaultRESTMapper) KindForWithContext(_ context.Context, resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return m.KindFor(resource) +} + type kindByPreferredGroupVersion struct { list []schema.GroupVersionKind sortOrder []schema.GroupVersion @@ -461,6 +484,10 @@ func (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) return mappings[0], nil } +func (m *DefaultRESTMapper) RESTMappingWithContext(_ context.Context, gk schema.GroupKind, versions ...string) (*RESTMapping, error) { + return m.RESTMapping(gk, versions...) +} + // RESTMappings returns the RESTMappings for the provided group kind. If a version search order // is not provided, the search order provided to DefaultRESTMapper will be used. func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { @@ -520,10 +547,33 @@ func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string return mappings, nil } -// MaybeResetRESTMapper calls Reset() on the mapper if it is a ResettableRESTMapper. +func (m *DefaultRESTMapper) RESTMappingsWithContext(_ context.Context, gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) { + return m.RESTMappings(gk, versions...) +} + +// MaybeResetRESTMapper calls Reset() on the mapper if it is a ResettableRESTMapper or +// ResetWithContext() if it is a ResettableRESTMapperWithContext. +// +// MaybeResetRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use MaybeResetRESTMapperWithContext instead. func MaybeResetRESTMapper(mapper RESTMapper) { - m, ok := mapper.(ResettableRESTMapper) - if ok { + maybeReset(context.Background(), mapper) +} + +// MaybeResetRESTMapperWithContext calls Reset() on the mapper if it is a ResettableRESTMapper or +// ResetWithContext() if it is a ResettableRESTMapperWithContext. +func MaybeResetRESTMapperWithContext(ctx context.Context, mapper RESTMapperWithContext) { + maybeReset(ctx, mapper) +} + +func maybeReset(ctx context.Context, mapper any) { + if m, ok := mapper.(ResettableRESTMapperWithContext); ok { + m.ResetWithContext(ctx) + return + } + if m, ok := mapper.(ResettableRESTMapper); ok { m.Reset() + return } } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go index 86b6ddf37..cccc7e60c 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go @@ -17,7 +17,6 @@ limitations under the License. package operation import ( - "slices" "strings" ) @@ -31,28 +30,27 @@ type Operation struct { // those into a single "Update" category. Type Type - // Options declare the options enabled for validation. + // Options are the validation options in effect for this operation, mapping option + // name to whether it is enabled. Option names typically match feature gates, but an + // option may be enabled even when its feature gate is off — e.g. when the feature is + // already in use by the object being updated. Set by the resource strategy and + // read-only during validation. // - // Options should be set according to a resource validation strategy before validation - // is performed, and must be treated as read-only during validation. - // - // Options are identified by string names. Option string names may match the name of a feature - // gate, in which case the presence of the name in the set indicates that the feature is - // considered enabled for the resource being validated. Note that a resource may have a - // feature enabled even when the feature gate is disabled. This can happen when feature is - // already in-use by a resource, often because the feature gate was enabled when the - // resource first began using the feature. - // - // Unset options are disabled/false. - Options []string + // Every option a validation tag references must be defined here by the strategy; an + // option that is not defined is a programming error (see HasOption). + Options map[string]bool // Request provides information about the request being validated. Request Request } -// HasOption returns true if the given string is in the Options slice. -func (o Operation) HasOption(option string) bool { - return slices.Contains(o.Options, option) +// HasOption returns whether the named option is enabled and whether it was defined by +// the strategy. Every option a validation tag references must be defined; callers treat +// an undefined option as an internal error (see validate.IfOption) rather than silently +// as disabled. +func (o Operation) HasOption(option string) (enabled, defined bool) { + enabled, defined = o.Options[option] + return } // Request provides information about the request being validated. diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go index f3cd60060..e6b1f1b53 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go @@ -878,3 +878,14 @@ func (q *QuantityValue) Set(s string) error { func (q QuantityValue) Type() string { return "quantity" } + +// QuantityPtrEqual compares two Quantity pointers and returns true if they are both nil or point to equal quantities. +func QuantityPtrEqual(a, b *Quantity) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return a.Equal(*b) +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/content/kube.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/content/kube.go index 44e82eefd..608073f70 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/content/kube.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/content/kube.go @@ -99,3 +99,19 @@ func prefixEach(msgs []string, prefix string) []string { } return msgs } + +// IsPrefixedLabelKey tests whether the value passed is a valid label key with +// a domain prefix. This allows "example.com/key" but not "key". +// If the value is not valid, a list of error strings is returned. Otherwise, +// an empty list (or nil) is returned. +func IsPrefixedLabelKey(value string) []string { + if errs := IsLabelKey(value); len(errs) > 0 { + return errs + } + + segments := strings.Split(value, "/") + if len(segments) != 2 { + return []string{"must include a prefix (e.g. 'example.com/key')"} + } + return nil +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/dependentrequired.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/dependentrequired.go new file mode 100644 index 000000000..69222c975 --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/dependentrequired.go @@ -0,0 +1,83 @@ +/* +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 validate + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +// DependentRequired verifies that when triggerIsSet(obj) is true, dependentIsSet(obj) +// is also true; otherwise reports an error at fldPath.Child(dependentName). +// On Update, the check is skipped if neither side's set-ness changed from oldObj, +// so unrelated updates can proceed past a pre-existing violation. +func DependentRequired[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *T, + triggerName string, triggerIsSet ExtractorFn[*T, bool], + dependentName string, dependentIsSet ExtractorFn[*T, bool], +) field.ErrorList { + if obj == nil { + return nil + } + if op.Type == operation.Update && oldObj != nil { + if triggerIsSet(obj) == triggerIsSet(oldObj) && dependentIsSet(obj) == dependentIsSet(oldObj) { + return nil + } + } + if !triggerIsSet(obj) { + return nil + } + if dependentIsSet(obj) { + return nil + } + return field.ErrorList{ + field.Required(fldPath.Child(dependentName), + fmt.Sprintf("must be set when %s is set", triggerName)). + WithOrigin("dependentRequired"), + } +} + +// DependentForbidden verifies that when triggerIsSet(obj) is true, dependentIsSet(obj) +// is false; otherwise reports an error at fldPath.Child(dependentName). +// On Update, the check is skipped if neither side's set-ness changed from oldObj, +// so unrelated updates can proceed past a pre-existing violation. +func DependentForbidden[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *T, + triggerName string, triggerIsSet ExtractorFn[*T, bool], + dependentName string, dependentIsSet ExtractorFn[*T, bool], +) field.ErrorList { + if obj == nil { + return nil + } + if op.Type == operation.Update && oldObj != nil { + if triggerIsSet(obj) == triggerIsSet(oldObj) && dependentIsSet(obj) == dependentIsSet(oldObj) { + return nil + } + } + if !triggerIsSet(obj) { + return nil + } + if !dependentIsSet(obj) { + return nil + } + return field.ErrorList{ + field.Forbidden(fldPath.Child(dependentName), + fmt.Sprintf("may not be set when %s is set", triggerName)). + WithOrigin("dependentForbidden"), + } +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go index 787ae6b0b..6f4b3cddd 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go @@ -35,6 +35,9 @@ type DiscriminatedRule[Tfield any, Tdisc comparable] struct { // // It performs ratcheting: if the operation is an Update, and neither the discriminator // nor the value (checked via equiv) have changed, validation is skipped. +// +// The equiv function can be called with nil arguments in the case of nilable +// fields. func Discriminated[Tfield any, Tdisc comparable, Tstruct any](ctx context.Context, op operation.Operation, structPath *field.Path, obj, oldObj *Tstruct, fieldName string, getMemberValue func(*Tstruct) Tfield, getDiscriminator func(*Tstruct) Tdisc, equiv MatchFunc[Tfield], defaultValidation ValidateFunc[Tfield], rules []DiscriminatedRule[Tfield, Tdisc], diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/each.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/each.go index c815d6d91..2930c2183 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/each.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/each.go @@ -18,6 +18,7 @@ package validate import ( "context" + "slices" "sort" "k8s.io/apimachinery/pkg/api/equality" @@ -29,22 +30,29 @@ import ( // according to some criteria, and returns true if they match. type MatchFunc[T any] func(T, T) bool -// EachSliceVal performs validation on each element of newSlice using the provided validation function. +// EachValSliceVal performs validation on each element of a slice of values +// using the provided validation function. // -// For update operations, the match function finds corresponding values in oldSlice for each -// value in newSlice. This comparison can be either full or partial (e.g., matching only -// specific struct fields that serve as a unique identifier). If match is nil, validation -// proceeds without considering old values, and the equiv function is not used. +// For update operations, the match function finds corresponding values in +// oldSlice for each value in newSlice. This comparison can be either full or +// partial (e.g., matching only specific struct fields that serve as a unique +// identifier). If match is nil, validation proceeds without considering old +// values, and the equiv function is not used. // -// For update operations, the equiv function checks if a new value is equivalent to its -// corresponding old value, enabling validation ratcheting. If equiv is nil but match is -// provided, the match function is assumed to perform full value comparison. +// For update operations, the equiv function checks if a new value is +// equivalent to its corresponding old value, enabling validation ratcheting. +// If equiv is nil but match is provided, the match function is assumed to +// perform full value comparison. +// +// The match and equiv functions will never be called with nil arguments. // // Note: The slice element type must be non-nilable. -func EachSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []T, - match, equiv MatchFunc[T], validator ValidateFunc[*T]) field.ErrorList { +func EachValSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []T, + match, equiv MatchFunc[*T], validator ValidateFunc[*T]) field.ErrorList { var errs field.ErrorList - for i, val := range newSlice { + for i := range newSlice { + val := &newSlice[i] + var old *T if match != nil && len(oldSlice) > 0 { old = lookup(oldSlice, val, match) @@ -55,33 +63,90 @@ func EachSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *f // 2. The equiv function confirms the values are equivalent (either directly or semantically) // // The equiv function provides equality comparison when match uses partial comparison. - if op.Type == operation.Update && old != nil && (equiv == nil || equiv(val, *old)) { + if op.Type == operation.Update && old != nil && (equiv == nil || equiv(val, old)) { + continue + } + errs = append(errs, validator(ctx, op, fldPath.Index(i), val, old)...) + } + return errs +} + +// EachPtrSliceVal performs validation on each element of a slice of pointers +// using the provided validation function. +// +// For update operations, the match function finds corresponding values in +// oldSlice for each value in newSlice. This comparison can be either full or +// partial (e.g., matching only specific struct fields that serve as a unique +// identifier). If match is nil, validation proceeds without considering old +// values, and the equiv function is not used. +// +// For update operations, the equiv function checks if a new value is +// equivalent to its corresponding old value, enabling validation ratcheting. +// If equiv is nil but match is provided, the match function is assumed to +// perform full value comparison. +// +// The match and equiv functions will never be called with nil arguments. +func EachPtrSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []*T, + match, equiv MatchFunc[*T], validator ValidateFunc[*T]) field.ErrorList { + var errs field.ErrorList + for i := range newSlice { + val := newSlice[i] + if val == nil { + // Ignore nil items; they are supposed to have been checked by PtrSliceNoNils. + continue + } + + var old *T + if match != nil && len(oldSlice) > 0 { + old = lookupPointer(oldSlice, val, match) + } + if op.Type == operation.Update && old != nil && (equiv == nil || equiv(val, old)) { continue } - errs = append(errs, validator(ctx, op, fldPath.Index(i), &val, old)...) + errs = append(errs, validator(ctx, op, fldPath.Index(i), val, old)...) } return errs } // lookup returns a pointer to the first element in the list that matches the // target, according to the provided comparison function, or else nil. -func lookup[T any](list []T, target T, match MatchFunc[T]) *T { +func lookup[T any](list []T, target *T, match MatchFunc[*T]) *T { for i := range list { - if match(list[i], target) { + if match(&list[i], target) { return &list[i] } } return nil } +// lookupPointer returns the first non-nil element in the list that matches the +// target, according to the provided comparison function, or else nil. +// Nil elements in the list are skipped. +func lookupPointer[T any](list []*T, target *T, match MatchFunc[*T]) *T { + for i := range list { + if list[i] == nil { + // We can't really do anything about nil entries in the old list, + // just skip them. + continue + } + if match(list[i], target) { + return list[i] + } + } + return nil +} + // EachMapVal validates each value in newMap using the specified validation // function, passing the corresponding old value from oldMap if the key exists in oldMap. // For update operations, it implements validation ratcheting by skipping validation // when the old value exists and the equiv function confirms the values are equivalent. // The value-type of the map is assumed to not be nilable. +// +// The equiv function will never be called with nil arguments. +// // If equiv is nil, value-based ratcheting is disabled and all values will be validated. func EachMapVal[K ~string, V any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]V, - equiv MatchFunc[V], validator ValidateFunc[*V]) field.ErrorList { + equiv MatchFunc[*V], validator ValidateFunc[*V]) field.ErrorList { var errs field.ErrorList for key, val := range newMap { var old *V @@ -90,7 +155,7 @@ func EachMapVal[K ~string, V any](ctx context.Context, op operation.Operation, f } // If the operation is an update, for validation ratcheting, skip re-validating if the old // value is found and the equiv function confirms the values are equivalent. - if op.Type == operation.Update && old != nil && equiv != nil && equiv(val, *old) { + if op.Type == operation.Update && old != nil && equiv != nil && equiv(&val, old) { continue } errs = append(errs, validator(ctx, op, fldPath.Key(string(key)), &val, old)...) @@ -119,19 +184,20 @@ func EachMapKey[K ~string, T any](ctx context.Context, op operation.Operation, f return errs } -// Unique verifies that each element of newSlice is unique, according to the -// match function. It compares every element of the slice with every other -// element and returns errors for non-unique items. -func Unique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []T, match MatchFunc[T]) field.ErrorList { +// ValSliceUnique verifies that each element of a slice of values is unique, +// according to the match function. It compares every element of the slice with +// every other element and returns errors for non-unique items. +// +// The match function will never be called with nil arguments. +func ValSliceUnique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []T, match MatchFunc[*T]) field.ErrorList { var dups []int - for i, val := range newSlice { + for i := range newSlice { for j := i + 1; j < len(newSlice); j++ { - other := newSlice[j] - if match(val, other) { + if match(&newSlice[i], &newSlice[j]) { if dups == nil { dups = make([]int, 0, len(newSlice)) } - if lookup(dups, j, func(a, b int) bool { return a == b }) == nil { + if !slices.Contains(dups, j) { dups = append(dups, j) } } @@ -152,6 +218,42 @@ func Unique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path return errs } +// PtrSliceUnique verifies that each element of a slice of pointers is unique, +// according to the match function. It compares every element of the slice with +// every other element and returns errors for non-unique items. +// +// The match function will never be called with nil arguments. +func PtrSliceUnique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []*T, match MatchFunc[*T]) field.ErrorList { + var errs field.ErrorList + var dups []int + for i := range newSlice { + if newSlice[i] == nil { + // Ignore nil items; they are supposed to have been checked by PtrSliceNoNils. + continue + } + for j := i + 1; j < len(newSlice); j++ { + if newSlice[j] == nil { + continue + } + if match(newSlice[i], newSlice[j]) { + if dups == nil { + dups = make([]int, 0, len(newSlice)) + } + if !slices.Contains(dups, j) { + dups = append(dups, j) + } + } + } + } + + sort.Ints(dups) + for _, i := range dups { + var val any = newSlice[i] + errs = append(errs, field.Duplicate(fldPath.Index(i), val)) + } + return errs +} + // SemanticDeepEqual is a MatchFunc that uses equality.Semantic.DeepEqual to // compare two values. // This wrapper is needed because MatchFunc requires a function that takes two @@ -163,19 +265,12 @@ func SemanticDeepEqual[T any](a, b T) bool { return equality.Semantic.DeepEqual(a, b) } -// DirectEqual is a MatchFunc that uses the == operator to compare two values. -// It can be used by any other function that needs to compare two values -// directly. -func DirectEqual[T comparable](a, b T) bool { - return a == b -} - -// DirectEqualPtr is a MatchFunc that dereferences two pointers and uses the == +// DirectEqual is a MatchFunc that dereferences two pointers and uses the == // operator to compare the values. If both pointers are nil, it returns true. // If one pointer is nil and the other is not, it returns false. // It can be used by any other function that needs to compare two pointees // directly. -func DirectEqualPtr[T comparable](a, b *T) bool { +func DirectEqual[T comparable](a, b *T) bool { if a == b { return true } @@ -184,3 +279,14 @@ func DirectEqualPtr[T comparable](a, b *T) bool { } return *a == *b } + +// PtrSliceNoNils returns a Required error for each nil element in a slice of +// pointers. +func PtrSliceNoNils[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []*T) (errs field.ErrorList) { + for i := range newSlice { + if newSlice[i] == nil { + errs = append(errs, field.Required(fldPath.Index(i), "")) + } + } + return +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/enum.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/enum.go index 6e5bcf373..4d8e2c0aa 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/enum.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/enum.go @@ -18,6 +18,7 @@ package validate import ( "context" + "fmt" "slices" "k8s.io/apimachinery/pkg/api/operation" @@ -32,24 +33,36 @@ func Enum[T ~string](_ context.Context, op operation.Operation, fldPath *field.P if value == nil { return nil } - if !validValues.Has(*value) || isExcluded(op, exclusions, *value) { - return field.ErrorList{field.NotSupported[T](fldPath, *value, supportedValues(op, validValues, exclusions))} + excluded, err := isExcluded(op, exclusions, *value) + if err != nil { + return field.ErrorList{field.InternalError(fldPath, err)} + } + if !validValues.Has(*value) || excluded { + supported, err := supportedValues(op, validValues, exclusions) + if err != nil { + return field.ErrorList{field.InternalError(fldPath, err)} + } + return field.ErrorList{field.NotSupported[T](fldPath, *value, supported)} } return nil } // supportedValues returns a sorted list of supported values. // Excluded enum values are not included in the list. -func supportedValues[T ~string](op operation.Operation, values sets.Set[T], exclusions []EnumExclusion[T]) []T { +func supportedValues[T ~string](op operation.Operation, values sets.Set[T], exclusions []EnumExclusion[T]) ([]T, error) { res := make([]T, 0, len(values)) for key := range values { - if isExcluded(op, exclusions, key) { + excluded, err := isExcluded(op, exclusions, key) + if err != nil { + return nil, err + } + if excluded { continue } res = append(res, key) } slices.Sort(res) - return res + return res, nil } // EnumExclusion represents a single enum exclusion rule. @@ -64,11 +77,15 @@ type EnumExclusion[T ~string] struct { Option string } -func isExcluded[T ~string](op operation.Operation, exclusions []EnumExclusion[T], value T) bool { +func isExcluded[T ~string](op operation.Operation, exclusions []EnumExclusion[T], value T) (bool, error) { for _, rule := range exclusions { - if rule.Value == value && rule.ExcludeWhen == op.HasOption(rule.Option) { - return true + on, defined := op.HasOption(rule.Option) + if !defined { + return false, fmt.Errorf("undefined validation option %q", rule.Option) + } + if rule.Value == value && rule.ExcludeWhen == on { + return true, nil } } - return false + return false, nil } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/errors.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/errors.go new file mode 100644 index 000000000..a9dc4b01c --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/errors.go @@ -0,0 +1,96 @@ +/* +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 validate + +import ( + "context" + "errors" + + "k8s.io/apimachinery/pkg/util/validation/field" +) + +type allDeclarativeEnforcedKeyType struct{} + +var allDeclarativeEnforcedKey = allDeclarativeEnforcedKeyType{} + +// WithAllDeclarativeEnforcedForTest returns a copy of parent context with allDeclarativeEnforcedKey set to true. +// This is used for testing to expose all declarative validation errors and filter all handwritten validation errors +// that are covered by declarative validation, regardless of the feature gate or maturity level. +// +// NOTE: This function is intended for testing purposes only and should not be used in production code. +func WithAllDeclarativeEnforcedForTest(ctx context.Context) context.Context { + return context.WithValue(ctx, allDeclarativeEnforcedKey, true) +} + +// AllDeclarativeEnforced returns true if the context contains allDeclarativeEnforcedKey set to true. +func AllDeclarativeEnforced(ctx context.Context) bool { + if ctx == nil { + return false + } + return ctx.Value(allDeclarativeEnforcedKey) == true +} + +// FilterCoveredHandwrittenErrors removes a CoveredByDeclarative handwritten error when a matching enforced +// beta declarative error exists (matched by type, field, and origin). In AllDeclarativeEnforced +// (testing-only) mode every covered handwritten error is removed. +func FilterCoveredHandwrittenErrors(ctx context.Context, imperativeErrs, enforcedDeclarativeErrs field.ErrorList, betaEnabled bool, rules ...field.NormalizationRule) field.ErrorList { + matcher := field.ErrorMatcher{}.ByType().ByOrigin().RequireOriginWhenInvalid().ByFieldNormalized(rules) + allDeclarativeEnforced := AllDeclarativeEnforced(ctx) + return imperativeErrs.Filter(func(e error) bool { + var fe *field.Error + if !errors.As(e, &fe) || !fe.CoveredByDeclarative { + return false + } + if allDeclarativeEnforced { + return true + } + for _, dErr := range enforcedDeclarativeErrs { + if dErr.IsBeta() && matcher.Matches(fe, dErr) { + return true + } + } + return false + }) +} + +// FilterEnforcedDeclarativeErrors collects the declarative errors that are enforced (i.e. surfaced to the user) in the +// current mode. A declarative error is enforced when any of the following holds: +// - AllDeclarativeEnforced is set (testing): every declarative error is enforced. +// - It is an internal error: always enforced, regardless of lifecycle. +// - It is a beta error and BetaEnabled is true. +// - It is a standard (unprefixed) error: always enforced. +// +// Alpha errors are never enforced; they remain shadowed by handwritten validation. +func FilterEnforcedDeclarativeErrors(ctx context.Context, declarativeErrs field.ErrorList, betaEnabled bool) field.ErrorList { + enforcedDeclarativeErrs := make(field.ErrorList, 0, len(declarativeErrs)) + allDeclarativeEnforced := AllDeclarativeEnforced(ctx) + for _, dvErr := range declarativeErrs { + switch { + case allDeclarativeEnforced: + enforcedDeclarativeErrs = append(enforcedDeclarativeErrs, dvErr) + case dvErr.Type == field.ErrorTypeInternal: + enforcedDeclarativeErrs = append(enforcedDeclarativeErrs, dvErr) + case dvErr.IsBeta(): + if betaEnabled { + enforcedDeclarativeErrs = append(enforcedDeclarativeErrs, dvErr) + } + case !dvErr.IsAlpha(): + enforcedDeclarativeErrs = append(enforcedDeclarativeErrs, dvErr) // Standard + } + } + return enforcedDeclarativeErrs +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/item.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/item.go index aba417fa1..4ddb2860c 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/item.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/item.go @@ -23,36 +23,39 @@ import ( "k8s.io/apimachinery/pkg/util/validation/field" ) -// MatchItemFn takes a pointer to an item and returns true if it matches the criteria. -type MatchItemFn[T any] func(*T) bool +// MatchItemFunc takes an item and returns true if it matches the criteria. +type MatchItemFunc[T any] func(T) bool -// SliceItem finds the first item in newList that satisfies the match function, -// and if found, also looks for a matching item in oldList. If the value of the -// item is the same as the previous value, as per the equiv function, then no -// validation is performed. Otherwise, it invokes 'itemValidator' on these items. +// ValSliceItem finds the first item in a list of values which satisfies the +// match function, and if found, also looks for a matching item in oldList. If +// the value of the item is the same as the previous value, as per the equiv +// function, then no validation is performed. Otherwise, it invokes +// 'itemValidator' on these items. // // This function processes only the *first* matching item found in newList. It // assumes that the match functions targets a unique identifier (primary key) // and will match at most one element per list. If this assumption is violated, // changes in list order can lead this function to have inconsistent behavior. // +// The match and equiv functions will never be called with nil arguments. +// // The fldPath passed to itemValidator is indexed to the matched item's // position in newList. // // This function does not validate items that were removed (present in oldList // but not in newList). -func SliceItem[TList ~[]TItem, TItem any]( +func ValSliceItem[TList ~[]TItem, TItem any]( ctx context.Context, op operation.Operation, fldPath *field.Path, newList, oldList TList, - matches MatchItemFn[TItem], - equiv MatchFunc[TItem], + match MatchItemFunc[*TItem], + equiv MatchFunc[*TItem], itemValidator func(ctx context.Context, op operation.Operation, fldPath *field.Path, newObj, oldObj *TItem) field.ErrorList, ) field.ErrorList { var matchedNew, matchedOld *TItem var newIndex int for i := range newList { - if matches(&newList[i]) { + if match(&newList[i]) { matchedNew = &newList[i] newIndex = i break @@ -63,13 +66,73 @@ func SliceItem[TList ~[]TItem, TItem any]( } for i := range oldList { - if matches(&oldList[i]) { + if match(&oldList[i]) { matchedOld = &oldList[i] break } } - if op.Type == operation.Update && matchedOld != nil && equiv(*matchedNew, *matchedOld) { + if op.Type == operation.Update && matchedOld != nil && equiv(matchedNew, matchedOld) { + return nil + } + + return itemValidator(ctx, op, fldPath.Index(newIndex), matchedNew, matchedOld) +} + +// PtrSliceItem finds the first item in a list of pointers which satisfies the +// match function, and if found, also looks for a matching item in oldList. If +// the value of the item is the same as the previous value, as per the equiv +// function, then no validation is performed. Otherwise, it invokes +// 'itemValidator' on these items. +// +// This function processes only the *first* matching item found in newList. It +// assumes that the match functions targets a unique identifier (primary key) +// and will match at most one element per list. If this assumption is violated, +// changes in list order can lead this function to have inconsistent behavior. +// +// The match and equiv functions will never be called with nil arguments. +// +// The fldPath passed to itemValidator is indexed to the matched item's +// position in newList. +// +// This function does not validate items that were removed (present in oldList +// but not in newList). +func PtrSliceItem[TList ~[]*TItem, TItem any]( + ctx context.Context, op operation.Operation, fldPath *field.Path, + newList, oldList TList, + match MatchItemFunc[*TItem], + equiv MatchFunc[*TItem], + itemValidator func(ctx context.Context, op operation.Operation, fldPath *field.Path, newObj, oldObj *TItem) field.ErrorList, +) field.ErrorList { + var matchedNew, matchedOld *TItem + var newIndex int + + for i := range newList { + if newList[i] == nil { + // Ignore nil items; they are supposed to have been checked by PtrSliceNoNils. + continue + } + if match(newList[i]) { + matchedNew = newList[i] + newIndex = i + break + } + } + if matchedNew == nil { + return nil + } + + for i := range oldList { + if oldList[i] == nil { + continue + } + if match(oldList[i]) { + matchedOld = oldList[i] + break + } + } + + if op.Type == operation.Update && matchedOld != nil && equiv(matchedNew, matchedOld) { return nil } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go index dcc7f518d..768546f6b 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go @@ -78,6 +78,18 @@ func MaxItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Pa return nil } +// MaxProperties verifies that the specified map has no more than max keys. +func MaxProperties[K comparable, V any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]V, max int) field.ErrorList { + if value == nil { + return nil + } + + if len(value) > max { + return field.ErrorList{field.TooMany(fldPath, len(value), max).WithOrigin("maxProperties")} + } + return nil +} + // MinItems verifies that the specified slice is not shorter than min items. func MinItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T, min int) field.ErrorList { if len(value) < min { @@ -86,6 +98,14 @@ func MinItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Pa return nil } +// MinProperties verifies that the specified map is not shorter than min properties. +func MinProperties[K comparable, V any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]V, min int) field.ErrorList { + if len(value) < min { + return field.ErrorList{field.TooFew(fldPath, len(value), min).WithOrigin("minProperties")} + } + return nil +} + // Minimum verifies that the specified value is greater than or equal to min. func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min T) field.ErrorList { if value == nil { diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/monotonic.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/monotonic.go new file mode 100644 index 000000000..f0526c9ff --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/monotonic.go @@ -0,0 +1,43 @@ +/* +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 validate + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/api/validate/constraints" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +// Monotonic validates that an integer value has not decreased on update. +func Monotonic[T constraints.Integer](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T) field.ErrorList { + if op.Type != operation.Update { + return nil + } + + if value == nil || oldValue == nil { + return nil + } + + if *value < *oldValue { + return field.ErrorList{field.Invalid(fldPath, *value, fmt.Sprintf("may not be decreased from %v", *oldValue)).WithOrigin("monotonic")} + } + + return nil +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/options.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/options.go index 44236550b..143be3b64 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/options.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/options.go @@ -18,6 +18,7 @@ package validate import ( "context" + "fmt" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/util/validation/field" @@ -25,10 +26,14 @@ import ( // IfOption conditionally evaluates a validation function. If the option and enabled are both true the validator // is called. If the option and enabled are both false the validator is called. Otherwise, the validator is not called. -func IfOption[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, - optionName string, enabled bool, validator func(context.Context, operation.Operation, *field.Path, *T, *T) field.ErrorList, +func IfOption[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue T, + optionName string, enabled bool, validator func(context.Context, operation.Operation, *field.Path, T, T) field.ErrorList, ) field.ErrorList { - if op.HasOption(optionName) == enabled { + on, defined := op.HasOption(optionName) + if !defined { + return field.ErrorList{field.InternalError(fldPath, fmt.Errorf("undefined validation option %q", optionName))} + } + if on == enabled { return validator(ctx, op, fldPath, value, oldValue) } return nil diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go index 190fa8dbe..893f55d77 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go @@ -97,6 +97,28 @@ func LabelKey[T ~string](_ context.Context, op operation.Operation, fldPath *fie return allErrs } +// PrefixedLabelKey verifies that the specified value is a valid label key with +// a domain prefix. +// A prefixed label key is composed of a prefix and a name, separated by a '/'. +// The name part is required and must: +// - be 63 characters or less +// - begin and end with an alphanumeric character ([a-z0-9A-Z]) +// - contain only alphanumeric characters, dashes (-), underscores (_), or dots (.) +// +// The prefix must: +// - be a DNS subdomain +// - be no more than 253 characters +func PrefixedLabelKey[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList { + if value == nil { + return nil + } + var allErrs field.ErrorList + for _, msg := range content.IsPrefixedLabelKey((string)(*value)) { + allErrs = append(allErrs, field.Invalid(fldPath, *value, msg).WithOrigin("format=k8s-prefixed-label-key")) + } + return allErrs +} + // LongNameCaseless verifies that the specified value is a valid "long name" // (sometimes known as a "DNS subdomain"), but is case-insensitive. // - must not be empty diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/subfield.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/subfield.go index 896f3c3f3..7aa48d330 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/subfield.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/subfield.go @@ -31,6 +31,9 @@ type GetFieldFunc[Tstruct any, Tfield any] func(*Tstruct) Tfield // the value of the subfield is the same as the previous value, as per the // equiv function, then no validation is performed. // +// The equiv function can be called with nil arguments in the case of nilable +// fields. +// // The fldPath passed to the validator includes the subfield name. func Subfield[Tstruct any, Tfield any]( ctx context.Context, op operation.Operation, fldPath *field.Path, diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/update.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/update.go index e67ee28de..c258e6d11 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/update.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validate/update.go @@ -18,6 +18,8 @@ package validate import ( "context" + "fmt" + "slices" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/operation" @@ -34,11 +36,16 @@ const ( NoUnset // NoModify prevents value changes but allows set/unset transitions NoModify + // NoAddItem prevents adding items to a slice or map + NoAddItem + // NoRemoveItem prevents removing items from a slice or map + NoRemoveItem ) // UpdateValueByCompare verifies update constraints for comparable value types. func UpdateValueByCompare[T comparable](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList { - if op.Type != operation.Update { + // nil oldValue means no prior value to compare against (eg: a new item at +k8s:eachVal scope) -> no transition to check. + if op.Type != operation.Update || oldValue == nil { return nil } @@ -101,7 +108,8 @@ func UpdatePointer[T any](_ context.Context, op operation.Operation, fldPath *fi // UpdateValueByReflect verifies update constraints for non-comparable value types using reflection. func UpdateValueByReflect[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList { - if op.Type != operation.Update { + // nil oldValue means no prior value to compare against (eg: a new item at +k8s:eachVal scope) -> no transition to check. + if op.Type != operation.Update || oldValue == nil { return nil } @@ -136,7 +144,8 @@ func UpdateValueByReflect[T any](_ context.Context, op operation.Operation, fldP // UpdateStruct verifies update constraints for non-pointer struct types. // Non-pointer structs are always considered "set" and never "unset". func UpdateStruct[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList { - if op.Type != operation.Update { + // nil oldValue means no prior value to compare against (eg: a new item at +k8s:eachVal scope) -> no transition to check. + if op.Type != operation.Update || oldValue == nil { return nil } @@ -158,3 +167,142 @@ func UpdateStruct[T any](_ context.Context, op operation.Operation, fldPath *fie return errs } + +// ValSliceUpdate verifies update constraints for slices of values. +// NoAddItem and NoRemoveItem use the match function to find corresponding +// elements between value and oldValue. NoSet and NoUnset treat len == 0 as +// "unset". +// +// The match function will never be called with nil arguments. +func ValSliceUpdate[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue []T, match MatchFunc[*T], constraints ...UpdateConstraint) field.ErrorList { + if op.Type != operation.Update { + return nil + } + + if match == nil && (slices.Contains(constraints, NoAddItem) || slices.Contains(constraints, NoRemoveItem)) { + return field.ErrorList{field.InternalError(fldPath, fmt.Errorf("ValSliceUpdate: NoAddItem/NoRemoveItem require a non-nil match function"))} + } + + var errs field.ErrorList + + for _, constraint := range constraints { + switch constraint { + case NoSet: + if len(oldValue) == 0 && len(value) > 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be set once created").WithOrigin("update")) + } + case NoUnset: + if len(oldValue) > 0 && len(value) == 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be cleared once set").WithOrigin("update")) + } + case NoAddItem: + for i := range value { + newItem := &value[i] + if lookup(oldValue, newItem, match) == nil { + errs = append(errs, field.Forbidden(fldPath.Index(i), "item may not be added").WithOrigin("update")) + } + } + case NoRemoveItem: + for i := range oldValue { + oldItem := &oldValue[i] + if lookup(value, oldItem, match) == nil { + errs = append(errs, field.Forbidden(fldPath, "item may not be removed").WithOrigin("update")) + } + } + } + } + + return errs +} + +// PtrSliceUpdate verifies update constraints for slices of pointers. +// NoAddItem and NoRemoveItem use the match function to find corresponding +// elements between value and oldValue. NoSet and NoUnset treat len == 0 as +// "unset". +// +// The match function will never be called with nil arguments. +func PtrSliceUpdate[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue []*T, match MatchFunc[*T], constraints ...UpdateConstraint) field.ErrorList { + if op.Type != operation.Update { + return nil + } + + if match == nil && (slices.Contains(constraints, NoAddItem) || slices.Contains(constraints, NoRemoveItem)) { + return field.ErrorList{field.InternalError(fldPath, fmt.Errorf("PtrSliceUpdate: NoAddItem/NoRemoveItem require a non-nil match function"))} + } + + var errs field.ErrorList + + for _, constraint := range constraints { + switch constraint { + case NoSet: + if len(oldValue) == 0 && len(value) > 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be set once created").WithOrigin("update")) + } + case NoUnset: + if len(oldValue) > 0 && len(value) == 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be cleared once set").WithOrigin("update")) + } + case NoAddItem: + for i := range value { + newItem := value[i] + if newItem == nil { + // Ignore nil items; they are supposed to have been checked by PtrSliceNoNils. + continue + } + if lookupPointer(oldValue, newItem, match) == nil { + errs = append(errs, field.Forbidden(fldPath.Index(i), "item may not be added").WithOrigin("update")) + } + } + case NoRemoveItem: + for i := range oldValue { + oldItem := oldValue[i] + if oldItem == nil { + continue + } + if lookupPointer(value, oldItem, match) == nil { + errs = append(errs, field.Forbidden(fldPath, "item may not be removed").WithOrigin("update")) + } + } + } + } + + return errs +} + +// UpdateMap verifies update constraints for map types. +// NoAddItem and NoRemoveItem compare keys between value and oldValue. NoSet +// and NoUnset treat len == 0 as "unset". +func UpdateMap[K comparable, V any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue map[K]V, constraints ...UpdateConstraint) field.ErrorList { + if op.Type != operation.Update { + return nil + } + + var errs field.ErrorList + + for _, constraint := range constraints { + switch constraint { + case NoSet: + if len(oldValue) == 0 && len(value) > 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be set once created").WithOrigin("update")) + } + case NoUnset: + if len(oldValue) > 0 && len(value) == 0 { + errs = append(errs, field.Invalid(fldPath, nil, "field cannot be cleared once set").WithOrigin("update")) + } + case NoAddItem: + for k := range value { + if _, ok := oldValue[k]; !ok { + errs = append(errs, field.Forbidden(fldPath.Key(fmt.Sprintf("%v", k)), "item may not be added").WithOrigin("update")) + } + } + case NoRemoveItem: + for k := range oldValue { + if _, ok := value[k]; !ok { + errs = append(errs, field.Forbidden(fldPath.Key(fmt.Sprintf("%v", k)), "item may not be removed").WithOrigin("update")) + } + } + } + } + + return errs +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go b/constraint/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go index 9a4f37848..ff86973fb 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go @@ -17,11 +17,14 @@ limitations under the License. package validation import ( + "context" "fmt" "strings" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/api/validate" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" "k8s.io/apimachinery/pkg/runtime/schema" @@ -68,20 +71,23 @@ func ValidateAnnotationsSize(annotations map[string]string) error { func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - gvk := schema.FromAPIVersionAndKind(ownerReference.APIVersion, ownerReference.Kind) + gv, err := schema.ParseGroupVersion(ownerReference.APIVersion) // gvk.Group is empty for the legacy group. - if len(gvk.Version) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("apiVersion"), ownerReference.APIVersion, "version must not be empty")) + if len(ownerReference.APIVersion) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("apiVersion"), "must not be empty").MarkCoveredByDeclarative()) + } else if err != nil || len(gv.Version) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Child("apiVersion"), ownerReference.APIVersion, "must be / or ")) } - if len(gvk.Kind) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ownerReference.Kind, "must not be empty")) + if len(ownerReference.Kind) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("kind"), "must not be empty").MarkCoveredByDeclarative()) } if len(ownerReference.Name) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ownerReference.Name, "must not be empty")) + allErrs = append(allErrs, field.Required(fldPath.Child("name"), "must not be empty").MarkCoveredByDeclarative()) } if len(ownerReference.UID) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), ownerReference.UID, "must not be empty")) + allErrs = append(allErrs, field.Required(fldPath.Child("uid"), "must not be empty").MarkCoveredByDeclarative()) } + gvk := gv.WithKind(ownerReference.Kind) if _, ok := BannedOwners[gvk]; ok { allErrs = append(allErrs, field.Invalid(fldPath, ownerReference, fmt.Sprintf("%s is disallowed from being an owner", gvk))) } @@ -92,8 +98,8 @@ func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field func ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} firstControllerName := "" - for _, ref := range ownerReferences { - allErrs = append(allErrs, validateOwnerReference(ref, fldPath)...) + for idx, ref := range ownerReferences { + allErrs = append(allErrs, validateOwnerReference(ref, fldPath.Index(idx))...) if ref.Controller != nil && *ref.Controller { curControllerName := ref.Kind + "/" + ref.Name if firstControllerName != "" { @@ -136,6 +142,25 @@ func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) fie return allErrs } +// ValidateObjectMetaDeclaratively validates an ObjectMeta instance declaratively and deduplicates handwritten errors. +// betaEnabled controls whether declarative validation rules at the Beta stability level are enforced. +// NOTE: This method should be used in the types for which declarative validation is not enabled yet or cannot be enabled. The types +// for which declarative validation is enabled and valdiation code is generated must use ValidateObjectMeta and ValidateObjectMetaUpdate. +func ValidateObjectMetaDeclaratively(ctx context.Context, op operation.Type, obj, oldObj *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path, betaEnabled bool) field.ErrorList { + var errs field.ErrorList + switch op { + case operation.Create: + errs = ValidateObjectMeta(obj, requiresNamespace, nameFn, fldPath) + case operation.Update: + errs = ValidateObjectMetaUpdate(obj, oldObj, fldPath) + } + dvErrs := v1validation.Validate_ObjectMeta(ctx, operation.Operation{Type: op}, fldPath, obj, oldObj) + enforcedDVErrs := validate.FilterEnforcedDeclarativeErrors(ctx, dvErrs, betaEnabled) + errs = errs.MarkFromImperative() + errs = validate.FilterCoveredHandwrittenErrors(ctx, errs, enforcedDVErrs, betaEnabled) + return append(errs, enforcedDVErrs...) +} + // ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already // been performed. func ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList { @@ -262,12 +287,12 @@ func validateObjectMetaAccessorWithOptsCommon(meta metav1.Object, isNamespaced b } } - allErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child("generation"))...) + allErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child("generation")).MarkCoveredByDeclarative()...) allErrs = append(allErrs, v1validation.ValidateLabels(meta.GetLabels(), fldPath.Child("labels"))...) allErrs = append(allErrs, ValidateAnnotations(meta.GetAnnotations(), fldPath.Child("annotations"))...) allErrs = append(allErrs, ValidateOwnerReferences(meta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...) allErrs = append(allErrs, ValidateFinalizers(meta.GetFinalizers(), fldPath.Child("finalizers"))...) - allErrs = append(allErrs, v1validation.ValidateManagedFields(meta.GetManagedFields(), fldPath.Child("managedFields"))...) + allErrs = append(allErrs, v1validation.ValidateManagedFields(meta.GetManagedFields(), fldPath.Child("managedFields"), v1validation.CoveredByDeclarative)...) return allErrs } @@ -323,21 +348,22 @@ func ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *f } // Generation shouldn't be decremented + allErrs = append(allErrs, ValidateNonnegativeField(newMeta.GetGeneration(), fldPath.Child("generation")).MarkCoveredByDeclarative()...) if newMeta.GetGeneration() < oldMeta.GetGeneration() { allErrs = append(allErrs, field.Invalid(fldPath.Child("generation"), newMeta.GetGeneration(), "must not be decremented")) } allErrs = append(allErrs, ValidateImmutableField(newMeta.GetName(), oldMeta.GetName(), fldPath.Child("name"))...) allErrs = append(allErrs, ValidateImmutableField(newMeta.GetNamespace(), oldMeta.GetNamespace(), fldPath.Child("namespace"))...) - allErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child("uid"))...) - allErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child("creationTimestamp"))...) - allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionTimestamp(), oldMeta.GetDeletionTimestamp(), fldPath.Child("deletionTimestamp"))...) - allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionGracePeriodSeconds(), oldMeta.GetDeletionGracePeriodSeconds(), fldPath.Child("deletionGracePeriodSeconds"))...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child("uid")).WithOrigin("immutable").MarkCoveredByDeclarative()...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child("creationTimestamp")).WithOrigin("immutable").MarkCoveredByDeclarative()...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionTimestamp(), oldMeta.GetDeletionTimestamp(), fldPath.Child("deletionTimestamp")).WithOrigin("immutable").MarkCoveredByDeclarative()...) + allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionGracePeriodSeconds(), oldMeta.GetDeletionGracePeriodSeconds(), fldPath.Child("deletionGracePeriodSeconds")).WithOrigin("immutable").MarkCoveredByDeclarative()...) allErrs = append(allErrs, v1validation.ValidateLabels(newMeta.GetLabels(), fldPath.Child("labels"))...) allErrs = append(allErrs, ValidateAnnotations(newMeta.GetAnnotations(), fldPath.Child("annotations"))...) allErrs = append(allErrs, ValidateOwnerReferences(newMeta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...) - allErrs = append(allErrs, v1validation.ValidateManagedFields(newMeta.GetManagedFields(), fldPath.Child("managedFields"))...) + allErrs = append(allErrs, v1validation.ValidateManagedFields(newMeta.GetManagedFields(), fldPath.Child("managedFields"), v1validation.CoveredByDeclarative)...) return allErrs } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto index d03a73314..afc9b250f 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto @@ -179,6 +179,9 @@ message ApplyOptions { // // +patchStrategy=merge // // +listType=map // // +listMapKey=type +// // +k8s:alpha(since: "1.37")=+k8s:optional +// // +k8s:alpha(since: "1.37")=+k8s:listType=map +// // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type // Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // // // other fields @@ -193,12 +196,14 @@ message Condition { // +kubebuilder:validation: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:MaxLength=316 + // +k8s:alpha(since: "1.37")=+k8s:required optional string type = 1; // status of the condition, one of True, False, Unknown. // +required // +kubebuilder:validation:Required // +kubebuilder:validation:Enum=True;False;Unknown + // +k8s:alpha(since: "1.37")=+k8s:required optional string status = 2; // observedGeneration represents the .metadata.generation that the condition was set based upon. @@ -206,6 +211,8 @@ message Condition { // with respect to the current state of the instance. // +optional // +kubebuilder:validation:Minimum=0 + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:minimum=0 optional int64 observedGeneration = 3; // lastTransitionTime is the last time the condition transitioned from one status to another. @@ -214,6 +221,7 @@ message Condition { // +kubebuilder:validation:Required // +kubebuilder:validation:Type=string // +kubebuilder:validation:Format=date-time + // +k8s:alpha(since: "1.37")=+k8s:customValidation optional Time lastTransitionTime = 4; // reason contains a programmatic identifier indicating the reason for the condition's last transition. @@ -226,6 +234,8 @@ message Condition { // +kubebuilder:validation:MaxLength=1024 // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:Pattern=`^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$` + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:maxBytes=1024 optional string reason = 5; // message is a human readable message indicating details about the transition. @@ -700,6 +710,7 @@ message ManagedFieldsEntry { // Operation is the type of operation which lead to this ManagedFieldsEntry being created. // The only valid values for this field are 'Apply' and 'Update'. + // +k8s:alpha(since: "1.37")=+k8s:required optional string operation = 2; // APIVersion defines the version of this resource that this field set @@ -802,6 +813,8 @@ message ObjectMeta { // Read-only. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable optional string uid = 5; // An opaque value that represents the internal version of this object that can @@ -820,6 +833,8 @@ message ObjectMeta { // A sequence number representing a specific generation of the desired state. // Populated by the system. Read-only. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:minimum=0 optional int64 generation = 7; // CreationTimestamp is a timestamp representing the server time when this object was @@ -831,6 +846,7 @@ message ObjectMeta { // Null for lists. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable optional Time creationTimestamp = 8; // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This @@ -852,6 +868,8 @@ message ObjectMeta { // Read-only. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable optional Time deletionTimestamp = 9; // Number of seconds allowed for this object to gracefully terminate before @@ -859,6 +877,8 @@ message ObjectMeta { // May only be shortened. // Read-only. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable optional int64 deletionGracePeriodSeconds = 10; // Map of string keys and values that can be used to organize and categorize @@ -884,6 +904,7 @@ message ObjectMeta { // +patchStrategy=merge // +listType=map // +listMapKey=uid + // +k8s:alpha(since:"1.37")=+k8s:optional repeated OwnerReference ownerReferences = 13; // Must be empty before the object is deleted from the registry. Each entry @@ -914,6 +935,7 @@ message ObjectMeta { // // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional repeated ManagedFieldsEntry managedFields = 17; } @@ -923,18 +945,22 @@ message ObjectMeta { // +structType=atomic message OwnerReference { // API version of the referent. + // +k8s:alpha(since:"1.37")=+k8s:required optional string apiVersion = 5; // Kind of the referent. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since:"1.37")=+k8s:required optional string kind = 1; // Name of the referent. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + // +k8s:alpha(since:"1.37")=+k8s:required optional string name = 3; // UID of the referent. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + // +k8s:alpha(since:"1.37")=+k8s:required optional string uid = 4; // If true, this reference points to the managing controller. @@ -960,6 +986,7 @@ message PartialObjectMetadata { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType optional ObjectMeta metadata = 1; } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go index c8b87f20c..f88212e15 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go @@ -176,6 +176,8 @@ type ObjectMeta struct { // Read-only. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable UID types.UID `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"` // An opaque value that represents the internal version of this object that can @@ -194,6 +196,8 @@ type ObjectMeta struct { // A sequence number representing a specific generation of the desired state. // Populated by the system. Read-only. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:minimum=0 Generation int64 `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"` // CreationTimestamp is a timestamp representing the server time when this object was @@ -205,6 +209,7 @@ type ObjectMeta struct { // Null for lists. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:alpha(since: "1.37")=+k8s:immutable CreationTimestamp Time `json:"creationTimestamp,omitempty,omitzero" protobuf:"bytes,8,opt,name=creationTimestamp"` // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This @@ -226,6 +231,8 @@ type ObjectMeta struct { // Read-only. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable DeletionTimestamp *Time `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"` // Number of seconds allowed for this object to gracefully terminate before @@ -233,6 +240,8 @@ type ObjectMeta struct { // May only be shortened. // Read-only. // +optional + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:immutable DeletionGracePeriodSeconds *int64 `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"` // Map of string keys and values that can be used to organize and categorize @@ -258,6 +267,7 @@ type ObjectMeta struct { // +patchStrategy=merge // +listType=map // +listMapKey=uid + // +k8s:alpha(since:"1.37")=+k8s:optional OwnerReferences []OwnerReference `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"` // Must be empty before the object is deleted from the registry. Each entry @@ -292,6 +302,7 @@ type ObjectMeta struct { // // +optional // +listType=atomic + // +k8s:alpha(since: "1.37")=+k8s:optional ManagedFields []ManagedFieldsEntry `json:"managedFields,omitempty" protobuf:"bytes,17,rep,name=managedFields"` } @@ -314,15 +325,19 @@ const ( // +structType=atomic type OwnerReference struct { // API version of the referent. + // +k8s:alpha(since:"1.37")=+k8s:required APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"` // Kind of the referent. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + // +k8s:alpha(since:"1.37")=+k8s:required Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` // Name of the referent. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names + // +k8s:alpha(since:"1.37")=+k8s:required Name string `json:"name" protobuf:"bytes,3,opt,name=name"` // UID of the referent. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids + // +k8s:alpha(since:"1.37")=+k8s:required UID types.UID `json:"uid" protobuf:"bytes,4,opt,name=uid,casttype=k8s.io/apimachinery/pkg/types.UID"` // If true, this reference points to the managing controller. // +optional @@ -344,7 +359,7 @@ type OwnerReference struct { // ListOptions is the query options to a standard REST list call. type ListOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // A selector to restrict the list of returned objects by their labels. // Defaults to everything. @@ -517,7 +532,7 @@ const ( // GetOptions is the standard query options to the standard REST get call. type GetOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // resourceVersion sets a constraint on what resource versions a request may be served from. // See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for // details. @@ -557,7 +572,7 @@ const ( // DeleteOptions may be provided when deleting an API object. type DeleteOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // The duration in seconds before the object should be deleted. Value must be non-negative integer. // The value zero indicates delete immediately. If this value is nil, the default grace period for the @@ -629,7 +644,7 @@ const ( // CreateOptions may be provided when creating an API object. type CreateOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // When present, indicates that modifications should not be // persisted. An invalid or unrecognized dryRun directive will @@ -674,7 +689,7 @@ type CreateOptions struct { // PatchOptions may be provided when patching an API object. // PatchOptions is meant to be a superset of UpdateOptions. type PatchOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // When present, indicates that modifications should not be // persisted. An invalid or unrecognized dryRun directive will @@ -726,7 +741,7 @@ type PatchOptions struct { // ApplyOptions is equivalent to PatchOptions. It is provided as a convenience with documentation // that speaks specifically to how the options fields relate to apply. type ApplyOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // When present, indicates that modifications should not be // persisted. An invalid or unrecognized dryRun directive will @@ -759,7 +774,7 @@ func (o ApplyOptions) ToPatchOptions() PatchOptions { // UpdateOptions may be provided when updating an API object. // All fields in UpdateOptions should also be present in PatchOptions. type UpdateOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // When present, indicates that modifications should not be // persisted. An invalid or unrecognized dryRun directive will @@ -811,7 +826,7 @@ type Preconditions struct { // Status is a return value for calls that don't return other objects. type Status struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1131,7 +1146,7 @@ const ( // List holds a list of objects, which may not be known by the server. type List struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1147,7 +1162,7 @@ type List struct { // +protobuf.options.(gogoproto.goproto_stringer)=false // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type APIVersions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // versions are the api versions that are available. // +listType=atomic Versions []string `json:"versions" protobuf:"bytes,1,rep,name=versions"` @@ -1167,7 +1182,7 @@ type APIVersions struct { // APIGroupList is a list of APIGroup, to allow clients to discover the API at // /apis. type APIGroupList struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // groups is a list of APIGroup. // +listType=atomic Groups []APIGroup `json:"groups" protobuf:"bytes,1,rep,name=groups"` @@ -1178,7 +1193,7 @@ type APIGroupList struct { // APIGroup contains the name, the supported versions, and the preferred version // of a group. type APIGroup struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // name is the name of the group. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // versions are the versions supported in this group. @@ -1273,7 +1288,7 @@ func (vs Verbs) String() string { // resources supported in a specific group and version, and if the resource // is namespaced. type APIResourceList struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // groupVersion is the group and version this APIResourceList is for. GroupVersion string `json:"groupVersion" protobuf:"bytes,1,opt,name=groupVersion"` // resources contains the name of the resources and if they are namespaced. @@ -1394,6 +1409,7 @@ type ManagedFieldsEntry struct { Manager string `json:"manager,omitempty" protobuf:"bytes,1,opt,name=manager"` // Operation is the type of operation which lead to this ManagedFieldsEntry being created. // The only valid values for this field are 'Apply' and 'Update'. + // +k8s:alpha(since: "1.37")=+k8s:required Operation ManagedFieldsOperationType `json:"operation,omitempty" protobuf:"bytes,2,opt,name=operation,casttype=ManagedFieldsOperationType"` // APIVersion defines the version of this resource that this field set // applies to. The format is "group/version" just like the top-level @@ -1429,6 +1445,7 @@ type ManagedFieldsEntry struct { } // ManagedFieldsOperationType is the type of operation which lead to a ManagedFieldsEntry being created. +// +k8s:alpha(since: "1.37")=+k8s:enum type ManagedFieldsOperationType string const ( @@ -1446,7 +1463,7 @@ const ( // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +protobuf=false type Table struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1537,6 +1554,7 @@ const ( RowCompleted RowConditionType = "Completed" ) +// +k8s:alpha(since: "1.37")=+k8s:enum type ConditionStatus string // These are valid condition statuses. "ConditionTrue" means a resource is in the condition. @@ -1565,7 +1583,7 @@ const ( // +k8s:conversion-gen:explicit-from=net/url.Values // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type TableOptions struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // NoHeaders is only exposed for internal callers. It is not included in our OpenAPI definitions // and may be removed as a field in a future release. @@ -1582,17 +1600,18 @@ type TableOptions struct { // to get access to a particular ObjectMeta schema without knowing the details of the version. // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PartialObjectMetadata struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata // +optional + // +k8s:opaqueType ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` } // PartialObjectMetadataList contains a list of objects containing only their metadata // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PartialObjectMetadataList struct { - TypeMeta `json:",inline"` + TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional @@ -1613,6 +1632,9 @@ type PartialObjectMetadataList struct { // // +patchStrategy=merge // // +listType=map // // +listMapKey=type +// // +k8s:alpha(since: "1.37")=+k8s:optional +// // +k8s:alpha(since: "1.37")=+k8s:listType=map +// // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type // Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // // // other fields @@ -1627,17 +1649,21 @@ type Condition struct { // +kubebuilder:validation: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:MaxLength=316 + // +k8s:alpha(since: "1.37")=+k8s:required Type string `json:"type" protobuf:"bytes,1,opt,name=type"` // status of the condition, one of True, False, Unknown. // +required // +kubebuilder:validation:Required // +kubebuilder:validation:Enum=True;False;Unknown + // +k8s:alpha(since: "1.37")=+k8s:required Status ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status"` // 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. // +optional // +kubebuilder:validation:Minimum=0 + // +k8s:alpha(since: "1.37")=+k8s:optional + // +k8s:alpha(since: "1.37")=+k8s:minimum=0 ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,3,opt,name=observedGeneration"` // 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. @@ -1645,6 +1671,7 @@ type Condition struct { // +kubebuilder:validation:Required // +kubebuilder:validation:Type=string // +kubebuilder:validation:Format=date-time + // +k8s:alpha(since: "1.37")=+k8s:customValidation LastTransitionTime Time `json:"lastTransitionTime" protobuf:"bytes,4,opt,name=lastTransitionTime"` // 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, @@ -1656,6 +1683,8 @@ type Condition struct { // +kubebuilder:validation:MaxLength=1024 // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:Pattern=`^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$` + // +k8s:alpha(since: "1.37")=+k8s:required + // +k8s:alpha(since: "1.37")=+k8s:maxBytes=1024 Reason string `json:"reason" protobuf:"bytes,5,opt,name=reason"` // message is a human readable message indicating details about the transition. // This may be an empty string. diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go index 59f43b7bf..592445d9c 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go @@ -523,6 +523,7 @@ func NewJSONFallbackEncoder(encoder runtime.Encoder) runtime.Encoder { } identifier, err := gojson.Marshal(result) if err != nil { + //nolint:logcheck // Should not be reached. klog.Fatalf("Failed marshaling identifier for jsonFallbackEncoder: %v", err) } return &jsonFallbackEncoder{ diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/doc.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/doc.go new file mode 100644 index 000000000..3b9cb30f2 --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/doc.go @@ -0,0 +1,21 @@ +/* +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. +*/ + +// +k8s:validation-gen=TypesWithField=TypeMeta +// +k8s:validation-gen-input=k8s.io/apimachinery/pkg/apis/meta/v1 + +// Package validation holds generated validations for meta/v1 types. +package validation diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go index d0ca20013..b9ec34427 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go @@ -17,10 +17,12 @@ limitations under the License. package validation import ( + "context" "fmt" "regexp" "unicode" + "k8s.io/apimachinery/pkg/api/operation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" @@ -266,14 +268,39 @@ func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList { const MaxSubresourceNameLength = 256 -func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path) field.ErrorList { +// ManagedFieldsValidationOption specifies options for validating managed fields. +type ManagedFieldsValidationOption int + +const ( + // CoveredByDeclarative indicates whether errors should be marked as covered by declarative validation. + CoveredByDeclarative ManagedFieldsValidationOption = iota + 1 +) + +// ValidateManagedFields validates a list of managed fields. +func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path, opts ...ManagedFieldsValidationOption) field.ErrorList { + coveredByDeclarative := false + for _, opt := range opts { + if opt == CoveredByDeclarative { + coveredByDeclarative = true + } + } var allErrs field.ErrorList for i, fields := range fieldsList { fldPath := fldPath.Index(i) switch fields.Operation { + case "": + err := field.Required(fldPath.Child("operation"), "must not be empty") + if coveredByDeclarative { + err = err.MarkCoveredByDeclarative() + } + allErrs = append(allErrs, err) case metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate: default: - allErrs = append(allErrs, field.Invalid(fldPath.Child("operation"), fields.Operation, "must be `Apply` or `Update`")) + err := field.NotSupported(fldPath.Child("operation"), fields.Operation, []metav1.ManagedFieldsOperationType{metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate}) + if coveredByDeclarative { + err = err.MarkCoveredByDeclarative() + } + allErrs = append(allErrs, err) } if len(fields.FieldsType) > 0 && fields.FieldsType != "FieldsV1" { allErrs = append(allErrs, field.Invalid(fldPath.Child("fieldsType"), fields.FieldsType, "must be `FieldsV1`")) @@ -293,7 +320,7 @@ func ValidateConditions(conditions []metav1.Condition, fldPath *field.Path) fiel conditionTypeToFirstIndex := map[string]int{} for i, condition := range conditions { if _, ok := conditionTypeToFirstIndex[condition.Type]; ok { - allErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child("type"), condition.Type)) + allErrs = append(allErrs, field.Duplicate(fldPath.Index(i), condition.Type).MarkCoveredByDeclarative()) } else { conditionTypeToFirstIndex[condition.Type] = i } @@ -316,29 +343,35 @@ func ValidateCondition(condition metav1.Condition, fldPath *field.Path) field.Er var allErrs field.ErrorList // type is set and is a valid format - allErrs = append(allErrs, ValidateLabelName(condition.Type, fldPath.Child("type"))...) + if len(condition.Type) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("type"), "is required").MarkCoveredByDeclarative()) + } else { + allErrs = append(allErrs, ValidateLabelName(condition.Type, fldPath.Child("type"))...) + } // status is set and is an accepted value - if !validConditionStatuses.Has(string(condition.Status)) { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("status"), condition.Status, validConditionStatuses.List())) + if len(condition.Status) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Child("status"), "").MarkCoveredByDeclarative()) + } else if !validConditionStatuses.Has(string(condition.Status)) { + allErrs = append(allErrs, field.NotSupported(fldPath.Child("status"), condition.Status, validConditionStatuses.List()).MarkCoveredByDeclarative()) } if condition.ObservedGeneration < 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("observedGeneration"), condition.ObservedGeneration, "must be greater than or equal to zero")) + allErrs = append(allErrs, field.Invalid(fldPath.Child("observedGeneration"), condition.ObservedGeneration, "must be greater than or equal to zero").WithOrigin("minimum").MarkCoveredByDeclarative()) } if condition.LastTransitionTime.IsZero() { - allErrs = append(allErrs, field.Required(fldPath.Child("lastTransitionTime"), "")) + allErrs = append(allErrs, field.Required(fldPath.Child("lastTransitionTime"), "").MarkCoveredByDeclarative()) } if len(condition.Reason) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("reason"), "")) + allErrs = append(allErrs, field.Required(fldPath.Child("reason"), "").MarkCoveredByDeclarative()) } else { - for _, currErr := range isValidConditionReason(condition.Reason) { + for _, currErr := range IsValidConditionReason(condition.Reason) { allErrs = append(allErrs, field.Invalid(fldPath.Child("reason"), condition.Reason, currErr)) } if len(condition.Reason) > maxReasonLen { - allErrs = append(allErrs, field.TooLong(fldPath.Child("reason"), "" /*unused*/, maxReasonLen)) + allErrs = append(allErrs, field.TooLong(fldPath.Child("reason"), "" /*unused*/, maxReasonLen).WithOrigin("maxBytes").MarkCoveredByDeclarative()) } } @@ -354,8 +387,9 @@ const conditionReasonErrMsg string = "a condition reason must start with alphabe var conditionReasonRegexp = regexp.MustCompile("^" + conditionReasonFmt + "$") -// isValidConditionReason tests for a string that conforms to rules for condition reasons. This checks the format, but not the length. -func isValidConditionReason(value string) []string { +// IsValidConditionReason tests for a string that conforms to rules for condition +// reasons. This checks the format, but not the length. +func IsValidConditionReason(value string) []string { if !conditionReasonRegexp.MatchString(value) { return []string{validation.RegexError(conditionReasonErrMsg, conditionReasonFmt, "my_name", "MY_NAME", "MyName", "ReasonA,ReasonB", "ReasonA:ReasonB")} } @@ -370,9 +404,6 @@ func ValidateIgnoreStoreReadError(fldPath *field.Path, options *metav1.DeleteOpt return allErrs } - if len(options.DryRun) > 0 { - allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .dryRun")) - } if options.PropagationPolicy != nil { allErrs = append(allErrs, field.Invalid(fldPath, true, "cannot be set together with .propagationPolicy")) } @@ -389,3 +420,14 @@ func ValidateIgnoreStoreReadError(fldPath *field.Path, options *metav1.DeleteOpt return allErrs } + +// ValidateCustom_Condition_LastTransitionTime is wired into the generated +// declarative validation by +k8s:customValidation on Condition.LastTransitionTime. +// It enforces that the field is set, mirroring the handwritten check in +// ValidateCondition. +func ValidateCustom_Condition_LastTransitionTime(ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *metav1.Time) field.ErrorList { + if value.IsZero() { + return field.ErrorList{field.Required(fldPath, "")} + } + return nil +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/zz_generated.validations.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/zz_generated.validations.go new file mode 100644 index 000000000..f79373a26 --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/zz_generated.validations.go @@ -0,0 +1,638 @@ +//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 validation-gen. DO NOT EDIT. + +package validation + +import ( + context "context" + + equality "k8s.io/apimachinery/pkg/api/equality" + operation "k8s.io/apimachinery/pkg/api/operation" + safe "k8s.io/apimachinery/pkg/api/safe" + validate "k8s.io/apimachinery/pkg/api/validate" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + field "k8s.io/apimachinery/pkg/util/validation/field" +) + +// Validate_Condition validates an instance of Condition according +// to declarative validation rules in the API schema. +func Validate_Condition( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.Condition) (errs field.ErrorList) { + + { // field v1.Condition.Type + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Condition) *string { + return &oldObj.Type + }) + errs = append(errs, fn(fldPath.Child("type"), &obj.Type, oldVal, oldObj != nil)...) + } + + { // field v1.Condition.Status + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ConditionStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_ConditionStatus(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Condition) *v1.ConditionStatus { + return &oldObj.Status + }) + errs = append(errs, fn(fldPath.Child("status"), &obj.Status, oldVal, oldObj != nil)...) + } + + { // field v1.Condition.ObservedGeneration + fn := func( + fldPath *field.Path, + obj, oldObj *int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Condition) *int64 { + return &oldObj.ObservedGeneration + }) + errs = append(errs, fn(fldPath.Child("observedGeneration"), &obj.ObservedGeneration, oldVal, oldObj != nil)...) + } + + { // field v1.Condition.LastTransitionTime + fn := func( + fldPath *field.Path, + obj, oldObj *v1.Time, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + // custom validation + if e := ValidateCustom_Condition_LastTransitionTime(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Condition) *v1.Time { + return &oldObj.LastTransitionTime + }) + errs = append(errs, fn(fldPath.Child("lastTransitionTime"), &obj.LastTransitionTime, oldVal, oldObj != nil)...) + } + + { // field v1.Condition.Reason + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxBytes(ctx, op, fldPath, obj, oldObj, 1024).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Condition) *string { + return &oldObj.Reason + }) + errs = append(errs, fn(fldPath.Child("reason"), &obj.Reason, oldVal, oldObj != nil)...) + } + + // field v1.Condition.Message has no validation + return errs +} + +var symbolsForConditionStatus = sets.New(v1.ConditionFalse, v1.ConditionTrue, v1.ConditionUnknown) + +// Validate_ConditionStatus validates an instance of ConditionStatus according +// to declarative validation rules in the API schema. +func Validate_ConditionStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ConditionStatus) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForConditionStatus, nil).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_ManagedFieldsEntry validates an instance of ManagedFieldsEntry according +// to declarative validation rules in the API schema. +func Validate_ManagedFieldsEntry( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ManagedFieldsEntry) (errs field.ErrorList) { + + // field v1.ManagedFieldsEntry.Manager has no validation + + { // field v1.ManagedFieldsEntry.Operation + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ManagedFieldsOperationType, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_ManagedFieldsOperationType(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ManagedFieldsEntry) *v1.ManagedFieldsOperationType { + return &oldObj.Operation + }) + errs = append(errs, fn(fldPath.Child("operation"), &obj.Operation, oldVal, oldObj != nil)...) + } + + // field v1.ManagedFieldsEntry.APIVersion has no validation + // field v1.ManagedFieldsEntry.Time has no validation + // field v1.ManagedFieldsEntry.FieldsType has no validation + // field v1.ManagedFieldsEntry.FieldsV1 has no validation + // field v1.ManagedFieldsEntry.Subresource has no validation + return errs +} + +var symbolsForManagedFieldsOperationType = sets.New(v1.ManagedFieldsOperationApply, v1.ManagedFieldsOperationUpdate) + +// Validate_ManagedFieldsOperationType validates an instance of ManagedFieldsOperationType according +// to declarative validation rules in the API schema. +func Validate_ManagedFieldsOperationType( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ManagedFieldsOperationType) (errs field.ErrorList) { + + if e := validate.Enum(ctx, op, fldPath, obj, oldObj, symbolsForManagedFieldsOperationType, nil).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + + return errs +} + +// Validate_ObjectMeta validates an instance of ObjectMeta according +// to declarative validation rules in the API schema. +func Validate_ObjectMeta( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ObjectMeta) (errs field.ErrorList) { + + // field v1.ObjectMeta.Name has no validation + // field v1.ObjectMeta.GenerateName has no validation + // field v1.ObjectMeta.Namespace has no validation + // field v1.ObjectMeta.SelfLink has no validation + + { // field v1.ObjectMeta.UID + fn := func( + fldPath *field.Path, + obj, oldObj *types.UID, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) *types.UID { + return &oldObj.UID + }) + errs = append(errs, fn(fldPath.Child("uid"), &obj.UID, oldVal, oldObj != nil)...) + } + + // field v1.ObjectMeta.ResourceVersion has no validation + + { // field v1.ObjectMeta.Generation + fn := func( + fldPath *field.Path, + obj, oldObj *int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0).MarkAlpha(); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) *int64 { + return &oldObj.Generation + }) + errs = append(errs, fn(fldPath.Child("generation"), &obj.Generation, oldVal, oldObj != nil)...) + } + + { // field v1.ObjectMeta.CreationTimestamp + fn := func( + fldPath *field.Path, + obj, oldObj *v1.Time, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) *v1.Time { + return &oldObj.CreationTimestamp + }) + errs = append(errs, fn(fldPath.Child("creationTimestamp"), &obj.CreationTimestamp, oldVal, oldObj != nil)...) + } + + { // field v1.ObjectMeta.DeletionTimestamp + fn := func( + fldPath *field.Path, + obj, oldObj *v1.Time, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) *v1.Time { + return oldObj.DeletionTimestamp + }) + errs = append(errs, fn(fldPath.Child("deletionTimestamp"), obj.DeletionTimestamp, oldVal, oldObj != nil)...) + } + + { // field v1.ObjectMeta.DeletionGracePeriodSeconds + fn := func( + fldPath *field.Path, + obj, oldObj *int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) *int64 { + return oldObj.DeletionGracePeriodSeconds + }) + errs = append(errs, fn(fldPath.Child("deletionGracePeriodSeconds"), obj.DeletionGracePeriodSeconds, oldVal, oldObj != nil)...) + } + + // field v1.ObjectMeta.Labels has no validation + // field v1.ObjectMeta.Annotations has no validation + + { // field v1.ObjectMeta.OwnerReferences + fn := func( + fldPath *field.Path, + obj, oldObj []v1.OwnerReference, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_OwnerReference); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) []v1.OwnerReference { + return oldObj.OwnerReferences + }) + errs = append(errs, fn(fldPath.Child("ownerReferences"), obj.OwnerReferences, oldVal, oldObj != nil)...) + } + + // field v1.ObjectMeta.Finalizers has no validation + + { // field v1.ObjectMeta.ManagedFields + fn := func( + fldPath *field.Path, + obj, oldObj []v1.ManagedFieldsEntry, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if equality.Semantic.DeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // iterate the list and call the type's validation function + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_ManagedFieldsEntry); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ObjectMeta) []v1.ManagedFieldsEntry { + return oldObj.ManagedFields + }) + errs = append(errs, fn(fldPath.Child("managedFields"), obj.ManagedFields, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_OwnerReference validates an instance of OwnerReference according +// to declarative validation rules in the API schema. +func Validate_OwnerReference( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.OwnerReference) (errs field.ErrorList) { + + { // field v1.OwnerReference.APIVersion + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.OwnerReference) *string { + return &oldObj.APIVersion + }) + errs = append(errs, fn(fldPath.Child("apiVersion"), &obj.APIVersion, oldVal, oldObj != nil)...) + } + + { // field v1.OwnerReference.Kind + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.OwnerReference) *string { + return &oldObj.Kind + }) + errs = append(errs, fn(fldPath.Child("kind"), &obj.Kind, oldVal, oldObj != nil)...) + } + + { // field v1.OwnerReference.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.OwnerReference) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field v1.OwnerReference.UID + fn := func( + fldPath *field.Path, + obj, oldObj *types.UID, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkAlpha().MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.OwnerReference) *types.UID { + return &oldObj.UID + }) + errs = append(errs, fn(fldPath.Child("uid"), &obj.UID, oldVal, oldObj != nil)...) + } + + // field v1.OwnerReference.Controller has no validation + // field v1.OwnerReference.BlockOwnerDeletion has no validation + return errs +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go index 68f261cc1..1cda0840a 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/types.go @@ -62,7 +62,7 @@ type PartialObjectMetadata = v1.PartialObjectMetadata // PartialObjectMetadataList contains a list of objects containing only their metadata. // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type PartialObjectMetadataList struct { - v1.TypeMeta `json:",inline"` + v1.TypeMeta `json:""` // Standard list metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds // +optional diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go b/constraint/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go index b0a9246d9..5eb25e2e8 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go @@ -34,8 +34,8 @@ type Unmarshaler interface { } func jsonTag(field reflect.StructField) (string, bool) { - structTag := field.Tag.Get("json") - if len(structTag) == 0 { + structTag, exists := field.Tag.Lookup("json") + if !exists || len(structTag) == 0 { return "", false } parts := strings.Split(structTag, ",") diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/labels/selector.go b/constraint/vendor/k8s.io/apimachinery/pkg/labels/selector.go index 031dcd21b..f31a890f2 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/labels/selector.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/labels/selector.go @@ -269,13 +269,15 @@ func (r *Requirement) Matches(ls Labels) bool { } lsValue, err := strconv.ParseInt(val, 10, 64) if err != nil { - klog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", val, ls, err) + //nolint:logcheck // Extending the API is not worth it for contextual, structured logging of this. + klog.V(10).InfoS("ParseInt failed", "value", val, "label", ls, "err", err) return false } // There should be only one strValue in r.strValues, and can be converted to an integer. if len(r.strValues) != 1 { - klog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r) + //nolint:logcheck // Extending the API is not worth it for contextual, structured logging of this. + klog.V(10).InfoS("Invalid values count: for 'Gt', 'Lt' operators, exactly one value is required", "count", len(r.strValues), "requirement", r) return false } @@ -283,7 +285,8 @@ func (r *Requirement) Matches(ls Labels) bool { for i := range r.strValues { rValue, err = strconv.ParseInt(r.strValues[i], 10, 64) if err != nil { - klog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r) + //nolint:logcheck // Extending the API is not worth it for contextual, structured logging of this. + klog.V(10).InfoS("ParseInt failed: for 'Gt', 'Lt' operators, the value must be an integer", "value", r.strValues[i], "requirement", r, "err", err) return false } } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/codec.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/codec.go index 73f85286c..654835b3e 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/codec.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/codec.go @@ -226,6 +226,7 @@ func identifier(e Encoder) Identifier { } identifier, err := json.Marshal(result) if err != nil { + //nolint:logcheck // Should not be reached. klog.Fatalf("Failed marshaling identifier for base64Serializer: %v", err) } return Identifier(identifier) @@ -390,6 +391,7 @@ func (v multiGroupVersioner) Identifier() string { } identifier, err := json.Marshal(result) if err != nil { + //nolint:logcheck // Should not be reached. klog.Fatalf("Failed marshaling Identifier for %#v: %v", v, err) } return string(identifier) diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go index d04d701f3..7cef382de 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go @@ -20,7 +20,6 @@ package runtime import ( "fmt" - "reflect" "strconv" "strings" @@ -41,18 +40,6 @@ func DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, } } -// JSONKeyMapper uses the struct tags on a conversion to determine the key value for -// the other side. Use when mapping from a map[string]* to a struct or vice versa. -func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) { - if s := destTag.Get("json"); len(s) > 0 { - return strings.SplitN(s, ",", 2)[0], key - } - if s := sourceTag.Get("json"); len(s) > 0 { - return key, strings.SplitN(s, ",", 2)[0] - } - return key, key -} - func Convert_Slice_string_To_string(in *[]string, out *string, s conversion.Scope) error { if len(*in) == 0 { *out = "" diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/converter.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/converter.go index b1a300959..5aa118f58 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/converter.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/converter.go @@ -251,9 +251,11 @@ func (c *unstructuredConverter) FromUnstructuredWithValidation(u map[string]inte newObj := reflect.New(t.Elem()).Interface() newErr := fromUnstructuredViaJSON(u, newObj) if (err != nil) != (newErr != nil) { + //nolint:logcheck // Should not be reached. klog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err) } if err == nil && !c.comparison.DeepEqual(obj, newObj) { + //nolint:logcheck // Should not be reached. klog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj) } } @@ -376,8 +378,8 @@ func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo { // Cache miss - we need to compute the field name. info := &fieldInfo{} typeField := structType.Field(field) - jsonTag := typeField.Tag.Get("json") - if len(jsonTag) == 0 { + jsonTag, exists := typeField.Tag.Lookup("json") + if !exists || len(jsonTag) == 0 { if !typeField.Anonymous { // match stdlib behavior for naming fields that don't specify a json tag name info.name = typeField.Name @@ -385,7 +387,10 @@ func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo { } else { items := strings.Split(jsonTag, ",") info.name = items[0] - if len(info.name) == 0 && !typeField.Anonymous { + if isInlinedFromTag(typeField, items[0], items[1:]) { + // match stdlib behavior when controlled by tag + info.name = "" + } else if len(info.name) == 0 && !typeField.Anonymous { // match stdlib behavior for naming fields that don't specify a json tag name info.name = typeField.Name } @@ -596,9 +601,11 @@ func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]inte newUnstr := map[string]interface{}{} newErr := toUnstructuredViaJSON(obj, &newUnstr) if (err != nil) != (newErr != nil) { + //nolint:logcheck // Should not be reached. klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr) } if err == nil && !c.comparison.DeepEqual(u, newUnstr) { + //nolint:logcheck // Should not be reached. klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr) } } @@ -680,11 +687,11 @@ func toUnstructured(sv, dv reflect.Value) error { dv.Set(reflect.ValueOf(sv.Int())) return nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - uVal := sv.Uint() - if uVal > math.MaxInt64 { - return fmt.Errorf("unsigned value %d does not fit into int64 (overflow)", uVal) + val, err := uintToUnstructuredHelper(sv.Uint()) + if err != nil { + return err } - dv.Set(reflect.ValueOf(int64(uVal))) + dv.Set(reflect.ValueOf(val)) return nil case reflect.Float32, reflect.Float64: dv.Set(reflect.ValueOf(sv.Float())) @@ -846,7 +853,11 @@ func structToUnstructured(sv, dv reflect.Value) error { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: realMap[fieldInfo.name] = fv.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - realMap[fieldInfo.name] = fv.Uint() + val, err := uintToUnstructuredHelper(fv.Uint()) + if err != nil { + return err + } + realMap[fieldInfo.name] = val case reflect.Float32, reflect.Float64: realMap[fieldInfo.name] = fv.Float() default: @@ -867,3 +878,10 @@ func interfaceToUnstructured(sv, dv reflect.Value) error { } return toUnstructured(sv.Elem(), dv) } + +func uintToUnstructuredHelper(uVal uint64) (int64, error) { + if uVal > math.MaxInt64 { + return 0, fmt.Errorf("unsigned value %d does not fit into int64 (overflow)", uVal) + } + return int64(uVal), nil +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_126.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_126.go new file mode 100644 index 000000000..686ff6abb --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_126.go @@ -0,0 +1,26 @@ +//go:build !go1.27 + +/* +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 runtime + +import "reflect" + +func isInlinedFromTag(fieldType reflect.StructField, tagName string, tagDirectives []string) bool { + // go <1.27 doesn't honor ",inline" + return false +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_127.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_127.go new file mode 100644 index 000000000..abaa79a2d --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/fieldinfo_127.go @@ -0,0 +1,33 @@ +//go:build go1.27 + +/* +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 runtime + +import ( + "reflect" +) + +func isInlinedFromTag(field reflect.StructField, tagName string, tagDirectives []string) bool { + fieldType := field.Type + if fieldType.Kind() == reflect.Pointer && fieldType.Name() == "" { + // optionally unwrap a single level + fieldType = fieldType.Elem() + } + // TODO: when switching to direct use of json/v2, error on non-struct embedding and use of embed with other directives + return fieldType.Kind() == reflect.Struct && tagName == "" && len(tagDirectives) == 1 && tagDirectives[0] == "embed" +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto index 5f06cc574..93d187d94 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/generated.proto @@ -33,7 +33,7 @@ option go_package = "k8s.io/apimachinery/pkg/runtime"; // // Internal package: // // type MyAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // MyPlugin runtime.Object `json:"myPlugin"` // } // @@ -44,7 +44,7 @@ option go_package = "k8s.io/apimachinery/pkg/runtime"; // // External package: // // type MyAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // MyPlugin runtime.RawExtension `json:"myPlugin"` // } // @@ -85,7 +85,7 @@ message RawExtension { // like this: // // type MyAwesomeAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // ... // other fields // } // diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/helper.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/helper.go index 395dfdbd0..242a34986 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/helper.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/helper.go @@ -285,20 +285,26 @@ func (e *encoderWithAllocator) Identifier() Identifier { return e.encoder.Identifier() } +// The legacy discovery endpoint requires that its response Encoder implement Serializer. +// https://github.com/kubernetes/kubernetes/blob/4a1340bfd58fdb3846d4342c101e0bcb574fbfb1/staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go#L101-L107 +var _ Serializer = nondeterministicEncoderToEncoderAdapter{} + type nondeterministicEncoderToEncoderAdapter struct { NondeterministicEncoder + + Decoder } func (e nondeterministicEncoderToEncoderAdapter) Encode(obj Object, w io.Writer) error { return e.EncodeNondeterministic(obj, w) } -// UseNondeterministicEncoding returns an Encoder that encodes objects using the provided Encoder's -// EncodeNondeterministic method if it implements NondeterministicEncoder, otherwise it returns the -// provided Encoder as-is. -func UseNondeterministicEncoding(encoder Encoder) Encoder { - if nondeterministic, ok := encoder.(NondeterministicEncoder); ok { - return nondeterministicEncoderToEncoderAdapter{nondeterministic} +// UseNondeterministicEncoding returns an Encoder that encodes objects using the provided +// Serializer's EncodeNondeterministic method if it implements NondeterministicEncoder, otherwise it +// returns the provided Serializer as-is. +func UseNondeterministicEncoding(serializer Serializer) Encoder { + if nondeterministic, ok := serializer.(NondeterministicEncoder); ok { + return nondeterministicEncoderToEncoderAdapter{NondeterministicEncoder: nondeterministic, Decoder: serializer} } - return encoder + return serializer } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go index e2fbeabdd..80662e55c 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go @@ -370,7 +370,7 @@ func (s *Scheme) AddValidationFunc(srcType Object, fn func(ctx context.Context, // Validate validates the provided Object according to the generated declarative validation code. // WARNING: This does not validate all objects! The handwritten validation code in validation.go // is not run when this is called. Only the generated zz_generated.validations.go validation code is run. -func (s *Scheme) Validate(ctx context.Context, options []string, object Object, subresources ...string) field.ErrorList { +func (s *Scheme) Validate(ctx context.Context, options map[string]bool, object Object, subresources ...string) field.ErrorList { if fn, ok := s.validationFuncs[reflect.TypeOf(object)]; ok { return fn(ctx, operation.Operation{Type: operation.Create, Request: operation.Request{Subresources: subresources}, Options: options}, object, nil) } @@ -380,13 +380,21 @@ func (s *Scheme) Validate(ctx context.Context, options []string, object Object, // ValidateUpdate validates the provided object and oldObject according to the generated declarative validation code. // WARNING: This does not validate all objects! The handwritten validation code in validation.go // is not run when this is called. Only the generated zz_generated.validations.go validation code is run. -func (s *Scheme) ValidateUpdate(ctx context.Context, options []string, object, oldObject Object, subresources ...string) field.ErrorList { +func (s *Scheme) ValidateUpdate(ctx context.Context, options map[string]bool, object, oldObject Object, subresources ...string) field.ErrorList { if fn, ok := s.validationFuncs[reflect.TypeOf(object)]; ok { return fn(ctx, operation.Operation{Type: operation.Update, Request: operation.Request{Subresources: subresources}, Options: options}, object, oldObject) } return nil } +// HasValidationFunc reports whether a validation function is registered for the +// object's type. Unlike Validate, it distinguishes "no function registered" from +// "function ran and found no errors", which both yield a nil error list. +func (s *Scheme) HasValidationFunc(obj Object) bool { + _, ok := s.validationFuncs[reflect.TypeOf(obj)] + return ok +} + // Convert will attempt to convert in into out. Both must be pointers. For easy // testing of conversion functions. Returns an error if the conversion isn't // possible. You can call this with types that haven't been registered (for example, diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/cbor.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/cbor.go index 118579ec3..e5730e3c5 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/cbor.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/cbor.go @@ -68,8 +68,9 @@ type Serializer interface { var _ Serializer = &serializer{} type options struct { - strict bool - transcode bool + strict bool + transcode bool + streamingCollectionsEncoding bool } type Option func(*options) @@ -92,6 +93,13 @@ func Transcode(s bool) Option { } } +// StreamingCollectionsEncoding is used for testing purposes only. +func StreamingCollectionsEncoding(s bool) Option { + return func(opts *options) { + opts.streamingCollectionsEncoding = s + } +} + type serializer struct { metaFactory metaFactory creater runtime.ObjectCreater @@ -114,6 +122,7 @@ func newSerializer(metaFactory metaFactory, creater runtime.ObjectCreater, typer typer: typer, } s.options.transcode = true + s.options.streamingCollectionsEncoding = true for _, o := range options { o(&s.options) } @@ -147,15 +156,25 @@ func (s *serializer) EncodeNondeterministic(obj runtime.Object, w io.Writer) err } func (s *serializer) encode(mode modes.EncMode, obj runtime.Object, w io.Writer) error { + if _, err := w.Write(selfDescribedCBOR); err != nil { + return err + } + + if s.options.streamingCollectionsEncoding { + ok, err := streamEncodeCollections(obj, w, mode) + if err != nil { + return err + } + if ok { + return nil + } + } + var v interface{} = obj if u, ok := obj.(runtime.Unstructured); ok { v = u.UnstructuredContent() } - if _, err := w.Write(selfDescribedCBOR); err != nil { - return err - } - return mode.MarshalTo(v, w) } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/collections.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/collections.go new file mode 100644 index 000000000..5aa0fb7ca --- /dev/null +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/collections.go @@ -0,0 +1,328 @@ +/* +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 cbor + +import ( + "encoding/json" + "fmt" + "io" + "maps" + "math/rand" + "reflect" + "slices" + "sort" + + "k8s.io/apimachinery/pkg/conversion" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes" + + "github.com/fxamacker/cbor/v2" +) + +func streamEncodeCollections(obj runtime.Object, w io.Writer, mode modes.EncMode) (bool, error) { + list, ok := obj.(*unstructured.UnstructuredList) + if ok { + return true, streamingEncodeUnstructuredList(w, list, mode) + } + if _, ok := obj.(cbor.Marshaler); ok { + return false, nil + } + if _, ok := obj.(json.Marshaler); ok { + return false, nil + } + typeMeta, listMeta, items, err := getListMeta(obj) + if err == nil { + return true, streamingEncodeList(w, typeMeta, listMeta, items, mode) + } + return false, nil +} + +// getListMeta implements list extraction logic for cbor stream serialization. +func getListMeta(list runtime.Object) (metav1.TypeMeta, metav1.ListMeta, []interface{}, error) { + listValue, err := conversion.EnforcePtr(list) + if err != nil { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, err + } + listType := listValue.Type() + if listType.NumField() != 3 { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected ListType to have 3 fields") + } + // The streaming encoder reproduces the field names and layout implied by the + // json struct tags (kind, apiVersion, metadata, items). The CBOR encoder, + // however, gives a "cbor" struct tag precedence over "json", so a cbor tag on + // any of these fields could rename a key, change its options (e.g. keyasint), + // or un-inline the embedded TypeMeta -- diverging from the streamed output. + // Refuse to stream such a type and fall back to the general encoder, which + // honors the cbor tag correctly. + for i := 0; i < listType.NumField(); i++ { + if _, ok := listType.Field(i).Tag.Lookup("cbor"); ok { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected list field %d to have no cbor tag", i) + } + } + // TypeMeta + typeMeta, ok := listValue.Field(0).Interface().(metav1.TypeMeta) + if !ok { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected TypeMeta field to have TypeMeta type") + } + if !listType.Field(0).Anonymous { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be embedded`) + } + if jsonTag, jsonTagExists := listType.Field(0).Tag.Lookup("json"); !jsonTagExists { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag`) + } else if jsonTag != "" && jsonTag != ",inline" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be "" or ",inline"`) + } + // ListMeta + listMeta, ok := listValue.Field(1).Interface().(metav1.ListMeta) + if !ok { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected ListMeta field to have ListMeta type") + } + if listType.Field(1).Tag.Get("json") != "metadata,omitempty" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected ListMeta json field tag to be "metadata,omitempty"`) + } + // Items + if listType.Field(2).Tag.Get("json") != "items" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected Items json field tag to be "items"`) + } + items, err := getListItems(listValue.Field(2)) + if err != nil { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, err + } + return typeMeta, listMeta, items, nil +} + +// getListItems returns the elements of a list's Items field as addressable +// values. Marshaling each element directly (rather than routing through +// meta.ExtractList) preserves the element's own type and custom marshaler, so +// that e.g. a metav1.List whose Items are runtime.RawExtension holding CBOR +// bytes are encoded verbatim by runtime.RawExtension.MarshalCBOR instead of +// being flattened into a runtime.Unknown (which has no MarshalCBOR and would be +// misencoded as a struct or fail JSON transcoding). +// +// A nil Items slice returns a nil result, distinct from an empty non-nil slice, +// so the encoder can emit CBOR null rather than an empty array. +func getListItems(itemsValue reflect.Value) ([]interface{}, error) { + if itemsValue.Kind() != reflect.Slice { + return nil, fmt.Errorf("expected Items field to be a slice, got %s", itemsValue.Kind()) + } + if itemsValue.IsNil() { + return nil, nil + } + items := make([]interface{}, itemsValue.Len()) + for i := range items { + items[i] = itemsValue.Index(i).Addr().Interface() + } + return items, nil +} + +type cborMapEntry struct { + key string + write func() error +} + +func streamingEncodeList(w io.Writer, typeMeta metav1.TypeMeta, listMeta metav1.ListMeta, items []interface{}, mode modes.EncMode) error { + var entries []cborMapEntry + + if typeMeta.Kind != "" { + entries = append(entries, cborMapEntry{ + key: "kind", + write: func() error { + return encodeKeyValuePair(w, "kind", typeMeta.Kind, mode) + }, + }) + } + entries = append(entries, cborMapEntry{ + key: "items", + write: func() error { + if err := mode.MarshalTo("items", w); err != nil { + return err + } + if items == nil { + _, err := w.Write([]byte{0xf6}) // CBOR null + return err + } + if err := writeArrayHead(w, len(items)); err != nil { + return err + } + for _, item := range items { + if err := mode.MarshalTo(item, w); err != nil { + return err + } + } + return nil + }, + }) + entries = append(entries, cborMapEntry{ + key: "metadata", + write: func() error { + return encodeKeyValuePair(w, "metadata", listMeta, mode) + }, + }) + if typeMeta.APIVersion != "" { + entries = append(entries, cborMapEntry{ + key: "apiVersion", + write: func() error { + return encodeKeyValuePair(w, "apiVersion", typeMeta.APIVersion, mode) + }, + }) + } + + // entries is built in a fixed order (kind, items, metadata, apiVersion). + // Unlike streamingEncodeUnstructuredList, whose keys come in Go's randomized + // map-iteration order, there is no inherent randomness here, so for + // nondeterministic modes (SortFastShuffle) we rotate the encoding for-loop + // by a random initial offset. + start := 0 + if !mode.IsDeterministic() && len(entries) > 0 { + start = rand.Intn(len(entries)) + } + + if err := writeMapHead(w, len(entries)); err != nil { + return err + } + + for i := 0; i < len(entries); i++ { + entry := entries[(start+i)%len(entries)] + if err := entry.write(); err != nil { + return err + } + } + return nil +} + +func streamingEncodeUnstructuredList(w io.Writer, list *unstructured.UnstructuredList, mode modes.EncMode) error { + keys := slices.Collect(maps.Keys(list.Object)) + if _, exists := list.Object["items"]; !exists { + keys = append(keys, "items") + } + // keys starts in Go's randomized map-iteration order. For deterministic + // modes (SortBytewiseLexical) we sort it: shorter lengths come first, then + // lexicographic by content. For nondeterministic modes (SortFastShuffle) we + // leave the map-iteration order as-is, which already varies from call to + // call (analogous to what SortFastShuffle does for structs), so no explicit + // shuffling is needed. + if mode.IsDeterministic() { + sort.Slice(keys, func(i, j int) bool { + if len(keys[i]) != len(keys[j]) { + return len(keys[i]) < len(keys[j]) + } + return keys[i] < keys[j] + }) + } + + if err := writeMapHead(w, len(keys)); err != nil { + return err + } + + for _, key := range keys { + if err := mode.MarshalTo(key, w); err != nil { + return err + } + if key == "items" { + if err := writeArrayHead(w, len(list.Items)); err != nil { + return err + } + for _, item := range list.Items { + if err := mode.MarshalTo(item.Object, w); err != nil { + return err + } + } + } else { + if err := mode.MarshalTo(list.Object[key], w); err != nil { + return err + } + } + } + return nil +} + +func encodeKeyValuePair(w io.Writer, key string, value interface{}, mode modes.EncMode) error { + if err := mode.MarshalTo(key, w); err != nil { + return err + } + if err := mode.MarshalTo(value, w); err != nil { + return err + } + return nil +} + +// CBOR major type prefix bytes (the type in the high 3 bits, additional info +// zeroed), following RFC 8949 Section 3.1. +const ( + cborTypeArray byte = 0x80 // major type 4 + cborTypeMap byte = 0xa0 // major type 5 +) + +// writeMapHead writes a CBOR map header for a map with n entries. +func writeMapHead(w io.Writer, n int) error { + return writeCollectionHead(w, cborTypeMap, int64(n)) +} + +// writeArrayHead writes a CBOR array header for an array with n elements. +func writeArrayHead(w io.Writer, n int) error { + return writeCollectionHead(w, cborTypeArray, int64(n)) +} + +// writeCollectionHead writes a CBOR collection (array or map) header encoding +// the number of elements n, following RFC 8949 Section 3 additional info rules: +// +// - base: the prefix byte for the collection type. +// For maps: cborTypeMap (0xa0), for arrays: cborTypeArray (0x80). +// +// The extended form prefixes are derived from base using bitwise OR: +// - base|24: 1-byte length follows (additional info 24) +// - base|25: 2-byte length follows (additional info 25) +// - base|26: 4-byte length follows (additional info 26) +// - base|27: 8-byte length follows (additional info 27) +// +// Encoding table (map example, base=0xa0): +// +// n <= 23: 1 byte — 0xa0|n +// n <= 0xFF: 2 bytes — 0xb8 (0xa0|24), n +// n <= 0xFFFF: 3 bytes — 0xb9 (0xa0|25), n>>8, n +// n <= 0xFFFFFFFF: 5 bytes — 0xba (0xa0|26), n>>24..n +// n > 0xFFFFFFFF: 9 bytes — 0xbb (0xa0|27), n>>56..n +func writeCollectionHead(w io.Writer, base byte, n int64) error { + switch { + case n <= 23: + // Additional info 0–23: length is encoded directly in the low 5 bits. + _, err := w.Write([]byte{base + byte(n)}) + return err + case n <= 0xFF: + // Additional info 24: one additional byte carries the length. + _, err := w.Write([]byte{base | 24, byte(n)}) + return err + case n <= 0xFFFF: + // Additional info 25: two additional bytes carry the length (big-endian). + _, err := w.Write([]byte{base | 25, byte(n >> 8), byte(n)}) + return err + case n <= 0xFFFFFFFF: + // Additional info 26: four additional bytes carry the length (big-endian). + _, err := w.Write([]byte{base | 26, byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}) + return err + default: + // Additional info 27: eight additional bytes carry the length (big-endian). + _, err := w.Write([]byte{ + base | 27, byte(n >> 56), byte(n >> 48), byte(n >> 40), byte(n >> 32), byte(n >> 24), byte(n >> 16), + byte(n >> 8), byte(n), + }) + return err + } +} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/encode.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/encode.go index 815dbe666..3287dfd31 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/encode.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/encode.go @@ -107,6 +107,7 @@ var encode = EncMode{ } return encode }(), + deterministic: true, } var Encode = EncMode{ @@ -122,6 +123,7 @@ var Encode = EncMode{ } return em }(), + deterministic: true, } var EncodeNondeterministic = EncMode{ @@ -134,16 +136,22 @@ var EncodeNondeterministic = EncMode{ } return em }(), + deterministic: false, } type EncMode struct { - delegate cbor.UserBufferEncMode + delegate cbor.UserBufferEncMode + deterministic bool } func (em EncMode) options() cbor.EncOptions { return em.delegate.EncOptions() } +func (em EncMode) IsDeterministic() bool { + return em.deterministic +} + func (em EncMode) MarshalTo(v interface{}, w io.Writer) error { if buf, ok := w.(*buffer); ok { return em.delegate.MarshalToBuffer(v, &buf.Buffer) diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go index 075163ddd..3fa6012dd 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go @@ -17,11 +17,10 @@ limitations under the License. package json import ( + "bytes" "encoding/json" "fmt" "io" - "maps" - "slices" "sort" "k8s.io/apimachinery/pkg/api/meta" @@ -35,14 +34,14 @@ import ( func streamEncodeCollections(obj runtime.Object, w io.Writer) (bool, error) { list, ok := obj.(*unstructured.UnstructuredList) if ok { - return true, streamingEncodeUnstructuredList(w, list) + return true, newStreamEncoder(w).encodeUnstructuredList(list) } if _, ok := obj.(json.Marshaler); ok { return false, nil } typeMeta, listMeta, items, err := getListMeta(obj) if err == nil { - return true, streamingEncodeList(w, typeMeta, listMeta, items) + return true, newStreamEncoder(w).encodeList(typeMeta, listMeta, items) } return false, nil } @@ -67,8 +66,13 @@ func getListMeta(list runtime.Object) (metav1.TypeMeta, metav1.ListMeta, []runti if !ok { return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected TypeMeta field to have TypeMeta type") } - if listType.Field(0).Tag.Get("json") != ",inline" { - return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be ",inline"`) + if !listType.Field(0).Anonymous { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be embedded`) + } + if jsonTag, jsonTagExists := listType.Field(0).Tag.Lookup("json"); !jsonTagExists { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag`) + } else if jsonTag != "" && jsonTag != ",inline" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be "" or ",inline"`) } // ListMeta listMeta, ok := listValue.Field(1).Interface().(metav1.ListMeta) @@ -89,45 +93,59 @@ func getListMeta(list runtime.Object) (metav1.TypeMeta, metav1.ListMeta, []runti return typeMeta, listMeta, items, nil } -func streamingEncodeList(w io.Writer, typeMeta metav1.TypeMeta, listMeta metav1.ListMeta, items []runtime.Object) error { +// streamEncoder encodes JSON values to w, reusing an internal buffer across +// values to avoid the fresh output allocation json.Marshal makes per call. +type streamEncoder struct { + w io.Writer + buf bytes.Buffer + json *json.Encoder +} + +func newStreamEncoder(w io.Writer) *streamEncoder { + e := &streamEncoder{w: w} + e.json = json.NewEncoder(&e.buf) + return e +} + +func (e *streamEncoder) encodeList(typeMeta metav1.TypeMeta, listMeta metav1.ListMeta, items []runtime.Object) error { // Start - if _, err := w.Write([]byte(`{`)); err != nil { + if _, err := e.w.Write([]byte(`{`)); err != nil { return err } // TypeMeta if typeMeta.Kind != "" { - if err := encodeKeyValuePair(w, "kind", typeMeta.Kind, []byte(",")); err != nil { + if err := e.encodeKeyValuePair("kind", typeMeta.Kind, []byte(",")); err != nil { return err } } if typeMeta.APIVersion != "" { - if err := encodeKeyValuePair(w, "apiVersion", typeMeta.APIVersion, []byte(",")); err != nil { + if err := e.encodeKeyValuePair("apiVersion", typeMeta.APIVersion, []byte(",")); err != nil { return err } } // ListMeta - if err := encodeKeyValuePair(w, "metadata", listMeta, []byte(",")); err != nil { + if err := e.encodeKeyValuePair("metadata", listMeta, []byte(",")); err != nil { return err } // Items - if err := encodeItemsObjectSlice(w, items); err != nil { + if err := e.encodeItemsObjectSlice(items); err != nil { return err } // End - _, err := w.Write([]byte("}\n")) + _, err := e.w.Write([]byte("}\n")) return err } -func encodeItemsObjectSlice(w io.Writer, items []runtime.Object) (err error) { +func (e *streamEncoder) encodeItemsObjectSlice(items []runtime.Object) (err error) { if items == nil { - err := encodeKeyValuePair(w, "items", nil, nil) + err := e.encodeKeyValuePair("items", nil, nil) return err } - _, err = w.Write([]byte(`"items":[`)) + _, err = e.w.Write([]byte(`"items":[`)) if err != nil { return err } @@ -136,24 +154,27 @@ func encodeItemsObjectSlice(w io.Writer, items []runtime.Object) (err error) { if i == len(items)-1 { suffix = nil } - err := encodeValue(w, item, suffix) + err := e.encodeValue(item, suffix) if err != nil { return err } } - _, err = w.Write([]byte("]")) + _, err = e.w.Write([]byte("]")) if err != nil { return err } return err } -func streamingEncodeUnstructuredList(w io.Writer, list *unstructured.UnstructuredList) error { - _, err := w.Write([]byte(`{`)) +func (e *streamEncoder) encodeUnstructuredList(list *unstructured.UnstructuredList) error { + _, err := e.w.Write([]byte(`{`)) if err != nil { return err } - keys := slices.Collect(maps.Keys(list.Object)) + keys := make([]string, 0, len(list.Object)+1) + for key := range list.Object { + keys = append(keys, key) + } if _, exists := list.Object["items"]; !exists { keys = append(keys, "items") } @@ -165,20 +186,20 @@ func streamingEncodeUnstructuredList(w io.Writer, list *unstructured.Unstructure suffix = nil } if key == "items" { - err = encodeItemsUnstructuredSlice(w, list.Items, suffix) + err = e.encodeItemsUnstructuredSlice(list.Items, suffix) } else { - err = encodeKeyValuePair(w, key, list.Object[key], suffix) + err = e.encodeKeyValuePair(key, list.Object[key], suffix) } if err != nil { return err } } - _, err = w.Write([]byte("}\n")) + _, err = e.w.Write([]byte("}\n")) return err } -func encodeItemsUnstructuredSlice(w io.Writer, items []unstructured.Unstructured, suffix []byte) (err error) { - _, err = w.Write([]byte(`"items":[`)) +func (e *streamEncoder) encodeItemsUnstructuredSlice(items []unstructured.Unstructured, suffix []byte) (err error) { + _, err = e.w.Write([]byte(`"items":[`)) if err != nil { return err } @@ -187,44 +208,42 @@ func encodeItemsUnstructuredSlice(w io.Writer, items []unstructured.Unstructured if i == len(items)-1 { comma = nil } - err := encodeValue(w, item.Object, comma) + err := e.encodeValue(item.Object, comma) if err != nil { return err } } - _, err = w.Write([]byte("]")) + _, err = e.w.Write([]byte("]")) if err != nil { return err } if len(suffix) > 0 { - _, err = w.Write(suffix) + _, err = e.w.Write(suffix) } return err } -func encodeKeyValuePair(w io.Writer, key string, value any, suffix []byte) (err error) { - err = encodeValue(w, key, []byte(":")) +func (e *streamEncoder) encodeKeyValuePair(key string, value any, suffix []byte) (err error) { + err = e.encodeValue(key, []byte(":")) if err != nil { return err } - err = encodeValue(w, value, suffix) + err = e.encodeValue(value, suffix) if err != nil { return err } return err } -func encodeValue(w io.Writer, value any, suffix []byte) error { - data, err := json.Marshal(value) - if err != nil { - return err - } - _, err = w.Write(data) - if err != nil { +func (e *streamEncoder) encodeValue(value any, suffix []byte) error { + e.buf.Reset() + if err := e.json.Encode(value); err != nil { return err } - if len(suffix) > 0 { - _, err = w.Write(suffix) - } + // Encode appends a newline after the value; replace it with the suffix to + // keep the output identical to json.Marshal's. + e.buf.Truncate(e.buf.Len() - 1) + e.buf.Write(suffix) + _, err := e.w.Write(e.buf.Bytes()) return err } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go index 24f66a101..52c814172 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go @@ -70,6 +70,7 @@ func identifier(options SerializerOptions) runtime.Identifier { } identifier, err := json.Marshal(result) if err != nil { + //nolint:logcheck // Should not be reached. klog.Fatalf("Failed marshaling identifier for json Serializer: %v", err) } return runtime.Identifier(identifier) diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go index afac03e9d..8db8932fb 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go @@ -17,6 +17,7 @@ limitations under the License. package protobuf import ( + "encoding/binary" "errors" "io" "math/bits" @@ -134,15 +135,17 @@ func streamingEncodeUnknownList(w io.Writer, unk runtime.Unknown, listData strea } func streamingEncodeList(w io.Writer, listData streamingListData, memAlloc runtime.MemoryAllocator) (size int, err error) { + // headerScratch escapes via w.Write, so allocate it once per call instead of once per item. + headerScratch := make([]byte, 1+binary.MaxVarintLen64) // ListMeta; 0xa = (1 << 3) | 2; field number: 1, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure - n, err := doEncodeWithHeader(&listData.listMeta, w, 0xa, listData.listMetaSize, memAlloc) + n, err := doEncodeWithHeader(&listData.listMeta, w, 0xa, listData.listMetaSize, headerScratch, memAlloc) size += n if err != nil { return size, err } // Items; 0x12 = (2 << 3) | 2; field number: 2, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure for i, item := range listData.items { - n, err := doEncodeWithHeader(item, w, 0x12, listData.itemsSizes[i], memAlloc) + n, err := doEncodeWithHeader(item, w, 0x12, listData.itemsSizes[i], headerScratch, memAlloc) size += n if err != nil { return size, err @@ -151,12 +154,6 @@ func streamingEncodeList(w io.Writer, listData streamingListData, memAlloc runti return size, nil } -func writeVarintGenerated(w io.Writer, v int) (int, error) { - buf := make([]byte, sovGenerated(uint64(v))) - encodeVarintGenerated(buf, len(buf), uint64(v)) - return w.Write(buf) -} - // sovGenerated is copied from `generated.pb.go` returns size of varint. func sovGenerated(v uint64) int { return (bits.Len64(v|1) + 6) / 7 diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go index 67a2d1247..93ad95cef 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go @@ -199,6 +199,7 @@ func (s *Serializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime.Me func (s *Serializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error { if memAlloc == nil { + //nolint:logcheck // Should not be reached in normal operations. klog.Error("a mandatory memory allocator wasn't provided, this might have a negative impact on performance, check invocations of EncodeWithAllocator method, falling back on runtime.SimpleAllocator") memAlloc = &runtime.SimpleAllocator{} } @@ -470,15 +471,12 @@ func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runti return err } -func doEncodeWithHeader(obj any, w io.Writer, field byte, precomputedSize int, memAlloc runtime.MemoryAllocator) (size int, err error) { - // Field identifier - n, err := w.Write([]byte{field}) - size += n - if err != nil { - return size, err - } - // Size - n, err = writeVarintGenerated(w, precomputedSize) +func doEncodeWithHeader(obj any, w io.Writer, field byte, precomputedSize int, headerScratch []byte, memAlloc runtime.MemoryAllocator) (size int, err error) { + // Field identifier and size + header := headerScratch[:1+sovGenerated(uint64(precomputedSize))] + header[0] = field + encodeVarintGenerated(header, len(header), uint64(precomputedSize)) + n, err := w.Write(header) size += n if err != nil { return size, err @@ -500,6 +498,7 @@ func doEncodeWithHeader(obj any, w io.Writer, field byte, precomputedSize int, m // precomputedObjSize should not include header bytes (field identifier, size). func doEncode(obj any, w io.Writer, precomputedObjSize *int, memAlloc runtime.MemoryAllocator) (int, error) { if memAlloc == nil { + //nolint:logcheck // Should not be reached in normal operations. klog.Error("a mandatory memory allocator wasn't provided, this might have a negative impact on performance, check invocations of EncodeWithAllocator method, falling back on runtime.SimpleAllocator") memAlloc = &runtime.SimpleAllocator{} } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go index 25f955ed7..6c86d5e15 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go @@ -116,6 +116,7 @@ func identifier(encodeGV runtime.GroupVersioner, encoder runtime.Encoder) runtim } identifier, err := json.Marshal(result) if err != nil { + //nolint:logcheck // Should not be reached. klog.Fatalf("Failed marshaling identifier for codec: %v", err) } identifiersMap.Store(result, runtime.Identifier(identifier)) @@ -222,6 +223,7 @@ func (c *codec) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.Memor return encoder.EncodeWithAllocator(obj, w, memAlloc) } } else { + //nolint:logcheck // Extending the API is not worth it for contextual, structured logging of this. klog.V(6).Infof("a memory allocator was provided but the encoder %s doesn't implement the runtime.EncoderWithAllocator, using regular encoder.Encode method", c.encoder.Identifier()) } } diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go index 5bc642bc8..0d5a3e709 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go @@ -25,7 +25,10 @@ import ( "go/token" "io" "reflect" + "strconv" "strings" + + "k8s.io/apimachinery/pkg/util/errors" ) // Pair of strings. We keed the name of fields and the doc @@ -94,23 +97,29 @@ func fmtRawDoc(rawDoc string) string { // fieldName returns the name of the field as it should appear in JSON format // "-" indicates that this field is not part of the JSON representation -func fieldName(field *ast.Field) string { +func fieldName(field *ast.Field) (string, error) { jsonTag := "" if field.Tag != nil { - jsonTag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("json") // Delete first and last quotation - if strings.Contains(jsonTag, "inline") { - return "-" + var jsonTagExists bool + tagValue, err := strconv.Unquote(field.Tag.Value) + if err != nil { + return "", err + } + jsonTag, jsonTagExists = reflect.StructTag(tagValue).Lookup("json") // Delete first and last quotation + // field is embedded, json tag is declared and has an empty name + if field.Names == nil && jsonTagExists && (jsonTag == "" || strings.HasPrefix(jsonTag, ",")) { + return "-", nil } } jsonTag = strings.Split(jsonTag, ",")[0] // This can return "-" if jsonTag == "" { if field.Names != nil { - return field.Names[0].Name + return field.Names[0].Name, nil } - return field.Type.(*ast.Ident).Name + return field.Type.(*ast.Ident).Name, nil } - return jsonTag + return jsonTag, nil } // A buffer of lines that will be written. @@ -171,8 +180,9 @@ func writeMapBody(b *buffer, kubeType []Pair, indent int) { // array. Each type is again represented as an array (we have to use arrays as we // need to be sure for the order of the fields). This function returns fields and // struct definitions that have no documentation as {name, ""}. -func ParseDocumentationFrom(src string) []KubeTypes { +func ParseDocumentationFrom(src string) ([]KubeTypes, error) { var docForTypes []KubeTypes + var errs []error pkg := astFrom(src) @@ -182,7 +192,9 @@ func ParseDocumentationFrom(src string) []KubeTypes { ks = append(ks, Pair{kubType.Name, fmtRawDoc(kubType.Doc)}) for _, field := range structType.Fields.List { - if n := fieldName(field); n != "-" { + if n, err := fieldName(field); err != nil { + errs = append(errs, err) + } else if n != "-" { fieldDoc := fmtRawDoc(field.Doc.Text()) ks = append(ks, Pair{n, fieldDoc}) } @@ -191,7 +203,7 @@ func ParseDocumentationFrom(src string) []KubeTypes { } } - return docForTypes + return docForTypes, errors.NewAggregate(errs) } // WriteSwaggerDocFunc writes a declaration of a function as a string. This function is used in diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/types.go b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/types.go index ca7b7cc2d..6cded8899 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/runtime/types.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/runtime/types.go @@ -23,7 +23,7 @@ package runtime // like this: // // type MyAwesomeAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // ... // other fields // } // @@ -59,7 +59,7 @@ const ( // // Internal package: // // type MyAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // MyPlugin runtime.Object `json:"myPlugin"` // } // @@ -70,7 +70,7 @@ const ( // // External package: // // type MyAPIObject struct { -// runtime.TypeMeta `json:",inline"` +// runtime.TypeMeta `json:""` // MyPlugin runtime.RawExtension `json:"myPlugin"` // } // @@ -121,7 +121,7 @@ type RawExtension struct { // +protobuf=true // +k8s:openapi-gen=true type Unknown struct { - TypeMeta `json:",inline" protobuf:"bytes,1,opt,name=typeMeta"` + TypeMeta `json:"" protobuf:"bytes,1,opt,name=typeMeta"` // Raw will hold the complete serialized object which couldn't be matched // with a registered type. Most likely, nothing should be done with this // except for passing it through the system. diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go index f372ae589..b0ca3803e 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go @@ -59,6 +59,7 @@ const ( // Deprecated: use FromInt32 instead. func FromInt(val int) IntOrString { if val > math.MaxInt32 || val < math.MinInt32 { + //nolint:logcheck // Should not be reached. klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack()) } return IntOrString{Type: Int, IntVal: int32(val)} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go index ac8d4279d..2e2db6556 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go @@ -140,24 +140,28 @@ func (f *FieldManager) Update(liveObj, newObj runtime.Object, manager string) (o } // UpdateNoErrors is the same as Update, but it will not return -// errors. If an error happens, the object is returned with -// managedFields cleared. +// errors. If an error happens, we preserve the managedFields from +// liveObj. func (f *FieldManager) UpdateNoErrors(liveObj, newObj runtime.Object, manager string) runtime.Object { obj, err := f.Update(liveObj, newObj, manager) if err != nil { - atMostEverySecond.Do(func() { - ns, name := "unknown", "unknown" - if accessor, err := meta.Accessor(newObj); err == nil { - ns = accessor.GetNamespace() - name = accessor.GetName() + // Preserve the managedFields from the live object rather than + // stripping them entirely, to avoid silent data loss when the + // managedFields update fails (e.g. due to an unavailable + // conversion webhook). + // Note: meta.Accessor for liveObj and newObj below never return an error in this code branch, + // because if they would f.Update above would return "newObj, nil". Accordingly, the case + // where one of the accessors returns an error is not handled here. + if liveAccessor, aErr := meta.Accessor(liveObj); aErr == nil { + if newAccessor, aErr := meta.Accessor(newObj); aErr == nil { + atMostEverySecond.Do(func() { + //nolint:logcheck // Should not be reached. + klog.ErrorS(err, "[SHOULD NOT HAPPEN] failed to update managedFields (restored previous managedFields from live object)", "versionKind", + newObj.GetObjectKind().GroupVersionKind(), "namespace", newAccessor.GetNamespace(), "name", newAccessor.GetName()) + }) + newAccessor.SetManagedFields(liveAccessor.GetManagedFields()) } - - klog.ErrorS(err, "[SHOULD NOT HAPPEN] failed to update managedFields", "versionKind", - newObj.GetObjectKind().GroupVersionKind(), "namespace", ns, "name", name) - }) - // Explicitly remove managedFields on failure, so that - // we can't have garbage in it. - RemoveObjectManagedFields(newObj) + } return newObj } return obj diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go index cbefc2eba..40cc90da7 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go @@ -109,6 +109,24 @@ func valueToObject(val value.Value) (runtime.Object, error) { } } +// GroupVersionOfTypedValue returns the extracted GroupVersion from the TypeMeta +// fields of a TypedValue, or return false if no TypeMeta fields are found. +func GroupVersionOfTypedValue(object *typed.TypedValue) (schema.GroupVersion, bool) { + val := object.AsValue() + if val == nil || !val.IsMap() { + return schema.GroupVersion{}, false + } + apiVersion, ok := val.AsMap().Get("apiVersion") + if !ok || !apiVersion.IsString() { + return schema.GroupVersion{}, false + } + groupVersion, err := schema.ParseGroupVersion(apiVersion.AsString()) + if err != nil { + return schema.GroupVersion{}, false + } + return groupVersion, true +} + func indexModels( typeParser *typed.Parser, openAPISchemas map[string]*spec.Schema, diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go index 86695e0c0..917bdcd75 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go @@ -63,24 +63,23 @@ func newCRDVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema // Convert implements sigs.k8s.io/structured-merge-diff/merge.Converter func (v *versionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) { - // Convert the smd typed value to a kubernetes object. - objectToConvert, err := v.typeConverter.TypedToObject(object) - if err != nil { - return object, err - } - - // Parse the target groupVersion. groupVersion, err := schema.ParseGroupVersion(string(version)) if err != nil { return object, err } // If attempting to convert to the same version as we already have, just return it. - fromVersion := objectToConvert.GetObjectKind().GroupVersionKind().GroupVersion() - if fromVersion == groupVersion { + if typedVersion, ok := GroupVersionOfTypedValue(object); ok && typedVersion == groupVersion { return object, nil } + // Convert the smd typed value to a kubernetes object. + objectToConvert, err := v.typeConverter.TypedToObject(object) + if err != nil { + return object, err + } + fromVersion := objectToConvert.GetObjectKind().GroupVersionKind().GroupVersion() + // Convert to internal internalObject, err := v.objectConvertor.ConvertToVersion(objectToConvert, v.hubGetter(fromVersion)) if err != nil { diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go index 1eeb71ff5..1a18b2766 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go @@ -46,35 +46,57 @@ type ErrorMatcher struct { requireOriginWhenInvalid bool matchValidationStabilityLevel bool matchSource bool + matchAncestorShortCircuit bool + matchShortCircuit bool // normalizationRules holds the pre-compiled regex patterns for path normalization. normalizationRules []NormalizationRule } +// isChildPath returns true if child is a descendant path of parent. +// It avoids false positives like "spec.containers" being a child of "spec.container" +// by explicitly checking for '.' or '[' path separators. +func isChildPath(parent, child string) bool { + // "" as parent path not supported. It can un-intentionally match with any path. + // theoretically system errors can be matched with any path errors. + if len(parent) == 0 { + return false + } + if len(child) <= len(parent) { + return false + } + if child[:len(parent)] != parent { + return false + } + sep := child[len(parent)] + return sep == '.' || sep == '[' +} + // Matches returns true if the two Error objects match according to the // configured criteria. When field normalization is configured, only the // "got" error's field path is normalized (to bring older API versions up // to the internal/latest format), while "want" is assumed to already be // in the canonical internal API format. func (m ErrorMatcher) Matches(want, got *Error) bool { - if m.matchType && want.Type != got.Type { - return false + gotField := got.Field + if want.Field != gotField { + gotField = m.normalizePath(gotField) } - if m.matchField { - // Try direct match first (common case) - if want.Field != got.Field { - // Fields don't match, try normalization if rules are configured. - // Only normalize "got" - it may be from an older API version that - // needs to be brought up to the internal/latest format that "want" - // is already in. - if want.Field != m.normalizePath(got.Field) { - return false - } + if m.matchAncestorShortCircuit { + if got.ShortCircuit && (isChildPath(gotField, want.Field) || isChildPath(got.Field, want.Field)) { + return true } } + if m.matchType && want.Type != got.Type { + return false + } + if m.matchField && want.Field != gotField { + return false + } if m.matchValue && !reflect.DeepEqual(want.BadValue, got.BadValue) { return false } + if m.matchOrigin { if want.Origin != got.Origin { return false @@ -91,10 +113,12 @@ func (m ErrorMatcher) Matches(want, got *Error) bool { if m.matchValidationStabilityLevel && want.ValidationStabilityLevel != got.ValidationStabilityLevel { return false } - if m.matchSource && want.FromImperative != got.FromImperative { return false } + if m.matchShortCircuit && want.ShortCircuit != got.ShortCircuit { + return false + } return true } @@ -124,47 +148,51 @@ func (m ErrorMatcher) Render(e *Error) string { if m.matchType { comma() - buf.WriteString(fmt.Sprintf("Type=%q", e.Type)) + fmt.Fprintf(&buf, "Type=%q", e.Type) } if m.matchField { comma() if normalized := m.normalizePath(e.Field); normalized != e.Field { - buf.WriteString(fmt.Sprintf("Field=%q (aka %q)", normalized, e.Field)) + fmt.Fprintf(&buf, "Field=%q (aka %q)", normalized, e.Field) } else { - buf.WriteString(fmt.Sprintf("Field=%q", e.Field)) + fmt.Fprintf(&buf, "Field=%q", e.Field) } } if m.matchValue { comma() if s, ok := e.BadValue.(string); ok { - buf.WriteString(fmt.Sprintf("Value=%q", s)) + fmt.Fprintf(&buf, "Value=%q", s) } else { rv := reflect.ValueOf(e.BadValue) if rv.Kind() == reflect.Pointer && !rv.IsNil() { rv = rv.Elem() } if rv.IsValid() && rv.CanInterface() { - buf.WriteString(fmt.Sprintf("Value=%v", rv.Interface())) + fmt.Fprintf(&buf, "Value=%v", rv.Interface()) } else { - buf.WriteString(fmt.Sprintf("Value=%v", e.BadValue)) + fmt.Fprintf(&buf, "Value=%v", e.BadValue) } } } if m.matchOrigin || m.requireOriginWhenInvalid && e.Type == ErrorTypeInvalid { comma() - buf.WriteString(fmt.Sprintf("Origin=%q", e.Origin)) + fmt.Fprintf(&buf, "Origin=%q", e.Origin) } if m.matchDetail != nil { comma() - buf.WriteString(fmt.Sprintf("Detail=%q", e.Detail)) + fmt.Fprintf(&buf, "Detail=%q", e.Detail) } if m.matchValidationStabilityLevel { comma() - buf.WriteString(fmt.Sprintf("ValidationStabilityLevel=%s", e.ValidationStabilityLevel)) + fmt.Fprintf(&buf, "ValidationStabilityLevel=%s", e.ValidationStabilityLevel) } if m.matchSource { comma() - buf.WriteString(fmt.Sprintf("FromImperative=%t", e.FromImperative)) + fmt.Fprintf(&buf, "FromImperative=%t", e.FromImperative) + } + if m.matchShortCircuit { + comma() + fmt.Fprintf(&buf, "ShortCircuit=%t", e.ShortCircuit) } return "{" + buf.String() + "}" } @@ -249,6 +277,18 @@ func (m ErrorMatcher) BySource() ErrorMatcher { return m } +// MatchAncestorShortCircuit returns a derived ErrorMatcher which also matches when the "got" error short-circuited at an ancestor of the "want" error's field path. +func (m ErrorMatcher) MatchAncestorShortCircuit() ErrorMatcher { + m.matchAncestorShortCircuit = true + return m +} + +// MatchShortCircuit returns a derived ErrorMatcher which also matches by the ShortCircuit value. +func (m ErrorMatcher) MatchShortCircuit() ErrorMatcher { + m.matchShortCircuit = true + return m +} + // ByValidationStabilityLevel returns a derived ErrorMatcher which also matches by the validation stability level // value of field errors. func (m ErrorMatcher) ByValidationStabilityLevel() ErrorMatcher { @@ -300,9 +340,13 @@ type TestIntf interface { // "want" error can match multiple "got" errors, and they will all be consumed. // The only exception to this is if the matcher got multiple identical (in every way, // even those not being matched on) errors, which is likely to indicate a bug. +// This doesn't support matchAncestorShortCircuit as it it not needed to be used in the tests. func (m ErrorMatcher) Test(tb TestIntf, want, got ErrorList) { tb.Helper() + if m.matchAncestorShortCircuit { + tb.Errorf("matchAncestorShortCircuit is not supported for test") + } exactly := m.Exactly() // makes a copy // If we ever find an EXACT duplicate error, it's almost certainly a bug diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go index 9357fb306..0d00acb42 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go @@ -59,6 +59,12 @@ type Error struct { // FromImperative denotes these errors are originating from the hand written validations. FromImperative bool + // ShortCircuit denotes that this error prevents further validation of the current field's children. + ShortCircuit bool + + // ShortCircuitedInDeclarative denotes this error is covered by declarative validation. But not returned by declarative validation due to a short circuiting behavior for the current input. + ShortCircuitedInDeclarative bool + // ValidationStabilityLevel denotes the validation stability level of the declarative validation from this error is returned. This should be used in the declarative validations only. ValidationStabilityLevel ValidationStabilityLevel } @@ -545,6 +551,12 @@ func (e *Error) MarkAlpha() *Error { return e } +// MarkShortCircuitedInDV marks that this error is not returned by declarative validations, because DV returns before running the current validation. Handwritten validations still return it. +func (e *Error) MarkShortCircuitedInDV() *Error { + e.ShortCircuitedInDeclarative = true + return e +} + // MarkAlpha marks the errors as alpha validation errors. func (list ErrorList) MarkAlpha() ErrorList { for _, err := range list { @@ -579,6 +591,14 @@ func (list ErrorList) MarkFromImperative() ErrorList { return list } +// MarkShortCircuit marks the errors as short-circuit errors. +func (list ErrorList) MarkShortCircuit() ErrorList { + for _, err := range list { + err.ShortCircuit = true + } + return list +} + // RemoveCoveredByDeclarative returns a new ErrorList containing only the errors that should not be covered by declarative validation. func (list ErrorList) RemoveCoveredByDeclarative() ErrorList { newList := ErrorList{} diff --git a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go index 869fb0aad..95f4e6218 100644 --- a/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go +++ b/constraint/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go @@ -105,6 +105,7 @@ func IsValidIP(fldPath *field.Path, value string) field.ErrorList { func GetWarningsForIP(fldPath *field.Path, value string) []string { ip := netutils.ParseIPSloppy(value) if ip == nil { + //nolint:logcheck // Should not be reached. klog.ErrorS(nil, "GetWarningsForIP called on value that was not validated with IsValidIPForLegacyField", "field", fldPath, "value", value) return nil } @@ -211,6 +212,7 @@ func IsValidCIDR(fldPath *field.Path, value string) field.ErrorList { func GetWarningsForCIDR(fldPath *field.Path, value string) []string { ip, ipnet, err := netutils.ParseCIDRSloppy(value) if err != nil { + //nolint:logcheck // Should not be reached. klog.ErrorS(err, "GetWarningsForCIDR called on value that was not validated with IsValidCIDRForLegacyField", "field", fldPath, "value", value) return nil } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/types.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/types.go index ecfe48262..317d21534 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/types.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/types.go @@ -26,7 +26,7 @@ import ( // AdmissionConfiguration provides versioned configuration for admission controllers. type AdmissionConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Plugins allows specifying a configuration per admission control plugin. // +optional @@ -54,7 +54,7 @@ type AdmissionPluginConfiguration struct { // AuthenticationConfiguration provides versioned configuration for authentication. type AuthenticationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // jwt is a list of authenticator to authenticate Kubernetes users using // JWT compliant tokens. The authenticator will attempt to parse a raw ID token, @@ -419,7 +419,7 @@ type UserValidationRule struct { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type AuthorizationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // Authorizers is an ordered list of authorizers to // authorize requests against. @@ -558,8 +558,8 @@ type WebhookMatchCondition struct { // TracingConfiguration provides versioned configuration for tracing clients. type TracingConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Embed the component config tracing configuration struct - tracingapi.TracingConfiguration `json:",inline"` + tracingapi.TracingConfiguration `json:""` } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/zz_generated.conversion.go index 325739c7c..ff3c709ff 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/zz_generated.conversion.go @@ -311,7 +311,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1_AESConfiguration_To_apiserver_AESConfiguration(in *AESConfiguration, out *apiserver.AESConfiguration, s conversion.Scope) error { - out.Keys = *(*[]apiserver.Key)(unsafe.Pointer(&in.Keys)) + *out = *(*apiserver.AESConfiguration)(unsafe.Pointer(in)) return nil } @@ -321,7 +321,7 @@ func Convert_v1_AESConfiguration_To_apiserver_AESConfiguration(in *AESConfigurat } func autoConvert_apiserver_AESConfiguration_To_v1_AESConfiguration(in *apiserver.AESConfiguration, out *AESConfiguration, s conversion.Scope) error { - out.Keys = *(*[]Key)(unsafe.Pointer(&in.Keys)) + *out = *(*AESConfiguration)(unsafe.Pointer(in)) return nil } @@ -351,9 +351,7 @@ func Convert_apiserver_AdmissionConfiguration_To_v1_AdmissionConfiguration(in *a } func autoConvert_v1_AdmissionPluginConfiguration_To_apiserver_AdmissionPluginConfiguration(in *AdmissionPluginConfiguration, out *apiserver.AdmissionPluginConfiguration, s conversion.Scope) error { - out.Name = in.Name - out.Path = in.Path - out.Configuration = (*runtime.Unknown)(unsafe.Pointer(in.Configuration)) + *out = *(*apiserver.AdmissionPluginConfiguration)(unsafe.Pointer(in)) return nil } @@ -363,9 +361,7 @@ func Convert_v1_AdmissionPluginConfiguration_To_apiserver_AdmissionPluginConfigu } func autoConvert_apiserver_AdmissionPluginConfiguration_To_v1_AdmissionPluginConfiguration(in *apiserver.AdmissionPluginConfiguration, out *AdmissionPluginConfiguration, s conversion.Scope) error { - out.Name = in.Name - out.Path = in.Path - out.Configuration = (*runtime.Unknown)(unsafe.Pointer(in.Configuration)) + *out = *(*AdmissionPluginConfiguration)(unsafe.Pointer(in)) return nil } @@ -375,7 +371,7 @@ func Convert_apiserver_AdmissionPluginConfiguration_To_v1_AdmissionPluginConfigu } func autoConvert_v1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition(in *AnonymousAuthCondition, out *apiserver.AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*apiserver.AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -385,7 +381,7 @@ func Convert_v1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition(in *A } func autoConvert_apiserver_AnonymousAuthCondition_To_v1_AnonymousAuthCondition(in *apiserver.AnonymousAuthCondition, out *AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -395,8 +391,7 @@ func Convert_apiserver_AnonymousAuthCondition_To_v1_AnonymousAuthCondition(in *a } func autoConvert_v1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *AnonymousAuthConfig, out *apiserver.AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]apiserver.AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*apiserver.AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -406,8 +401,7 @@ func Convert_v1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *Anonymo } func autoConvert_apiserver_AnonymousAuthConfig_To_v1_AnonymousAuthConfig(in *apiserver.AnonymousAuthConfig, out *AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -539,16 +533,7 @@ func Convert_apiserver_AuthorizerConfiguration_To_v1_AuthorizerConfiguration(in } func autoConvert_v1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings, out *apiserver.ClaimMappings, s conversion.Scope) error { - if err := Convert_v1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_v1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_v1_ClaimOrExpression_To_apiserver_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]apiserver.ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*apiserver.ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -558,16 +543,7 @@ func Convert_v1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings, out } func autoConvert_apiserver_ClaimMappings_To_v1_ClaimMappings(in *apiserver.ClaimMappings, out *ClaimMappings, s conversion.Scope) error { - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_apiserver_ClaimOrExpression_To_v1_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -577,8 +553,7 @@ func Convert_apiserver_ClaimMappings_To_v1_ClaimMappings(in *apiserver.ClaimMapp } func autoConvert_v1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *ClaimOrExpression, out *apiserver.ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*apiserver.ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -588,8 +563,7 @@ func Convert_v1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *ClaimOrExpr } func autoConvert_apiserver_ClaimOrExpression_To_v1_ClaimOrExpression(in *apiserver.ClaimOrExpression, out *ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -599,10 +573,7 @@ func Convert_apiserver_ClaimOrExpression_To_v1_ClaimOrExpression(in *apiserver.C } func autoConvert_v1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *ClaimValidationRule, out *apiserver.ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -612,10 +583,7 @@ func Convert_v1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *ClaimVa } func autoConvert_apiserver_ClaimValidationRule_To_v1_ClaimValidationRule(in *apiserver.ClaimValidationRule, out *ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -645,8 +613,7 @@ func Convert_apiserver_EncryptionConfiguration_To_v1_EncryptionConfiguration(in } func autoConvert_v1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, out *apiserver.ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*apiserver.ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -656,8 +623,7 @@ func Convert_v1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, out *ap } func autoConvert_apiserver_ExtraMapping_To_v1_ExtraMapping(in *apiserver.ExtraMapping, out *ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -667,6 +633,7 @@ func Convert_apiserver_ExtraMapping_To_v1_ExtraMapping(in *apiserver.ExtraMappin } func autoConvert_v1_IdentityConfiguration_To_apiserver_IdentityConfiguration(in *IdentityConfiguration, out *apiserver.IdentityConfiguration, s conversion.Scope) error { + *out = *(*apiserver.IdentityConfiguration)(unsafe.Pointer(in)) return nil } @@ -676,6 +643,7 @@ func Convert_v1_IdentityConfiguration_To_apiserver_IdentityConfiguration(in *Ide } func autoConvert_apiserver_IdentityConfiguration_To_v1_IdentityConfiguration(in *apiserver.IdentityConfiguration, out *IdentityConfiguration, s conversion.Scope) error { + *out = *(*IdentityConfiguration)(unsafe.Pointer(in)) return nil } @@ -753,11 +721,7 @@ func Convert_apiserver_JWTAuthenticator_To_v1_JWTAuthenticator(in *apiserver.JWT } func autoConvert_v1_KMSConfiguration_To_apiserver_KMSConfiguration(in *KMSConfiguration, out *apiserver.KMSConfiguration, s conversion.Scope) error { - out.APIVersion = in.APIVersion - out.Name = in.Name - out.CacheSize = (*int32)(unsafe.Pointer(in.CacheSize)) - out.Endpoint = in.Endpoint - out.Timeout = (*metav1.Duration)(unsafe.Pointer(in.Timeout)) + *out = *(*apiserver.KMSConfiguration)(unsafe.Pointer(in)) return nil } @@ -767,11 +731,7 @@ func Convert_v1_KMSConfiguration_To_apiserver_KMSConfiguration(in *KMSConfigurat } func autoConvert_apiserver_KMSConfiguration_To_v1_KMSConfiguration(in *apiserver.KMSConfiguration, out *KMSConfiguration, s conversion.Scope) error { - out.APIVersion = in.APIVersion - out.Name = in.Name - out.CacheSize = (*int32)(unsafe.Pointer(in.CacheSize)) - out.Endpoint = in.Endpoint - out.Timeout = (*metav1.Duration)(unsafe.Pointer(in.Timeout)) + *out = *(*KMSConfiguration)(unsafe.Pointer(in)) return nil } @@ -781,8 +741,7 @@ func Convert_apiserver_KMSConfiguration_To_v1_KMSConfiguration(in *apiserver.KMS } func autoConvert_v1_Key_To_apiserver_Key(in *Key, out *apiserver.Key, s conversion.Scope) error { - out.Name = in.Name - out.Secret = in.Secret + *out = *(*apiserver.Key)(unsafe.Pointer(in)) return nil } @@ -792,8 +751,7 @@ func Convert_v1_Key_To_apiserver_Key(in *Key, out *apiserver.Key, s conversion.S } func autoConvert_apiserver_Key_To_v1_Key(in *apiserver.Key, out *Key, s conversion.Scope) error { - out.Name = in.Name - out.Secret = in.Secret + *out = *(*Key)(unsafe.Pointer(in)) return nil } @@ -803,9 +761,7 @@ func Convert_apiserver_Key_To_v1_Key(in *apiserver.Key, out *Key, s conversion.S } func autoConvert_v1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(in *PrefixedClaimOrExpression, out *apiserver.PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*apiserver.PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -815,9 +771,7 @@ func Convert_v1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression } func autoConvert_apiserver_PrefixedClaimOrExpression_To_v1_PrefixedClaimOrExpression(in *apiserver.PrefixedClaimOrExpression, out *PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -827,11 +781,7 @@ func Convert_apiserver_PrefixedClaimOrExpression_To_v1_PrefixedClaimOrExpression } func autoConvert_v1_ProviderConfiguration_To_apiserver_ProviderConfiguration(in *ProviderConfiguration, out *apiserver.ProviderConfiguration, s conversion.Scope) error { - out.AESGCM = (*apiserver.AESConfiguration)(unsafe.Pointer(in.AESGCM)) - out.AESCBC = (*apiserver.AESConfiguration)(unsafe.Pointer(in.AESCBC)) - out.Secretbox = (*apiserver.SecretboxConfiguration)(unsafe.Pointer(in.Secretbox)) - out.Identity = (*apiserver.IdentityConfiguration)(unsafe.Pointer(in.Identity)) - out.KMS = (*apiserver.KMSConfiguration)(unsafe.Pointer(in.KMS)) + *out = *(*apiserver.ProviderConfiguration)(unsafe.Pointer(in)) return nil } @@ -841,11 +791,7 @@ func Convert_v1_ProviderConfiguration_To_apiserver_ProviderConfiguration(in *Pro } func autoConvert_apiserver_ProviderConfiguration_To_v1_ProviderConfiguration(in *apiserver.ProviderConfiguration, out *ProviderConfiguration, s conversion.Scope) error { - out.AESGCM = (*AESConfiguration)(unsafe.Pointer(in.AESGCM)) - out.AESCBC = (*AESConfiguration)(unsafe.Pointer(in.AESCBC)) - out.Secretbox = (*SecretboxConfiguration)(unsafe.Pointer(in.Secretbox)) - out.Identity = (*IdentityConfiguration)(unsafe.Pointer(in.Identity)) - out.KMS = (*KMSConfiguration)(unsafe.Pointer(in.KMS)) + *out = *(*ProviderConfiguration)(unsafe.Pointer(in)) return nil } @@ -855,8 +801,7 @@ func Convert_apiserver_ProviderConfiguration_To_v1_ProviderConfiguration(in *api } func autoConvert_v1_ResourceConfiguration_To_apiserver_ResourceConfiguration(in *ResourceConfiguration, out *apiserver.ResourceConfiguration, s conversion.Scope) error { - out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) - out.Providers = *(*[]apiserver.ProviderConfiguration)(unsafe.Pointer(&in.Providers)) + *out = *(*apiserver.ResourceConfiguration)(unsafe.Pointer(in)) return nil } @@ -866,8 +811,7 @@ func Convert_v1_ResourceConfiguration_To_apiserver_ResourceConfiguration(in *Res } func autoConvert_apiserver_ResourceConfiguration_To_v1_ResourceConfiguration(in *apiserver.ResourceConfiguration, out *ResourceConfiguration, s conversion.Scope) error { - out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) - out.Providers = *(*[]ProviderConfiguration)(unsafe.Pointer(&in.Providers)) + *out = *(*ResourceConfiguration)(unsafe.Pointer(in)) return nil } @@ -877,7 +821,7 @@ func Convert_apiserver_ResourceConfiguration_To_v1_ResourceConfiguration(in *api } func autoConvert_v1_SecretboxConfiguration_To_apiserver_SecretboxConfiguration(in *SecretboxConfiguration, out *apiserver.SecretboxConfiguration, s conversion.Scope) error { - out.Keys = *(*[]apiserver.Key)(unsafe.Pointer(&in.Keys)) + *out = *(*apiserver.SecretboxConfiguration)(unsafe.Pointer(in)) return nil } @@ -887,7 +831,7 @@ func Convert_v1_SecretboxConfiguration_To_apiserver_SecretboxConfiguration(in *S } func autoConvert_apiserver_SecretboxConfiguration_To_v1_SecretboxConfiguration(in *apiserver.SecretboxConfiguration, out *SecretboxConfiguration, s conversion.Scope) error { - out.Keys = *(*[]Key)(unsafe.Pointer(&in.Keys)) + *out = *(*SecretboxConfiguration)(unsafe.Pointer(in)) return nil } @@ -917,8 +861,7 @@ func Convert_apiserver_TracingConfiguration_To_v1_TracingConfiguration(in *apise } func autoConvert_v1_UserValidationRule_To_apiserver_UserValidationRule(in *UserValidationRule, out *apiserver.UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -928,8 +871,7 @@ func Convert_v1_UserValidationRule_To_apiserver_UserValidationRule(in *UserValid } func autoConvert_apiserver_UserValidationRule_To_v1_UserValidationRule(in *apiserver.UserValidationRule, out *UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -989,8 +931,7 @@ func Convert_apiserver_WebhookConfiguration_To_v1_WebhookConfiguration(in *apise } func autoConvert_v1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(in *WebhookConnectionInfo, out *apiserver.WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*apiserver.WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -1000,8 +941,7 @@ func Convert_v1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(in *Web } func autoConvert_apiserver_WebhookConnectionInfo_To_v1_WebhookConnectionInfo(in *apiserver.WebhookConnectionInfo, out *WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -1011,7 +951,7 @@ func Convert_apiserver_WebhookConnectionInfo_To_v1_WebhookConnectionInfo(in *api } func autoConvert_v1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(in *WebhookMatchCondition, out *apiserver.WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*apiserver.WebhookMatchCondition)(unsafe.Pointer(in)) return nil } @@ -1021,7 +961,7 @@ func Convert_v1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(in *Web } func autoConvert_apiserver_WebhookMatchCondition_To_v1_WebhookMatchCondition(in *apiserver.WebhookMatchCondition, out *WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*WebhookMatchCondition)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go index 1e20c697b..e42a86bc9 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go @@ -26,7 +26,7 @@ import ( // AdmissionConfiguration provides versioned configuration for admission controllers. type AdmissionConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Plugins allows specifying a configuration per admission control plugin. // +optional @@ -54,7 +54,7 @@ type AdmissionPluginConfiguration struct { // EgressSelectorConfiguration provides versioned configuration for egress selector clients. type EgressSelectorConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // connectionServices contains a list of egress selection client configurations EgressSelections []EgressSelection `json:"egressSelections"` @@ -157,17 +157,17 @@ type TLSConfig struct { // TracingConfiguration provides versioned configuration for tracing clients. type TracingConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Embed the component config tracing configuration struct - tracingapi.TracingConfiguration `json:",inline"` + tracingapi.TracingConfiguration `json:""` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // AuthenticationConfiguration provides versioned configuration for authentication. type AuthenticationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // jwt is a list of authenticator to authenticate Kubernetes users using // JWT compliant tokens. The authenticator will attempt to parse a raw ID token, @@ -532,7 +532,7 @@ type UserValidationRule struct { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type AuthorizationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // Authorizers is an ordered list of authorizers to // authorize requests against. diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/zz_generated.conversion.go index 4ea029789..e310e250b 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/zz_generated.conversion.go @@ -321,9 +321,7 @@ func Convert_apiserver_AdmissionConfiguration_To_v1alpha1_AdmissionConfiguration } func autoConvert_v1alpha1_AdmissionPluginConfiguration_To_apiserver_AdmissionPluginConfiguration(in *AdmissionPluginConfiguration, out *apiserver.AdmissionPluginConfiguration, s conversion.Scope) error { - out.Name = in.Name - out.Path = in.Path - out.Configuration = (*runtime.Unknown)(unsafe.Pointer(in.Configuration)) + *out = *(*apiserver.AdmissionPluginConfiguration)(unsafe.Pointer(in)) return nil } @@ -333,9 +331,7 @@ func Convert_v1alpha1_AdmissionPluginConfiguration_To_apiserver_AdmissionPluginC } func autoConvert_apiserver_AdmissionPluginConfiguration_To_v1alpha1_AdmissionPluginConfiguration(in *apiserver.AdmissionPluginConfiguration, out *AdmissionPluginConfiguration, s conversion.Scope) error { - out.Name = in.Name - out.Path = in.Path - out.Configuration = (*runtime.Unknown)(unsafe.Pointer(in.Configuration)) + *out = *(*AdmissionPluginConfiguration)(unsafe.Pointer(in)) return nil } @@ -345,7 +341,7 @@ func Convert_apiserver_AdmissionPluginConfiguration_To_v1alpha1_AdmissionPluginC } func autoConvert_v1alpha1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition(in *AnonymousAuthCondition, out *apiserver.AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*apiserver.AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -355,7 +351,7 @@ func Convert_v1alpha1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition } func autoConvert_apiserver_AnonymousAuthCondition_To_v1alpha1_AnonymousAuthCondition(in *apiserver.AnonymousAuthCondition, out *AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -365,8 +361,7 @@ func Convert_apiserver_AnonymousAuthCondition_To_v1alpha1_AnonymousAuthCondition } func autoConvert_v1alpha1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *AnonymousAuthConfig, out *apiserver.AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]apiserver.AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*apiserver.AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -376,8 +371,7 @@ func Convert_v1alpha1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *A } func autoConvert_apiserver_AnonymousAuthConfig_To_v1alpha1_AnonymousAuthConfig(in *apiserver.AnonymousAuthConfig, out *AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -509,16 +503,7 @@ func Convert_apiserver_AuthorizerConfiguration_To_v1alpha1_AuthorizerConfigurati } func autoConvert_v1alpha1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings, out *apiserver.ClaimMappings, s conversion.Scope) error { - if err := Convert_v1alpha1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_v1alpha1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_v1alpha1_ClaimOrExpression_To_apiserver_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]apiserver.ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*apiserver.ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -528,16 +513,7 @@ func Convert_v1alpha1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings } func autoConvert_apiserver_ClaimMappings_To_v1alpha1_ClaimMappings(in *apiserver.ClaimMappings, out *ClaimMappings, s conversion.Scope) error { - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1alpha1_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1alpha1_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_apiserver_ClaimOrExpression_To_v1alpha1_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -547,8 +523,7 @@ func Convert_apiserver_ClaimMappings_To_v1alpha1_ClaimMappings(in *apiserver.Cla } func autoConvert_v1alpha1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *ClaimOrExpression, out *apiserver.ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*apiserver.ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -558,8 +533,7 @@ func Convert_v1alpha1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *Claim } func autoConvert_apiserver_ClaimOrExpression_To_v1alpha1_ClaimOrExpression(in *apiserver.ClaimOrExpression, out *ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -569,10 +543,7 @@ func Convert_apiserver_ClaimOrExpression_To_v1alpha1_ClaimOrExpression(in *apise } func autoConvert_v1alpha1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *ClaimValidationRule, out *apiserver.ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -582,10 +553,7 @@ func Convert_v1alpha1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *C } func autoConvert_apiserver_ClaimValidationRule_To_v1alpha1_ClaimValidationRule(in *apiserver.ClaimValidationRule, out *ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -595,8 +563,7 @@ func Convert_apiserver_ClaimValidationRule_To_v1alpha1_ClaimValidationRule(in *a } func autoConvert_v1alpha1_Connection_To_apiserver_Connection(in *Connection, out *apiserver.Connection, s conversion.Scope) error { - out.ProxyProtocol = apiserver.ProtocolType(in.ProxyProtocol) - out.Transport = (*apiserver.Transport)(unsafe.Pointer(in.Transport)) + *out = *(*apiserver.Connection)(unsafe.Pointer(in)) return nil } @@ -606,8 +573,7 @@ func Convert_v1alpha1_Connection_To_apiserver_Connection(in *Connection, out *ap } func autoConvert_apiserver_Connection_To_v1alpha1_Connection(in *apiserver.Connection, out *Connection, s conversion.Scope) error { - out.ProxyProtocol = ProtocolType(in.ProxyProtocol) - out.Transport = (*Transport)(unsafe.Pointer(in.Transport)) + *out = *(*Connection)(unsafe.Pointer(in)) return nil } @@ -678,8 +644,7 @@ func Convert_apiserver_EgressSelectorConfiguration_To_v1alpha1_EgressSelectorCon } func autoConvert_v1alpha1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, out *apiserver.ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*apiserver.ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -689,8 +654,7 @@ func Convert_v1alpha1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, o } func autoConvert_apiserver_ExtraMapping_To_v1alpha1_ExtraMapping(in *apiserver.ExtraMapping, out *ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -768,9 +732,7 @@ func Convert_apiserver_JWTAuthenticator_To_v1alpha1_JWTAuthenticator(in *apiserv } func autoConvert_v1alpha1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(in *PrefixedClaimOrExpression, out *apiserver.PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*apiserver.PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -780,9 +742,7 @@ func Convert_v1alpha1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpr } func autoConvert_apiserver_PrefixedClaimOrExpression_To_v1alpha1_PrefixedClaimOrExpression(in *apiserver.PrefixedClaimOrExpression, out *PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -792,8 +752,7 @@ func Convert_apiserver_PrefixedClaimOrExpression_To_v1alpha1_PrefixedClaimOrExpr } func autoConvert_v1alpha1_TCPTransport_To_apiserver_TCPTransport(in *TCPTransport, out *apiserver.TCPTransport, s conversion.Scope) error { - out.URL = in.URL - out.TLSConfig = (*apiserver.TLSConfig)(unsafe.Pointer(in.TLSConfig)) + *out = *(*apiserver.TCPTransport)(unsafe.Pointer(in)) return nil } @@ -803,8 +762,7 @@ func Convert_v1alpha1_TCPTransport_To_apiserver_TCPTransport(in *TCPTransport, o } func autoConvert_apiserver_TCPTransport_To_v1alpha1_TCPTransport(in *apiserver.TCPTransport, out *TCPTransport, s conversion.Scope) error { - out.URL = in.URL - out.TLSConfig = (*TLSConfig)(unsafe.Pointer(in.TLSConfig)) + *out = *(*TCPTransport)(unsafe.Pointer(in)) return nil } @@ -814,10 +772,7 @@ func Convert_apiserver_TCPTransport_To_v1alpha1_TCPTransport(in *apiserver.TCPTr } func autoConvert_v1alpha1_TLSConfig_To_apiserver_TLSConfig(in *TLSConfig, out *apiserver.TLSConfig, s conversion.Scope) error { - out.CABundle = in.CABundle - out.ClientKey = in.ClientKey - out.ClientCert = in.ClientCert - out.TLSServerName = in.TLSServerName + *out = *(*apiserver.TLSConfig)(unsafe.Pointer(in)) return nil } @@ -827,10 +782,7 @@ func Convert_v1alpha1_TLSConfig_To_apiserver_TLSConfig(in *TLSConfig, out *apise } func autoConvert_apiserver_TLSConfig_To_v1alpha1_TLSConfig(in *apiserver.TLSConfig, out *TLSConfig, s conversion.Scope) error { - out.CABundle = in.CABundle - out.ClientKey = in.ClientKey - out.ClientCert = in.ClientCert - out.TLSServerName = in.TLSServerName + *out = *(*TLSConfig)(unsafe.Pointer(in)) return nil } @@ -860,8 +812,7 @@ func Convert_apiserver_TracingConfiguration_To_v1alpha1_TracingConfiguration(in } func autoConvert_v1alpha1_Transport_To_apiserver_Transport(in *Transport, out *apiserver.Transport, s conversion.Scope) error { - out.TCP = (*apiserver.TCPTransport)(unsafe.Pointer(in.TCP)) - out.UDS = (*apiserver.UDSTransport)(unsafe.Pointer(in.UDS)) + *out = *(*apiserver.Transport)(unsafe.Pointer(in)) return nil } @@ -871,8 +822,7 @@ func Convert_v1alpha1_Transport_To_apiserver_Transport(in *Transport, out *apise } func autoConvert_apiserver_Transport_To_v1alpha1_Transport(in *apiserver.Transport, out *Transport, s conversion.Scope) error { - out.TCP = (*TCPTransport)(unsafe.Pointer(in.TCP)) - out.UDS = (*UDSTransport)(unsafe.Pointer(in.UDS)) + *out = *(*Transport)(unsafe.Pointer(in)) return nil } @@ -882,7 +832,7 @@ func Convert_apiserver_Transport_To_v1alpha1_Transport(in *apiserver.Transport, } func autoConvert_v1alpha1_UDSTransport_To_apiserver_UDSTransport(in *UDSTransport, out *apiserver.UDSTransport, s conversion.Scope) error { - out.UDSName = in.UDSName + *out = *(*apiserver.UDSTransport)(unsafe.Pointer(in)) return nil } @@ -892,7 +842,7 @@ func Convert_v1alpha1_UDSTransport_To_apiserver_UDSTransport(in *UDSTransport, o } func autoConvert_apiserver_UDSTransport_To_v1alpha1_UDSTransport(in *apiserver.UDSTransport, out *UDSTransport, s conversion.Scope) error { - out.UDSName = in.UDSName + *out = *(*UDSTransport)(unsafe.Pointer(in)) return nil } @@ -902,8 +852,7 @@ func Convert_apiserver_UDSTransport_To_v1alpha1_UDSTransport(in *apiserver.UDSTr } func autoConvert_v1alpha1_UserValidationRule_To_apiserver_UserValidationRule(in *UserValidationRule, out *apiserver.UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -913,8 +862,7 @@ func Convert_v1alpha1_UserValidationRule_To_apiserver_UserValidationRule(in *Use } func autoConvert_apiserver_UserValidationRule_To_v1alpha1_UserValidationRule(in *apiserver.UserValidationRule, out *UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -974,8 +922,7 @@ func Convert_apiserver_WebhookConfiguration_To_v1alpha1_WebhookConfiguration(in } func autoConvert_v1alpha1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(in *WebhookConnectionInfo, out *apiserver.WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*apiserver.WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -985,8 +932,7 @@ func Convert_v1alpha1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(i } func autoConvert_apiserver_WebhookConnectionInfo_To_v1alpha1_WebhookConnectionInfo(in *apiserver.WebhookConnectionInfo, out *WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -996,7 +942,7 @@ func Convert_apiserver_WebhookConnectionInfo_To_v1alpha1_WebhookConnectionInfo(i } func autoConvert_v1alpha1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(in *WebhookMatchCondition, out *apiserver.WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*apiserver.WebhookMatchCondition)(unsafe.Pointer(in)) return nil } @@ -1006,7 +952,7 @@ func Convert_v1alpha1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(i } func autoConvert_apiserver_WebhookMatchCondition_To_v1alpha1_WebhookMatchCondition(in *apiserver.WebhookMatchCondition, out *WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*WebhookMatchCondition)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go index 44bfbbd3c..6d154d8c3 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go @@ -25,7 +25,7 @@ import ( // EgressSelectorConfiguration provides versioned configuration for egress selector clients. type EgressSelectorConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // connectionServices contains a list of egress selection client configurations EgressSelections []EgressSelection `json:"egressSelections"` @@ -128,17 +128,17 @@ type TLSConfig struct { // TracingConfiguration provides versioned configuration for tracing clients. type TracingConfiguration struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Embed the component config tracing configuration struct - tracingapi.TracingConfiguration `json:",inline"` + tracingapi.TracingConfiguration `json:""` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // AuthenticationConfiguration provides versioned configuration for authentication. type AuthenticationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // jwt is a list of authenticator to authenticate Kubernetes users using // JWT compliant tokens. The authenticator will attempt to parse a raw ID token, @@ -503,7 +503,7 @@ type UserValidationRule struct { // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type AuthorizationConfiguration struct { - metav1.TypeMeta + metav1.TypeMeta `json:""` // Authorizers is an ordered list of authorizers to // authorize requests against. diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/zz_generated.conversion.go index 04323e208..373285734 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/zz_generated.conversion.go @@ -281,7 +281,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1beta1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition(in *AnonymousAuthCondition, out *apiserver.AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*apiserver.AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -291,7 +291,7 @@ func Convert_v1beta1_AnonymousAuthCondition_To_apiserver_AnonymousAuthCondition( } func autoConvert_apiserver_AnonymousAuthCondition_To_v1beta1_AnonymousAuthCondition(in *apiserver.AnonymousAuthCondition, out *AnonymousAuthCondition, s conversion.Scope) error { - out.Path = in.Path + *out = *(*AnonymousAuthCondition)(unsafe.Pointer(in)) return nil } @@ -301,8 +301,7 @@ func Convert_apiserver_AnonymousAuthCondition_To_v1beta1_AnonymousAuthCondition( } func autoConvert_v1beta1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *AnonymousAuthConfig, out *apiserver.AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]apiserver.AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*apiserver.AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -312,8 +311,7 @@ func Convert_v1beta1_AnonymousAuthConfig_To_apiserver_AnonymousAuthConfig(in *An } func autoConvert_apiserver_AnonymousAuthConfig_To_v1beta1_AnonymousAuthConfig(in *apiserver.AnonymousAuthConfig, out *AnonymousAuthConfig, s conversion.Scope) error { - out.Enabled = in.Enabled - out.Conditions = *(*[]AnonymousAuthCondition)(unsafe.Pointer(&in.Conditions)) + *out = *(*AnonymousAuthConfig)(unsafe.Pointer(in)) return nil } @@ -445,16 +443,7 @@ func Convert_apiserver_AuthorizerConfiguration_To_v1beta1_AuthorizerConfiguratio } func autoConvert_v1beta1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings, out *apiserver.ClaimMappings, s conversion.Scope) error { - if err := Convert_v1beta1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_v1beta1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_v1beta1_ClaimOrExpression_To_apiserver_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]apiserver.ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*apiserver.ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -464,16 +453,7 @@ func Convert_v1beta1_ClaimMappings_To_apiserver_ClaimMappings(in *ClaimMappings, } func autoConvert_apiserver_ClaimMappings_To_v1beta1_ClaimMappings(in *apiserver.ClaimMappings, out *ClaimMappings, s conversion.Scope) error { - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1beta1_PrefixedClaimOrExpression(&in.Username, &out.Username, s); err != nil { - return err - } - if err := Convert_apiserver_PrefixedClaimOrExpression_To_v1beta1_PrefixedClaimOrExpression(&in.Groups, &out.Groups, s); err != nil { - return err - } - if err := Convert_apiserver_ClaimOrExpression_To_v1beta1_ClaimOrExpression(&in.UID, &out.UID, s); err != nil { - return err - } - out.Extra = *(*[]ExtraMapping)(unsafe.Pointer(&in.Extra)) + *out = *(*ClaimMappings)(unsafe.Pointer(in)) return nil } @@ -483,8 +463,7 @@ func Convert_apiserver_ClaimMappings_To_v1beta1_ClaimMappings(in *apiserver.Clai } func autoConvert_v1beta1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *ClaimOrExpression, out *apiserver.ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*apiserver.ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -494,8 +473,7 @@ func Convert_v1beta1_ClaimOrExpression_To_apiserver_ClaimOrExpression(in *ClaimO } func autoConvert_apiserver_ClaimOrExpression_To_v1beta1_ClaimOrExpression(in *apiserver.ClaimOrExpression, out *ClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Expression = in.Expression + *out = *(*ClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -505,10 +483,7 @@ func Convert_apiserver_ClaimOrExpression_To_v1beta1_ClaimOrExpression(in *apiser } func autoConvert_v1beta1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *ClaimValidationRule, out *apiserver.ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -518,10 +493,7 @@ func Convert_v1beta1_ClaimValidationRule_To_apiserver_ClaimValidationRule(in *Cl } func autoConvert_apiserver_ClaimValidationRule_To_v1beta1_ClaimValidationRule(in *apiserver.ClaimValidationRule, out *ClaimValidationRule, s conversion.Scope) error { - out.Claim = in.Claim - out.RequiredValue = in.RequiredValue - out.Expression = in.Expression - out.Message = in.Message + *out = *(*ClaimValidationRule)(unsafe.Pointer(in)) return nil } @@ -531,8 +503,7 @@ func Convert_apiserver_ClaimValidationRule_To_v1beta1_ClaimValidationRule(in *ap } func autoConvert_v1beta1_Connection_To_apiserver_Connection(in *Connection, out *apiserver.Connection, s conversion.Scope) error { - out.ProxyProtocol = apiserver.ProtocolType(in.ProxyProtocol) - out.Transport = (*apiserver.Transport)(unsafe.Pointer(in.Transport)) + *out = *(*apiserver.Connection)(unsafe.Pointer(in)) return nil } @@ -542,8 +513,7 @@ func Convert_v1beta1_Connection_To_apiserver_Connection(in *Connection, out *api } func autoConvert_apiserver_Connection_To_v1beta1_Connection(in *apiserver.Connection, out *Connection, s conversion.Scope) error { - out.ProxyProtocol = ProtocolType(in.ProxyProtocol) - out.Transport = (*Transport)(unsafe.Pointer(in.Transport)) + *out = *(*Connection)(unsafe.Pointer(in)) return nil } @@ -614,8 +584,7 @@ func Convert_apiserver_EgressSelectorConfiguration_To_v1beta1_EgressSelectorConf } func autoConvert_v1beta1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, out *apiserver.ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*apiserver.ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -625,8 +594,7 @@ func Convert_v1beta1_ExtraMapping_To_apiserver_ExtraMapping(in *ExtraMapping, ou } func autoConvert_apiserver_ExtraMapping_To_v1beta1_ExtraMapping(in *apiserver.ExtraMapping, out *ExtraMapping, s conversion.Scope) error { - out.Key = in.Key - out.ValueExpression = in.ValueExpression + *out = *(*ExtraMapping)(unsafe.Pointer(in)) return nil } @@ -704,9 +672,7 @@ func Convert_apiserver_JWTAuthenticator_To_v1beta1_JWTAuthenticator(in *apiserve } func autoConvert_v1beta1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpression(in *PrefixedClaimOrExpression, out *apiserver.PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*apiserver.PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -716,9 +682,7 @@ func Convert_v1beta1_PrefixedClaimOrExpression_To_apiserver_PrefixedClaimOrExpre } func autoConvert_apiserver_PrefixedClaimOrExpression_To_v1beta1_PrefixedClaimOrExpression(in *apiserver.PrefixedClaimOrExpression, out *PrefixedClaimOrExpression, s conversion.Scope) error { - out.Claim = in.Claim - out.Prefix = (*string)(unsafe.Pointer(in.Prefix)) - out.Expression = in.Expression + *out = *(*PrefixedClaimOrExpression)(unsafe.Pointer(in)) return nil } @@ -728,8 +692,7 @@ func Convert_apiserver_PrefixedClaimOrExpression_To_v1beta1_PrefixedClaimOrExpre } func autoConvert_v1beta1_TCPTransport_To_apiserver_TCPTransport(in *TCPTransport, out *apiserver.TCPTransport, s conversion.Scope) error { - out.URL = in.URL - out.TLSConfig = (*apiserver.TLSConfig)(unsafe.Pointer(in.TLSConfig)) + *out = *(*apiserver.TCPTransport)(unsafe.Pointer(in)) return nil } @@ -739,8 +702,7 @@ func Convert_v1beta1_TCPTransport_To_apiserver_TCPTransport(in *TCPTransport, ou } func autoConvert_apiserver_TCPTransport_To_v1beta1_TCPTransport(in *apiserver.TCPTransport, out *TCPTransport, s conversion.Scope) error { - out.URL = in.URL - out.TLSConfig = (*TLSConfig)(unsafe.Pointer(in.TLSConfig)) + *out = *(*TCPTransport)(unsafe.Pointer(in)) return nil } @@ -750,10 +712,7 @@ func Convert_apiserver_TCPTransport_To_v1beta1_TCPTransport(in *apiserver.TCPTra } func autoConvert_v1beta1_TLSConfig_To_apiserver_TLSConfig(in *TLSConfig, out *apiserver.TLSConfig, s conversion.Scope) error { - out.CABundle = in.CABundle - out.ClientKey = in.ClientKey - out.ClientCert = in.ClientCert - out.TLSServerName = in.TLSServerName + *out = *(*apiserver.TLSConfig)(unsafe.Pointer(in)) return nil } @@ -763,10 +722,7 @@ func Convert_v1beta1_TLSConfig_To_apiserver_TLSConfig(in *TLSConfig, out *apiser } func autoConvert_apiserver_TLSConfig_To_v1beta1_TLSConfig(in *apiserver.TLSConfig, out *TLSConfig, s conversion.Scope) error { - out.CABundle = in.CABundle - out.ClientKey = in.ClientKey - out.ClientCert = in.ClientCert - out.TLSServerName = in.TLSServerName + *out = *(*TLSConfig)(unsafe.Pointer(in)) return nil } @@ -796,8 +752,7 @@ func Convert_apiserver_TracingConfiguration_To_v1beta1_TracingConfiguration(in * } func autoConvert_v1beta1_Transport_To_apiserver_Transport(in *Transport, out *apiserver.Transport, s conversion.Scope) error { - out.TCP = (*apiserver.TCPTransport)(unsafe.Pointer(in.TCP)) - out.UDS = (*apiserver.UDSTransport)(unsafe.Pointer(in.UDS)) + *out = *(*apiserver.Transport)(unsafe.Pointer(in)) return nil } @@ -807,8 +762,7 @@ func Convert_v1beta1_Transport_To_apiserver_Transport(in *Transport, out *apiser } func autoConvert_apiserver_Transport_To_v1beta1_Transport(in *apiserver.Transport, out *Transport, s conversion.Scope) error { - out.TCP = (*TCPTransport)(unsafe.Pointer(in.TCP)) - out.UDS = (*UDSTransport)(unsafe.Pointer(in.UDS)) + *out = *(*Transport)(unsafe.Pointer(in)) return nil } @@ -818,7 +772,7 @@ func Convert_apiserver_Transport_To_v1beta1_Transport(in *apiserver.Transport, o } func autoConvert_v1beta1_UDSTransport_To_apiserver_UDSTransport(in *UDSTransport, out *apiserver.UDSTransport, s conversion.Scope) error { - out.UDSName = in.UDSName + *out = *(*apiserver.UDSTransport)(unsafe.Pointer(in)) return nil } @@ -828,7 +782,7 @@ func Convert_v1beta1_UDSTransport_To_apiserver_UDSTransport(in *UDSTransport, ou } func autoConvert_apiserver_UDSTransport_To_v1beta1_UDSTransport(in *apiserver.UDSTransport, out *UDSTransport, s conversion.Scope) error { - out.UDSName = in.UDSName + *out = *(*UDSTransport)(unsafe.Pointer(in)) return nil } @@ -838,8 +792,7 @@ func Convert_apiserver_UDSTransport_To_v1beta1_UDSTransport(in *apiserver.UDSTra } func autoConvert_v1beta1_UserValidationRule_To_apiserver_UserValidationRule(in *UserValidationRule, out *apiserver.UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*apiserver.UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -849,8 +802,7 @@ func Convert_v1beta1_UserValidationRule_To_apiserver_UserValidationRule(in *User } func autoConvert_apiserver_UserValidationRule_To_v1beta1_UserValidationRule(in *apiserver.UserValidationRule, out *UserValidationRule, s conversion.Scope) error { - out.Expression = in.Expression - out.Message = in.Message + *out = *(*UserValidationRule)(unsafe.Pointer(in)) return nil } @@ -910,8 +862,7 @@ func Convert_apiserver_WebhookConfiguration_To_v1beta1_WebhookConfiguration(in * } func autoConvert_v1beta1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(in *WebhookConnectionInfo, out *apiserver.WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*apiserver.WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -921,8 +872,7 @@ func Convert_v1beta1_WebhookConnectionInfo_To_apiserver_WebhookConnectionInfo(in } func autoConvert_apiserver_WebhookConnectionInfo_To_v1beta1_WebhookConnectionInfo(in *apiserver.WebhookConnectionInfo, out *WebhookConnectionInfo, s conversion.Scope) error { - out.Type = in.Type - out.KubeConfigFile = (*string)(unsafe.Pointer(in.KubeConfigFile)) + *out = *(*WebhookConnectionInfo)(unsafe.Pointer(in)) return nil } @@ -932,7 +882,7 @@ func Convert_apiserver_WebhookConnectionInfo_To_v1beta1_WebhookConnectionInfo(in } func autoConvert_v1beta1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(in *WebhookMatchCondition, out *apiserver.WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*apiserver.WebhookMatchCondition)(unsafe.Pointer(in)) return nil } @@ -942,7 +892,7 @@ func Convert_v1beta1_WebhookMatchCondition_To_apiserver_WebhookMatchCondition(in } func autoConvert_apiserver_WebhookMatchCondition_To_v1beta1_WebhookMatchCondition(in *apiserver.WebhookMatchCondition, out *WebhookMatchCondition, s conversion.Scope) error { - out.Expression = in.Expression + *out = *(*WebhookMatchCondition)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/types.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/types.go index 8c6dc676a..80a7175ca 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/types.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/types.go @@ -70,7 +70,7 @@ const ( // Event captures all the information that can be included in an API audit log. type Event struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // AuditLevel at which event was generated Level Level `json:"level" protobuf:"bytes,1,opt,name=level,casttype=Level"` @@ -156,7 +156,7 @@ type AuthenticationMetadata struct { // EventList is a list of audit Events. type EventList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -168,7 +168,7 @@ type EventList struct { // Policy defines the configuration of audit logging, and the rules for how different request // categories are logged. type Policy struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // ObjectMeta is included for interoperability with API infrastructure. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` @@ -200,7 +200,7 @@ type Policy struct { // PolicyList is a list of audit Policies. type PolicyList struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` diff --git a/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/zz_generated.conversion.go b/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/zz_generated.conversion.go index 904d9c12b..57205fbaf 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/apis/audit/v1/zz_generated.conversion.go @@ -123,7 +123,7 @@ func RegisterConversions(s *runtime.Scheme) error { } func autoConvert_v1_AuthenticationMetadata_To_audit_AuthenticationMetadata(in *AuthenticationMetadata, out *audit.AuthenticationMetadata, s conversion.Scope) error { - out.ImpersonationConstraint = in.ImpersonationConstraint + *out = *(*audit.AuthenticationMetadata)(unsafe.Pointer(in)) return nil } @@ -133,7 +133,7 @@ func Convert_v1_AuthenticationMetadata_To_audit_AuthenticationMetadata(in *Authe } func autoConvert_audit_AuthenticationMetadata_To_v1_AuthenticationMetadata(in *audit.AuthenticationMetadata, out *AuthenticationMetadata, s conversion.Scope) error { - out.ImpersonationConstraint = in.ImpersonationConstraint + *out = *(*AuthenticationMetadata)(unsafe.Pointer(in)) return nil } @@ -217,9 +217,7 @@ func Convert_audit_EventList_To_v1_EventList(in *audit.EventList, out *EventList } func autoConvert_v1_GroupResources_To_audit_GroupResources(in *GroupResources, out *audit.GroupResources, s conversion.Scope) error { - out.Group = in.Group - out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) - out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames)) + *out = *(*audit.GroupResources)(unsafe.Pointer(in)) return nil } @@ -229,9 +227,7 @@ func Convert_v1_GroupResources_To_audit_GroupResources(in *GroupResources, out * } func autoConvert_audit_GroupResources_To_v1_GroupResources(in *audit.GroupResources, out *GroupResources, s conversion.Scope) error { - out.Group = in.Group - out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) - out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames)) + *out = *(*GroupResources)(unsafe.Pointer(in)) return nil } @@ -241,14 +237,7 @@ func Convert_audit_GroupResources_To_v1_GroupResources(in *audit.GroupResources, } func autoConvert_v1_ObjectReference_To_audit_ObjectReference(in *ObjectReference, out *audit.ObjectReference, s conversion.Scope) error { - out.Resource = in.Resource - out.Namespace = in.Namespace - out.Name = in.Name - out.UID = types.UID(in.UID) - out.APIGroup = in.APIGroup - out.APIVersion = in.APIVersion - out.ResourceVersion = in.ResourceVersion - out.Subresource = in.Subresource + *out = *(*audit.ObjectReference)(unsafe.Pointer(in)) return nil } @@ -258,14 +247,7 @@ func Convert_v1_ObjectReference_To_audit_ObjectReference(in *ObjectReference, ou } func autoConvert_audit_ObjectReference_To_v1_ObjectReference(in *audit.ObjectReference, out *ObjectReference, s conversion.Scope) error { - out.Resource = in.Resource - out.Namespace = in.Namespace - out.Name = in.Name - out.UID = types.UID(in.UID) - out.APIGroup = in.APIGroup - out.APIVersion = in.APIVersion - out.ResourceVersion = in.ResourceVersion - out.Subresource = in.Subresource + *out = *(*ObjectReference)(unsafe.Pointer(in)) return nil } @@ -323,15 +305,7 @@ func Convert_audit_PolicyList_To_v1_PolicyList(in *audit.PolicyList, out *Policy } func autoConvert_v1_PolicyRule_To_audit_PolicyRule(in *PolicyRule, out *audit.PolicyRule, s conversion.Scope) error { - out.Level = audit.Level(in.Level) - out.Users = *(*[]string)(unsafe.Pointer(&in.Users)) - out.UserGroups = *(*[]string)(unsafe.Pointer(&in.UserGroups)) - out.Verbs = *(*[]string)(unsafe.Pointer(&in.Verbs)) - out.Resources = *(*[]audit.GroupResources)(unsafe.Pointer(&in.Resources)) - out.Namespaces = *(*[]string)(unsafe.Pointer(&in.Namespaces)) - out.NonResourceURLs = *(*[]string)(unsafe.Pointer(&in.NonResourceURLs)) - out.OmitStages = *(*[]audit.Stage)(unsafe.Pointer(&in.OmitStages)) - out.OmitManagedFields = (*bool)(unsafe.Pointer(in.OmitManagedFields)) + *out = *(*audit.PolicyRule)(unsafe.Pointer(in)) return nil } @@ -341,15 +315,7 @@ func Convert_v1_PolicyRule_To_audit_PolicyRule(in *PolicyRule, out *audit.Policy } func autoConvert_audit_PolicyRule_To_v1_PolicyRule(in *audit.PolicyRule, out *PolicyRule, s conversion.Scope) error { - out.Level = Level(in.Level) - out.Users = *(*[]string)(unsafe.Pointer(&in.Users)) - out.UserGroups = *(*[]string)(unsafe.Pointer(&in.UserGroups)) - out.Verbs = *(*[]string)(unsafe.Pointer(&in.Verbs)) - out.Resources = *(*[]GroupResources)(unsafe.Pointer(&in.Resources)) - out.Namespaces = *(*[]string)(unsafe.Pointer(&in.Namespaces)) - out.NonResourceURLs = *(*[]string)(unsafe.Pointer(&in.NonResourceURLs)) - out.OmitStages = *(*[]Stage)(unsafe.Pointer(&in.OmitStages)) - out.OmitManagedFields = (*bool)(unsafe.Pointer(in.OmitManagedFields)) + *out = *(*PolicyRule)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go b/constraint/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go index dd11efbde..a811d9674 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go @@ -20,6 +20,7 @@ import ( "fmt" "strings" + authenticationv1 "k8s.io/api/authentication/v1" v1 "k8s.io/api/core/v1" apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" "k8s.io/apiserver/pkg/authentication/user" @@ -48,6 +49,28 @@ const ( // NodeUIDKey is the key used in a user's "extra" to specify the node UID of // the authenticating request. NodeUIDKey = "authentication.kubernetes.io/node-uid" + // ValidatingWebhookConfigurationNameKey is the key used in a user's + // "extra" to specify the validating webhook configuration name of + // the authenticating request. + ValidatingWebhookConfigurationNameKey = "authentication.kubernetes.io/validatingwebhookconfiguration-name" + // ValidatingWebhookConfigurationUIDKey is the key used in a user's + // "extra" to specify the validating webhook configuration UID of + // the authenticating request. + ValidatingWebhookConfigurationUIDKey = "authentication.kubernetes.io/validatingwebhookconfiguration-uid" + // MutatingWebhookConfigurationNameKey is the key used in a user's + // "extra" to specify the mutating webhook configuration name of + // the authenticating request. + MutatingWebhookConfigurationNameKey = "authentication.kubernetes.io/mutatingwebhookconfiguration-name" + // MutatingWebhookConfigurationUIDKey is the key used in a user's + // "extra" to specify the mutating webhook configuration UID of + // the authenticating request. + MutatingWebhookConfigurationUIDKey = "authentication.kubernetes.io/mutatingwebhookconfiguration-uid" + // AttestationKeyPrefix is the prefix for the user info extra key used to + // detail attestations. + AttestationKeyPrefix = "attestation.authentication.kubernetes.io/" + // AttestationAdmissionReviewAPIGroupsKey is the key used in a user's + // "extra" to specify the "admissionReviewAPIGroups" claim. + AttestationAdmissionReviewAPIGroupsKey = AttestationKeyPrefix + authenticationv1.AttestationAdmissionReviewAPIGroups ) // MakeUsername generates a username from the given namespace and ServiceAccount name. @@ -123,10 +146,13 @@ func UserInfo(namespace, name, uid string) user.Info { } type ServiceAccountInfo struct { - Name, Namespace, UID string - PodName, PodUID string - CredentialID string - NodeName, NodeUID string + Name, Namespace, UID string + PodName, PodUID string + CredentialID string + NodeName, NodeUID string + ValidatingWebhookConfigurationName, ValidatingWebhookConfigurationUID string + MutatingWebhookConfigurationName, MutatingWebhookConfigurationUID string + AttestationAdmissionReviewAPIGroups []string } func (sa *ServiceAccountInfo) UserInfo() user.Info { @@ -159,6 +185,28 @@ func (sa *ServiceAccountInfo) UserInfo() user.Info { info.Extra[NodeUIDKey] = []string{sa.NodeUID} } } + if sa.ValidatingWebhookConfigurationName != "" && sa.ValidatingWebhookConfigurationUID != "" { + if info.Extra == nil { + info.Extra = make(map[string][]string) + } + info.Extra[ValidatingWebhookConfigurationNameKey] = []string{sa.ValidatingWebhookConfigurationName} + info.Extra[ValidatingWebhookConfigurationUIDKey] = []string{sa.ValidatingWebhookConfigurationUID} + } + + if sa.MutatingWebhookConfigurationName != "" && sa.MutatingWebhookConfigurationUID != "" { + if info.Extra == nil { + info.Extra = make(map[string][]string) + } + info.Extra[MutatingWebhookConfigurationNameKey] = []string{sa.MutatingWebhookConfigurationName} + info.Extra[MutatingWebhookConfigurationUIDKey] = []string{sa.MutatingWebhookConfigurationUID} + } + + if len(sa.AttestationAdmissionReviewAPIGroups) > 0 { + if info.Extra == nil { + info.Extra = make(map[string][]string) + } + info.Extra[AttestationAdmissionReviewAPIGroupsKey] = sa.AttestationAdmissionReviewAPIGroups + } return info } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditions.go b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditions.go new file mode 100644 index 000000000..5b00f6fa5 --- /dev/null +++ b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditions.go @@ -0,0 +1,307 @@ +/* +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 authorizer + +import ( + "fmt" + "iter" + "strings" + + utilerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apimachinery/pkg/util/sets" +) + +// conditionsAwareDecisionType is a small enum-like type for keeping track of what type a ConditionsAwareDecision is. +// These values must never be exposed to users outside of this package, and should not be used for anything else than +// keeping track of what type of a ConditionsAwareDecision is. +type conditionsAwareDecisionType int + +const ( + // conditionsAwareDecisionTypeDeny represents the unconditional Deny decision. + // It is zero such that ConditionsAwareDecision{}.IsDeny() == true + conditionsAwareDecisionTypeDeny conditionsAwareDecisionType = 0 + // conditionsAwareDecisionTypeAllow represents the unconditional Allow decision. + // It has a different value from DecisionAllow to never be conflated with that. + conditionsAwareDecisionTypeAllow conditionsAwareDecisionType = 11 + // conditionsAwareDecisionTypeNoOpinion represents the unconditional NoOpinion decision. + // It has a different value from DecisionNoOpinion to never be conflated with that. + conditionsAwareDecisionTypeNoOpinion conditionsAwareDecisionType = 12 + // conditionsAwareDecisionTypeConditionsMap represents the conditional ConditionsMap decision. + conditionsAwareDecisionTypeConditionsMap conditionsAwareDecisionType = 13 + // conditionsAwareDecisionTypeUnion represents a conditional Union decision. + conditionsAwareDecisionTypeUnion conditionsAwareDecisionType = 14 +) + +// ConditionsAwareDecision models an authorization decision that is conditions-aware. +// It is an enum type of the following five variants: +// - Allow: unconditional Allow. +// - Deny: unconditional Deny. +// - NoOpinion: unconditional NoOpinion. +// - Conditional: conditional on some previously-unseen data. +// - Union: an ordered list of sub-decisions, which forms a tree of decisions. +// +// The zero value (ConditionsAwareDecision{}) is equivalent to ConditionsAwareDecisionDeny(). +// A ConditionsAwareDecision is passed by value. +// Important: A ConditionsAwareDecision is immutable after construction. +type ConditionsAwareDecision struct { + decisionType conditionsAwareDecisionType + + conditionsMap ConditionsMap + union ConditionsAwareDecisionUnion + + reason string + err error +} + +// ConditionsAwareDecisionDeny constructs a Deny decision with the given reason and error. +func ConditionsAwareDecisionDeny(reason string, err error) ConditionsAwareDecision { + return ConditionsAwareDecision{ + // conditionsAwareDecisionTypeDeny == 0 == zero value + // => ConditionsAwareDecision{} == ConditionsAwareDecisionDeny() + decisionType: conditionsAwareDecisionTypeDeny, + reason: reason, + err: err, + } +} + +// ConditionsAwareDecisionAllow constructs an Allow decision with the given reason and error. +func ConditionsAwareDecisionAllow(reason string, err error) ConditionsAwareDecision { + return ConditionsAwareDecision{ + decisionType: conditionsAwareDecisionTypeAllow, + reason: reason, + err: err, + } +} + +// ConditionsAwareDecisionNoOpinion constructs a NoOpinion decision with the given reason and error. +func ConditionsAwareDecisionNoOpinion(reason string, err error) ConditionsAwareDecision { + return ConditionsAwareDecision{ + decisionType: conditionsAwareDecisionTypeNoOpinion, + reason: reason, + err: err, + } +} + +// ConditionsAwareDecisionFromParts is meant to be used by conditions-unaware Authorizer implementations +// in order to implement ConditionsAwareAuthorize as: +// "return authorizer.ConditionsAwareDecisionFromParts(self.Authorize(ctx, a))" +func ConditionsAwareDecisionFromParts(unconditional Decision, reason string, err error) ConditionsAwareDecision { + switch unconditional { + case DecisionAllow: + return ConditionsAwareDecisionAllow(reason, err) + case DecisionNoOpinion: + return ConditionsAwareDecisionNoOpinion(reason, err) + case DecisionDeny: + return ConditionsAwareDecisionDeny(reason, err) + default: + return ConditionsAwareDecisionDeny(reason, utilerrors.NewAggregate( + []error{ + err, + fmt.Errorf("unknown unconditional decision type: %d", unconditional), + }, + )) + } +} + +// IsAllow returns true if the decision is an unconditional Allow. +func (d ConditionsAwareDecision) IsAllow() bool { + return d.decisionType == conditionsAwareDecisionTypeAllow +} + +// IsNoOpinion returns true if the decision is an unconditional NoOpinion. +func (d ConditionsAwareDecision) IsNoOpinion() bool { + return d.decisionType == conditionsAwareDecisionTypeNoOpinion +} + +// IsDeny returns true if the decision is an unconditional Deny. +func (d ConditionsAwareDecision) IsDeny() bool { + return d.decisionType == conditionsAwareDecisionTypeDeny // == 0 == zero value +} + +// IsConditionsMap returns true if the decision is a conditional response +// with a map of conditions to evaluate. +func (d ConditionsAwareDecision) IsConditionsMap() bool { + return d.decisionType == conditionsAwareDecisionTypeConditionsMap +} + +// ConditionsMap returns the ConditionsMap, which is non-empty +// if and only if IsConditionsMap is true. +func (d ConditionsAwareDecision) ConditionsMap() ConditionsMap { + return d.conditionsMap +} + +// IsUnion returns true if the decision consists of other sub-decisions +// unioned together in a tree-like structure. +func (d ConditionsAwareDecision) IsUnion() bool { + return d.decisionType == conditionsAwareDecisionTypeUnion +} + +// IsUnconditional is true if d is Allow, Deny or NoOpinion. +func (d ConditionsAwareDecision) IsUnconditional() bool { + return d.IsAllow() || d.IsDeny() || d.IsNoOpinion() +} + +// unconditionalParts turns a ConditionsAwareDecision into the +// triple that Authorize expects. If the decision is +// conditional, the returned condition is Deny if there were at least +// some Deny condition, otherwise NoOpinion. +// This function is meant to be called when IsUnconditional() == true. +// +// If the authorizer is conditions-aware, it can choose to only implement +// real business logic in the ConditionsAwareAuthorize method, and implement +// Authorize() as "return self.ConditionsAwareAuthorize(ctx, attrs).unconditionalParts()" +// +// Private for now, to not encourage callers to perform conditions-aware logic where not needed. +func (d ConditionsAwareDecision) unconditionalParts() (Decision, string, error) { + switch { + case d.IsAllow(): + return DecisionAllow, d.Reason(), d.Error() + case d.IsDeny(): + return DecisionDeny, d.Reason(), d.Error() + case d.IsNoOpinion(): + return DecisionNoOpinion, d.Reason(), d.Error() + default: + // An error is not returned here, as that could yield a HTTP response code of 500 instead of 403. + // For the use-case described above with regards to calling this function in Authorize, not returning + // an error is important, as it is valid to always fail closed, as if this happens, no unconditional + // permissions were given the requestor. + return d.FailureDecision(), "failed closed: tried to return conditional decision to conditions-unaware authorizer", nil + } +} + +// PossibleDecisions details what are the possible decision outcomes of this +// ConditionsAwareDecision. The return value is a subset of {Allow, Deny, NoOpinion}, +// but never the empty set. If the set only contains a single value, it means the +// decision is unconditional. +func (d ConditionsAwareDecision) PossibleDecisions() sets.Set[Decision] { + switch { + case d.IsAllow(): + return sets.New(DecisionAllow) + case d.IsNoOpinion(): + return sets.New(DecisionNoOpinion) + case d.IsConditionsMap(): + return d.ConditionsMap().PossibleDecisions() + case d.IsUnion(): + return d.union.PossibleDecisions() + default: // default case Deny + return sets.New(DecisionDeny) + } +} + +// FailureDecision returns either a Deny or NoOpinion decision that the caller can +// use if the caller encounters an unrecoverable error while processing a +// ConditionsAwareDecision. If this decision is or could evaluate to Deny +// this function returns DecisionDeny to the caller, in order to fail closed +// as a conservative approximation. Otherwise, NoOpinion is returned. +func (d ConditionsAwareDecision) FailureDecision() Decision { + if d.PossibleDecisions().Has(DecisionDeny) { + return DecisionDeny + } + return DecisionNoOpinion +} + +// ContainsUnconditionalAllowOrDeny returns true whether there union contains at least one +// Allow or Deny decision within the tree of decisions. +func (d ConditionsAwareDecision) ContainsUnconditionalAllowOrDeny() bool { + if d.IsAllow() || d.IsDeny() { + return true + } + if d.IsNoOpinion() || d.IsConditionsMap() { + return false + } + return d.union.ContainsUnconditionalAllowOrDeny() +} + +// UnionedDecisions returns an iterator for unioned sub-decisions. +// This iterator is non-empty if and only if IsUnion() == true. +// Sub-decisions iteration order is preserved. +func (d ConditionsAwareDecision) UnionedDecisions() iter.Seq2[string, ConditionsAwareDecision] { + return func(yield func(string, ConditionsAwareDecision) bool) { + for _, subDecision := range d.union.inner { + if !yield(subDecision.conditionalAuthorizerName, subDecision.d) { + return + } + } + } +} + +// Reason returns the reason supplied when constructing +// an unconditional decision. +// Reason is an empty string for conditional decisions. +func (d ConditionsAwareDecision) Reason() string { + return d.reason +} + +// Error returns the error supplied when constructing +// an unconditional decision. +// Error is nil for conditional decisions. +func (d ConditionsAwareDecision) Error() error { + return d.err +} + +// String returns a human-readable representation of the decision. +func (d ConditionsAwareDecision) String() string { + if d.IsUnion() { + // No need to take d.reason or d.err into account, as they are always zero for the union. + b := strings.Builder{} + b.WriteString("Union[") + for i, sub := range d.union.inner { + if i != 0 { + b.WriteString(", ") + } + b.WriteString(sub.conditionalAuthorizerName) + b.WriteString(": ") + b.WriteString(sub.d.String()) + } + b.WriteByte(']') + return b.String() + } + params := []string{} + if len(d.reason) != 0 { + params = append(params, fmt.Sprintf("reason=%q", d.reason)) + } + if d.err != nil { + params = append(params, fmt.Sprintf("err=%q", d.err.Error())) + } + paramsStr := func() string { + if len(params) == 0 { + return "" + } + return fmt.Sprintf("(%s)", strings.Join(params, ", ")) + } + if d.IsAllow() { + return fmt.Sprintf("Allow%s", paramsStr()) + } + if d.IsNoOpinion() { + return fmt.Sprintf("NoOpinion%s", paramsStr()) + } + if d.IsConditionsMap() { + if len(d.conditionsMap.denyConditions) != 0 { + params = append(params, fmt.Sprintf("denies=%d", len(d.conditionsMap.denyConditions))) + } + if len(d.conditionsMap.noOpinionConditions) != 0 { + params = append(params, fmt.Sprintf("noopinions=%d", len(d.conditionsMap.noOpinionConditions))) + } + if len(d.conditionsMap.allowConditions) != 0 { + params = append(params, fmt.Sprintf("allows=%d", len(d.conditionsMap.allowConditions))) + } + return fmt.Sprintf("ConditionsMap%s", paramsStr()) + } + // Deny is written such that if none of the other modes apply, + // IsDenied() is true. + return fmt.Sprintf("Deny%s", paramsStr()) +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsmap.go b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsmap.go new file mode 100644 index 000000000..6552fe654 --- /dev/null +++ b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsmap.go @@ -0,0 +1,236 @@ +/* +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 authorizer + +import ( + "context" + "fmt" + "iter" + "slices" + "strings" + + "k8s.io/apimachinery/pkg/api/validate/content" + "k8s.io/apimachinery/pkg/util/sets" +) + +// ConditionsMap is a map of conditions, where each condition has a map-unique +// ID, is a function from ConditionsData -> bool and has Allow/Deny/NoOpinion effect. +// It must be constructed through ConditionsAwareDecisionConditionsMap. +// During construction, all conditions are validated. +type ConditionsMap struct { + // invariant: len(denyConditions) != 0 || len(allowConditions) != 0 + // + // slices are used here instead of actual maps, as the ConditionsMap does + // not need to lookup single elements. It's called a "map" as uniqueness of + // the IDs (keys) across all conditions (values) in the map is enforced. + denyConditions []Condition + noOpinionConditions []Condition + allowConditions []Condition +} + +// FailureDecision returns either a Deny or NoOpinion decision that the caller can +// use if the caller encounters an unrecoverable error while processing a +// ConditionsAwareDecision. If this decision is or could evaluate to Deny +// this function returns DecisionDeny to the caller, in order to fail closed +// as a conservative approximation. Otherwise, NoOpinion is returned. +func (c ConditionsMap) FailureDecision() Decision { + if c.PossibleDecisions().Has(DecisionDeny) { + // Note: this only happens if len(denyConditions) > 0 + return DecisionDeny + } + return DecisionNoOpinion +} + +// Length returns the number of elements in the map. +func (c ConditionsMap) Length() int { + return len(c.denyConditions) + len(c.noOpinionConditions) + len(c.allowConditions) +} + +// DenyConditions returns the Deny conditions in this map. +// The conditions are returned in the same order as they were supplied to ConditionsAwareDecisionConditionsMap. +func (c ConditionsMap) DenyConditions() iter.Seq[Condition] { + return func(yield func(Condition) bool) { + for _, cond := range c.denyConditions { + if !yield(cond) { + return + } + } + } +} + +// NoOpinionConditions returns the NoOpinion conditions in this map. +// The conditions are returned in the same order as they were supplied to ConditionsAwareDecisionConditionsMap. +func (c ConditionsMap) NoOpinionConditions() iter.Seq[Condition] { + return func(yield func(Condition) bool) { + for _, cond := range c.noOpinionConditions { + if !yield(cond) { + return + } + } + } +} + +// AllowConditions returns the Allow conditions in this map. +// The conditions are returned in the same order as they were supplied to ConditionsAwareDecisionConditionsMap. +func (c ConditionsMap) AllowConditions() iter.Seq[Condition] { + return func(yield func(Condition) bool) { + for _, cond := range c.allowConditions { + if !yield(cond) { + return + } + } + } +} + +// PossibleDecisions details what are the possible decision outcomes of this +// ConditionsAwareDecision. The return value is a subset of {Allow, Deny, NoOpinion}, +// but never the empty set. If the set only contains a single value, it means the +// decision is unconditional. +func (c ConditionsMap) PossibleDecisions() sets.Set[Decision] { + possibleDecisions := sets.New(DecisionNoOpinion) + if len(c.allowConditions) > 0 { + possibleDecisions.Insert(DecisionAllow) + } + if len(c.denyConditions) > 0 { + possibleDecisions.Insert(DecisionDeny) + } + return possibleDecisions +} + +// MaxConditionsPerMap is the maximum number of conditions allowed in a single ConditionsMap. +const MaxConditionsPerMap = 128 + +// ConditionsAwareDecisionConditionsMap creates a ConditionsMap decision. +// The conditions are grouped by their effects: Deny, NoOpinion and Allow, that function as follows: +// - Deny: If a Deny condition evaluates to true, the ConditionsMap necessarily evaluates to Deny. +// In this case, no further authorizers are consulted. +// - NoOpinion: If a NoOpinion condition evaluates to true, the given authorizer's ConditionsMap cannot +// evaluate to Allow anymore, but necessarily Deny or NoOpinion, depending on whether there are any true +// Deny conditions. However, later authorizers in the chain can still Allow or Deny. +// It is effectively a softer deny that just overrides the authorizer's own allow policies. +// - Allow: If any Allow condition evaluates to true, the ConditionsMap evaluates to Allow, +// unless any Deny/NoOpinion condition also evaluates to true (in which case the Deny/NoOpinion conditions +// have precedence). +// +// All conditions must be non-nil, this function panics if any condition is nil. +func ConditionsAwareDecisionConditionsMap(denyConditions []Condition, noOpinionConditions []Condition, allowConditions []Condition) ConditionsAwareDecision { + // if there are any Deny conditions, Deny is a possible decision, and thus should we fail closed with Deny in that case + hasDenyEffect := len(denyConditions) > 0 + makeFailClosedError := func(err error) ConditionsAwareDecision { + if hasDenyEffect { + return ConditionsAwareDecisionDeny("failed closed", err) + } + return ConditionsAwareDecisionNoOpinion("failed closed", err) + } + + // enforce minimum 1 and maximum amount of conditions per map + conditionsAmount := len(denyConditions) + len(noOpinionConditions) + len(allowConditions) + if conditionsAmount == 0 { + // Does not use makeFailClosedError, but NoOpinion directly, as in this branch there are no deny conditions, so NoOpinion is safe + return ConditionsAwareDecisionNoOpinion("no conditions", fmt.Errorf("at least one condition must be passed to ConditionsAwareDecisionConditionsMap(), got none")) + } + if conditionsAmount > MaxConditionsPerMap { + return makeFailClosedError(fmt.Errorf("too many conditions: %d exceeds maximum of %d", conditionsAmount, MaxConditionsPerMap)) + } + // short-circuit case: if no Allow or Deny conditions exist, then evaluating this ConditionsMap can never evaluate to Allow or Deny, + // but only NoOpinion, regardless of the data. Thus just fold to NoOpinion directly. + // this upholds the len(denyConditions) != 0 || len(allowConditions) != 0 invariant on the ConditionsMap. + if len(denyConditions) == 0 && len(allowConditions) == 0 { + return ConditionsAwareDecisionNoOpinion("only NoOpinion conditions always evaluate to NoOpinion", nil) + } + + seenIDs := sets.New[string]() + + if err := validateConditions(seenIDs, denyConditions); err != nil { + return makeFailClosedError(err) + } + if err := validateConditions(seenIDs, noOpinionConditions); err != nil { + return makeFailClosedError(err) + } + if err := validateConditions(seenIDs, allowConditions); err != nil { + return makeFailClosedError(err) + } + + return ConditionsAwareDecision{ + decisionType: conditionsAwareDecisionTypeConditionsMap, + conditionsMap: ConditionsMap{ + // ensure immutability of the ConditionsMap after construction by not sharing caller-owned references + denyConditions: slices.Clone(denyConditions), + noOpinionConditions: slices.Clone(noOpinionConditions), + allowConditions: slices.Clone(allowConditions), + }, + } +} + +func validateConditions(seenIDs sets.Set[string], conditions []Condition) error { + for _, condition := range conditions { + + id := condition.GetID() + if seenIDs.Has(id) { + return fmt.Errorf("duplicate condition ID %q", id) + } + seenIDs.Insert(id) + + // Validate ID as a label key. + if errs := content.IsLabelKey(id); len(errs) > 0 { + return fmt.Errorf("invalid condition ID %q: %s", id, strings.Join(errs, "; ")) + } + + // Validate type as a label key, if set. + if conditionType := condition.GetType(); len(conditionType) != 0 { + if errs := content.IsLabelKey(conditionType); len(errs) > 0 { + return fmt.Errorf("invalid condition type %q: %s", conditionType, strings.Join(errs, "; ")) + } + } + } + return nil +} + +// GenericCondition is a generic implementation of the Condition interface, +// with optional support for fast in-process conditions evaluation, by +// setting EvaluateFunc non-nil. +type GenericCondition struct { + ID string + Condition string + Type string + Description string + EvaluateFunc func(ctx context.Context, data ConditionsData) ConditionEvaluationResult +} + +var _ Condition = GenericCondition{} + +func (c GenericCondition) GetID() string { + return c.ID +} + +func (c GenericCondition) GetCondition() string { + return c.Condition +} + +func (c GenericCondition) GetType() string { + return c.Type +} + +func (c GenericCondition) GetDescription() string { + return c.Description +} +func (c GenericCondition) Evaluate(ctx context.Context, data ConditionsData) ConditionEvaluationResult { + if c.EvaluateFunc == nil { + return ConditionsEvaluationResultUnevaluatable() + } + return c.EvaluateFunc(ctx, data) +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsunion.go b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsunion.go new file mode 100644 index 000000000..a40ad25b9 --- /dev/null +++ b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/conditionsunion.go @@ -0,0 +1,204 @@ +/* +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 authorizer + +import ( + "errors" + "fmt" + "slices" + "strings" + + utilerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apimachinery/pkg/util/sets" +) + +type namedConditionsAwareDecision struct { + conditionalAuthorizerName string + d ConditionsAwareDecision +} + +// ConditionsAwareDecisionUnion is a builder struct for a Union-typed ConditionsAwareDecision. +// ConditionsAwareDecisionUnion is not thread-safe. +type ConditionsAwareDecisionUnion struct { + // Note: Remember to register any fields added here to the deepcopy in ToDecision + inner []namedConditionsAwareDecision + errs []error + // containsUnconditionalAllowOrDeny is a memorized value of whether any of + // the conditions in inner contain an unconditional Allow or Deny leaf. + containsUnconditionalAllowOrDeny bool + // subDecisionsPossibleDecisions is a memorized union of all added decisions' + // PossibleDecisions. Important: This is NOT the same as + // ConditionsAwareDecisionUnion.PossibleDecisions, as that also + // requires extra NoOpinion handling, adding NoOpinion in the empty + // union case, and removing it if containsUnconditionalAllowOrDeny == true. + subDecisionsPossibleDecisions sets.Set[Decision] +} + +// Add adds a named sub-decision to the current Union ConditionsAwareDecision builder. +// Add is a no-op if ContainsUnconditionalAllowOrDeny() is true, as adding decisions after an Allow or +// Deny will never change the final evaluated outcome. +// An error might be returned if the name is empty or a duplicate, the bool signifies whether +// the Add was a no-op. +// Add is not thread-safe. +func (unionMap *ConditionsAwareDecisionUnion) Add(conditionalAuthorizerName string, d ConditionsAwareDecision) { + if unionMap.ContainsUnconditionalAllowOrDeny() { + return // all items after the first concrete Allow or Deny aren't anyways used in evaluation, so they are not added to inner + } + + if len(conditionalAuthorizerName) == 0 { + unionMap.errs = append(unionMap.errs, fmt.Errorf("conditionalAuthorizerName must be non-empty")) + } + if unionMap.hasConditionalAuthorizerName(conditionalAuthorizerName) { + // Note: We don't short-circuit here, as we want to see all decisions "until the end", such that we can fail closed stronger if needed. + unionMap.errs = append(unionMap.errs, fmt.Errorf("duplicate conditionalAuthorizerName %q", conditionalAuthorizerName)) + } + // Once we've seen an unconditional Allow or Deny somewhere in the chain, we can stop accepting + // other decisions, as they won't ever apply. + if d.ContainsUnconditionalAllowOrDeny() { + unionMap.containsUnconditionalAllowOrDeny = true + } + unionMap.inner = append(unionMap.inner, namedConditionsAwareDecision{conditionalAuthorizerName: conditionalAuthorizerName, d: d}) + // Memorize the possible decisions. This is sound, as ConditionsAwareDecisions are immutable after construction. + if unionMap.subDecisionsPossibleDecisions == nil { + unionMap.subDecisionsPossibleDecisions = sets.New[Decision]() + } + unionMap.subDecisionsPossibleDecisions.Insert(d.PossibleDecisions().UnsortedList()...) +} + +func (unionMap *ConditionsAwareDecisionUnion) hasConditionalAuthorizerName(conditionalAuthorizerName string) bool { + return slices.ContainsFunc(unionMap.inner, func(nd namedConditionsAwareDecision) bool { + return nd.conditionalAuthorizerName == conditionalAuthorizerName + }) +} + +// FailureDecision returns either a Deny or NoOpinion decision that the caller can +// use if the caller encounters an unrecoverable error while processing a +// ConditionsAwareDecision. If this decision is or could evaluate to Deny +// this function returns DecisionDeny to the caller, in order to fail closed +// as a conservative approximation. Otherwise, NoOpinion is returned. +// FailureDecision is not thread-safe. +func (unionMap *ConditionsAwareDecisionUnion) FailureDecision() Decision { + if unionMap.PossibleDecisions().Has(DecisionDeny) { + return DecisionDeny + } + return DecisionNoOpinion +} + +// ContainsUnconditionalAllowOrDeny returns true whether there union contains at least one +// Allow or Deny decision within the unioned decisions. +// ContainsUnconditionalAllowOrDeny is not thread-safe. +func (unionMap *ConditionsAwareDecisionUnion) ContainsUnconditionalAllowOrDeny() bool { + return unionMap.containsUnconditionalAllowOrDeny +} + +// PossibleDecisions details what are the possible decision outcomes of this +// ConditionsAwareDecisionUnion. The return value is a subset of {Allow, Deny, NoOpinion}, +// but never the empty set. +// PossibleDecisions is not thread-safe. +func (unionMap *ConditionsAwareDecisionUnion) PossibleDecisions() sets.Set[Decision] { + // Default response is NoOpinion. + // Always return a fresh set, don't allow the caller to mutate any internal state. + possibleDecisions := sets.New(DecisionNoOpinion) + // Add the memorized possible decisions after adding them. + if unionMap.subDecisionsPossibleDecisions != nil { + possibleDecisions.Insert(unionMap.subDecisionsPossibleDecisions.UnsortedList()...) + } + // When there is an Allow or Deny leaf somewhere, the default response NoOpinion won't ever be returned + if unionMap.ContainsUnconditionalAllowOrDeny() { + possibleDecisions.Delete(DecisionNoOpinion) + } + return possibleDecisions +} + +// ConditionsAwareDecisionUnion unions some amount of decisions together into a tree structure, +// where Allow/Deny/NoOpinion/ConditionsMap decisions are leafs, and Union decisions are internal +// tree nodes. +// ToDecision is not thread-safe. +func (unionMap *ConditionsAwareDecisionUnion) ToDecision() ConditionsAwareDecision { + // If we encountered any errors (e.g. duplicate authorizernames) while building the slice, + // fail closed. + if len(unionMap.errs) != 0 { + err := utilerrors.NewAggregate(unionMap.errs) + return ConditionsAwareDecisionFromParts(unionMap.FailureDecision(), "failed closed", err) + } + + // If we only have one possible outcome, consolidate to an unconditional decision without evaluation. + if possibleDecisions := unionMap.PossibleDecisions(); possibleDecisions.Len() == 1 { + onlyPossibleDecision := possibleDecisions.UnsortedList()[0] + // Collect the certainly deciding decisions' reasons and errors. When the only possible + // decision is Allow or Deny, we in principle know it's the last decision added, but + // keep the logic generic and aligned with NoOpinion, for which we aggregate together + // the reasons and errors for all of the same-type decisions. + var aggregateReasons []string + var aggregateErrors []error + for _, namedDecision := range unionMap.inner { + reasons, errs := collectReasonsAndErrors([]string{namedDecision.conditionalAuthorizerName}, namedDecision.d, onlyPossibleDecision) + aggregateReasons = append(aggregateReasons, reasons...) + aggregateErrors = append(aggregateErrors, errs...) + } + + switch onlyPossibleDecision { + case DecisionDeny: + // For example, a union of decisions with possible outcomes "[Deny, NoOpinion], [NoOpinion], [Deny], [Allow]" yields possible outcome [Deny] always, + // regardless of how the ConditionsMap in the beginning evaluates. + return ConditionsAwareDecisionDeny(strings.Join(aggregateReasons, ", "), utilerrors.NewAggregate(aggregateErrors)) + case DecisionNoOpinion: + // This happens for instance when called on the empty slice, then the only possible mode is NoOpinion + // This can only happen if there were only NoOpinions in the chain, so we can gather them here. TODO: (formally) verify this + return ConditionsAwareDecisionNoOpinion(strings.Join(aggregateReasons, ", "), utilerrors.NewAggregate(aggregateErrors)) + case DecisionAllow: + // For example, a union of decisions with possible outcomes "[Allow, NoOpinion], [NoOpinion], [Allow], [Deny]" yields possible outcome [Allow] always, + // regardless of how the ConditionsMap in the beginning evaluates. + return ConditionsAwareDecisionAllow(strings.Join(aggregateReasons, ", "), utilerrors.NewAggregate(aggregateErrors)) + default: + return ConditionsAwareDecisionDeny("failed closed", errors.New("should be unreachable: ConditionsAwareDecision should only contain Allow/Deny/NoOpinion")) + } + } + + return ConditionsAwareDecision{ + decisionType: conditionsAwareDecisionTypeUnion, + union: ConditionsAwareDecisionUnion{ + // ensure ConditionsAwareDecision immutability by not sharing any references between the builder and the result + inner: slices.Clone(unionMap.inner), + containsUnconditionalAllowOrDeny: unionMap.containsUnconditionalAllowOrDeny, + subDecisionsPossibleDecisions: unionMap.subDecisionsPossibleDecisions.Clone(), + }, + } +} + +func collectReasonsAndErrors(authorizerNamePrefix []string, condAwareDecision ConditionsAwareDecision, unconditionalDecisionToCollect Decision) (aggregateReasons []string, aggregateErrors []error) { + if (unconditionalDecisionToCollect == DecisionAllow && condAwareDecision.IsAllow()) || + (unconditionalDecisionToCollect == DecisionNoOpinion && condAwareDecision.IsNoOpinion()) || + (unconditionalDecisionToCollect == DecisionDeny && condAwareDecision.IsDeny()) { + if reason := condAwareDecision.Reason(); len(reason) != 0 { + aggregateReasons = append(aggregateReasons, fmt.Sprintf("%s: {%s}", strings.Join(authorizerNamePrefix, ": "), reason)) + } + if err := condAwareDecision.Error(); err != nil { + aggregateErrors = append(aggregateErrors, fmt.Errorf("%s: %w", strings.Join(authorizerNamePrefix, ": "), err)) + } + return + } + if condAwareDecision.IsUnion() { + for authorizerName, subDecision := range condAwareDecision.UnionedDecisions() { + reasons, errs := collectReasonsAndErrors(slices.Concat(authorizerNamePrefix, []string{authorizerName}), subDecision, unconditionalDecisionToCollect) + aggregateReasons = append(aggregateReasons, reasons...) + aggregateErrors = append(aggregateErrors, errs...) + } + return + } + return +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/evaluate.go b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/evaluate.go new file mode 100644 index 000000000..d8371f421 --- /dev/null +++ b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/evaluate.go @@ -0,0 +1,280 @@ +/* +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 authorizer + +import ( + "context" + "errors" + "fmt" + "iter" + + utilerrors "k8s.io/apimachinery/pkg/util/errors" +) + +// partialConditionEvaluationResultType is a small enum for the type of ConditionEvaluationResult +type partialConditionEvaluationResultType int + +const ( + partialConditionEvaluationResultTypeUnevaluatable partialConditionEvaluationResultType = iota + partialConditionEvaluationResultTypeTrue + partialConditionEvaluationResultTypeFalse + partialConditionEvaluationResultTypeError +) + +// ConditionEvaluationResult is an enum type with four variants: +// - true and false: Evaluation was successful, and evaluated to this value +// - error: The condition could be evaluated, but errored during eval. +// - unevaluatable: The condition cannot readily be evaluated. This is the struct zero value. +type ConditionEvaluationResult struct { + resultType partialConditionEvaluationResultType + err error +} + +// ConditionEvaluationResultBoolean constructs an evaluation result with a boolean value. +func ConditionEvaluationResultBoolean(evalResult bool) ConditionEvaluationResult { + if evalResult { + return ConditionEvaluationResult{resultType: partialConditionEvaluationResultTypeTrue} + } + return ConditionEvaluationResult{resultType: partialConditionEvaluationResultTypeFalse} +} + +// ConditionEvaluationResultError indicates that the condition could be evaluated, but failed. +func ConditionEvaluationResultError(err error) ConditionEvaluationResult { + if err == nil { + return ConditionEvaluationResult{ + resultType: partialConditionEvaluationResultTypeError, + err: errors.New("unspecified evaluation error"), + } + } + return ConditionEvaluationResult{ + resultType: partialConditionEvaluationResultTypeError, + err: err, + } +} + +// ConditionsEvaluationResultUnevaluatable indicates direct conditions evaluation is not possible. +func ConditionsEvaluationResultUnevaluatable() ConditionEvaluationResult { + return ConditionEvaluationResult{ + resultType: partialConditionEvaluationResultTypeUnevaluatable, // == 0 (which matches the zero value of the struct) + } +} + +// IsTrue indicates that the conditions evaluation was successful, and evaluated to true, which means it influences the ConditionsMap decision. +func (r ConditionEvaluationResult) IsTrue() bool { + return r.resultType == partialConditionEvaluationResultTypeTrue +} + +// IsFalse indicates that the conditions evaluation was successful, but evaluated to false, and it not thus taken into account. +func (r ConditionEvaluationResult) IsFalse() bool { + return r.resultType == partialConditionEvaluationResultTypeFalse +} + +// IsError indicates whether conditions evaluation failed. +func (r ConditionEvaluationResult) IsError() bool { + return r.resultType == partialConditionEvaluationResultTypeError +} + +// Error returns the evaluation error, if any. +func (r ConditionEvaluationResult) Error() error { return r.err } + +// IsUnevaluatable is true whenever none of the other variants is, that is, the zero value. +func (r ConditionEvaluationResult) IsUnevaluatable() bool { + return r.resultType == partialConditionEvaluationResultTypeUnevaluatable +} + +// Evaluate evaluates the ConditionsMap primarily using the Conditions' own Evaluate() function, +// and secondarily using evaluateConditionFn, if set. The first matching (true) condition +// short-circuits the process, in order for the evaluation to be as efficient as possible. +func (c ConditionsMap) Evaluate(ctx context.Context, data ConditionsData, evaluateConditionFn EvaluateConditionFunc) (Decision, string, error) { + // This is a translation between the generic, private function, and the interface we want to expose to callers. + return partiallyEvaluateConditionsMapInternal(ctx, c, data, func(ctx context.Context, cond Condition, condData ConditionsData) ConditionEvaluationResult { + // Because we never return "unevaluatable", the returned ConditionsAwareDecision is always one of Allow/Deny/NoOpinion, and thus can we split it into unconditionalParts + applied, err := evaluateConditionFn(ctx, cond, condData) + if err != nil { + return ConditionEvaluationResultError(err) + } + return ConditionEvaluationResultBoolean(applied) + }).unconditionalParts() +} + +// partiallyEvaluateConditionsMapInternal evaluates the ConditionsMap primarily using the Conditions' own Evaluate() function, +// and secondarily using evaluateFunc, if set. If evaluateFunc is non-nil and never returns +// ConditionsEvaluationResultUnevaluatable, the returned decision is guaranteed to be Allow/Deny/NoOpinion. +// However, this method can also be used to evaluate a subset of the conditions (e.g. for builtin +// conditions evaluators that support a certain conditions type), returning ConditionsEvaluationResultUnevaluatable +// for conditions that the evaluator does not recognize. In the latter case, a partially evaluated, +// ConditionsMap might be returned. +func partiallyEvaluateConditionsMapInternal(ctx context.Context, c ConditionsMap, data ConditionsData, evaluateConditionFn MaybeEvaluateConditionFunc) ConditionsAwareDecision { + evalCond := func(cond Condition) ConditionEvaluationResult { + // First, try to use the condition's own evaluate function. + // Fallback to evaluateConditionFn if set and unevaluatable + result := cond.Evaluate(ctx, data) + if result.IsUnevaluatable() && evaluateConditionFn != nil { + return evaluateConditionFn(ctx, cond, data) + } + return result + } + + // General logic: Deny > NoOpinion > Allow. Within a set of same-effect conditions true > error > unevaluatable > false. + + if len(c.denyConditions) != 0 { + appliedReason, errored, unevaluated := conditionsToAppliedErroredUnevaluated( + c.DenyConditions(), evalCond, "Deny", "denied the request") + + if len(appliedReason) != 0 { + // No errors are returned here, as that would turn this into a 500 instead of 403 in the WithAuthorization HTTP filter + // TODO(luxas): We might want to change the WithAuthorization logic such that it becomes possible for an authorizer to + // surface non-critical errors also in the precence of denies. + return ConditionsAwareDecisionDeny(appliedReason, nil) + } + if len(errored) != 0 { + return ConditionsAwareDecisionDeny("one or more conditional evaluation errors occurred", utilerrors.NewAggregate(errored)) + } + if len(unevaluated) != 0 { + return ConditionsAwareDecisionConditionsMap(unevaluated, c.noOpinionConditions, c.allowConditions) + } + } + + // If we got here, all Deny conditions could be evaluated, and evaluated to false, nil + + if len(c.noOpinionConditions) != 0 { + appliedReason, errored, unevaluated := conditionsToAppliedErroredUnevaluated( + c.NoOpinionConditions(), evalCond, "NoOpinion", "evaluated to NoOpinion") + + if len(appliedReason) != 0 { + // No errors are returned here, as that would turn this into a 500 instead of 403 in the WithAuthorization HTTP filter + return ConditionsAwareDecisionNoOpinion(appliedReason, nil) + } + if len(errored) != 0 { + return ConditionsAwareDecisionNoOpinion("one or more conditional evaluation errors occurred", utilerrors.NewAggregate(errored)) + } + if len(unevaluated) != 0 { + // Note: If len(c.allowConditions) == 0, ConditionsAwareDecisionConditionsMap will fold this into an unconditional NoOpinion. + return ConditionsAwareDecisionConditionsMap(nil, unevaluated, c.allowConditions) + } + } + + // If we got here, all Deny and NoOpinion conditions could be evaluated, and evaluated to false, nil + + if len(c.allowConditions) != 0 { + appliedReason, errored, unevaluated := conditionsToAppliedErroredUnevaluated( + c.AllowConditions(), evalCond, "Allow", "allowed the request") + + if len(appliedReason) != 0 { + // Errors could technically be returned with an Allow (and be logged), but no errors are returned for + // the short-circuit true case, as the error list might be incomplete. + return ConditionsAwareDecisionAllow(appliedReason, nil) + } + if len(errored) != 0 { + return ConditionsAwareDecisionNoOpinion("one or more conditional evaluation errors occurred", utilerrors.NewAggregate(errored)) + } + if len(unevaluated) != 0 { + return ConditionsAwareDecisionConditionsMap(nil, nil, unevaluated) + } + } + + // All conditions evaluated to false. This means a simple default NoOpinion. + return ConditionsAwareDecisionNoOpinion("no conditions matched", nil) +} + +// Note: the signature is string, error, []Condition, as that is the order in which the return values should be processed +// The first true short-circuits the evaluation with a nil error, even though some potentially happened before the first +// true evaluation, as the errors list in that case wouldn't necessarily be comprehensive. +func conditionsToAppliedErroredUnevaluated(conditions iter.Seq[Condition], evalCond func(cond Condition) ConditionEvaluationResult, effect, appliedDescription string) (string, []error, []Condition) { + var errs []error + var unevaluatedConditions []Condition + for cond := range conditions { + id := cond.GetID() + evalResult := evalCond(cond) + switch { + case evalResult.IsTrue(): + reason := fmt.Sprintf("condition %q %s", id, appliedDescription) + if desc := cond.GetDescription(); len(desc) != 0 { + reason += fmt.Sprintf(" with description %q", desc) + } + // Note: nil is returned for errors here as the list is not comprehensive in the short-circuit case. + return reason, nil, nil + case evalResult.IsFalse(): + continue + case evalResult.IsUnevaluatable(): + unevaluatedConditions = append(unevaluatedConditions, cond) + continue + case evalResult.IsError(): + errs = append(errs, fmt.Errorf("condition %q with effect=%s evaluated to an error: %w", id, effect, evalResult.Error())) + continue + default: + errs = append(errs, fmt.Errorf("condition %q with effect=%s evaluated to an error: unknown evaluation result %v", id, effect, evalResult)) + continue + } + } + return "", errs, unevaluatedConditions +} + +// PartiallyEvaluateConditionsAwareDecision evaluates the ConditionsAwareDecision primarily using any conditions' own Evaluate() function, +// and secondarily/optionally using evaluateConditionFn, if set. If evaluateConditionFn is non-nil and never returns +// ConditionsEvaluationResultUnevaluatable, the returned decision is guaranteed to be Allow/Deny/NoOpinion. +// However, this method can also be used to evaluate a subset of the conditions (e.g. for builtin +// conditions evaluators that only support a certain conditions type), returning ConditionsEvaluationResultUnevaluatable +// for conditions that the evaluator does not recognize. In the latter case, a partially evaluated ConditionsAwareDecision is returned. +// When evaluating a ConditionsMap, only the first matching (true) condition short-circuits the process, +// in order for the evaluation to be as efficient as possible. +func PartiallyEvaluateConditionsAwareDecision(ctx context.Context, unevaluatedDecision ConditionsAwareDecision, data ConditionsData, evaluateConditionFn MaybeEvaluateConditionFunc) ConditionsAwareDecision { + switch { + case unevaluatedDecision.IsConditionsMap(): + // Try to evaluate or refine the leaf ConditionsMap using the builtin evaluator. + return partiallyEvaluateConditionsMapInternal(ctx, unevaluatedDecision.ConditionsMap(), data, evaluateConditionFn) + case unevaluatedDecision.IsUnion(): + var newDecisionChain ConditionsAwareDecisionUnion + // Recursively walk through the decision DAG in a depth-first manner. + // The logic in this function should be the same as in the union authorizer's ConditionsAwareAuthorize. + + collectTailAfterConditionalDecision := false + for authorizerName, unevaluatedSubDecision := range unevaluatedDecision.UnionedDecisions() { + // If collectAndShortcircuitOnly == true, a conditional decision that couldn't + // be evaluated to Allow/Deny/NoOpinion was encountered during a previous + // loop iteration. Then all latter decisions stay unevaluated. + if collectTailAfterConditionalDecision { + newDecisionChain.Add(authorizerName, unevaluatedSubDecision) + continue + } + + // When !collectTailAfterConditionalDecision: All decisions so far in newDecisionChain are NoOpinions, + // as if there existed a previous decision of type ConditionsMap or Union, collectTailAfterConditionalDecision == true, + // and if there existed an Allow or Deny earlier, the function would have returned. + + // Try evaluating or refining the leaf ConditionsMaps in this tree of decisions. + possiblyEvaluatedSubDecision := PartiallyEvaluateConditionsAwareDecision(ctx, unevaluatedSubDecision, data, evaluateConditionFn) + newDecisionChain.Add(authorizerName, possiblyEvaluatedSubDecision) + + // If there is any Allow/Deny decision leaf, no need to walk the chain further. + if possiblyEvaluatedSubDecision.ContainsUnconditionalAllowOrDeny() { + return newDecisionChain.ToDecision() + } + + // Stop partially evaluating after encountering a conditional decision + if !possiblyEvaluatedSubDecision.IsUnconditional() { + collectTailAfterConditionalDecision = true + } + } + // If we reached here, all leaf decisions were either of NoOpinion or ConditionsMap type. + // If all decisions were NoOpinions, the constructor folds into a single NoOpinion decision. + return newDecisionChain.ToDecision() + default: + // No simplification possible + return unevaluatedDecision + } +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go index 09000a1a5..a4179e515 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go @@ -18,16 +18,20 @@ package authorizer import ( "context" + "errors" "fmt" "net/http" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apiserver/pkg/authentication/user" ) -// Attributes is an interface used by an Authorizer to get information about a request -// that is used to make an authorization decision. +// Attributes is an interface used by an Authorizer to get information about a +// request's metadata, that is used to compute an unconditional or conditional +// authorization decision. type Attributes interface { // GetUser returns the user.Info object to authorize GetUser() user.Info @@ -77,19 +81,69 @@ type Attributes interface { GetLabelSelector() (labels.Requirements, error) } +// UnconditionalAuthorizer is a downscoped variant of Authorizer, which only gives the +// caller the ability to call the conditions-unaware Authorize method. +type UnconditionalAuthorizer interface { + Authorize(ctx context.Context, a Attributes) (authorized Decision, reason string, err error) +} + // Authorizer makes an authorization decision based on information gained by making -// zero or more calls to methods of the Attributes interface. It returns nil when an action is -// authorized, otherwise it returns an error. +// zero or more calls to methods of the Attributes interface. It might return +// an error together with any decision. It is up to the caller to decide whether +// that error is critical or not. +// +// The kube-apiserver WithAuthorization filter ignores errors when the decision is +// Allow, but returns response code 500 if an error is returned with a Deny or +// NoOpinion (instead of the usual 403). +// +// Any authorizer must implement this interface, but when passing a handle to an +// authorizer, one might choose whether to pass the Authorizer or smaller UnconditionalAuthorizer +// interface, depending on whether the receiver should be able to perform conditional +// authorization or not. type Authorizer interface { - Authorize(ctx context.Context, a Attributes) (authorized Decision, reason string, err error) + UnconditionalAuthorizer + + // ConditionsAwareAuthorize returns an unconditional, conditional, or unioned + // decision, where the error and reason is part of the Decision struct. + // + // An authorizer who is not conditions-aware MUST implement this function as + // "return authorizer.ConditionsAwareDecisionFromParts(self.Authorize(ctx, a))", + // such that conditions-aware callers to this authorizer get the same output + // as if they called Authorize. Callers are only expected to call one of + // Authorize or ConditionsAwareAuthorize, not both. + ConditionsAwareAuthorize(ctx context.Context, a Attributes) ConditionsAwareDecision + + // EvaluateConditions evaluates a conditional or unioned ConditionsAwareDecision against previously-unknown data. + // + // An authorizer who does not support conditions should fail closed and + // return authorizer.DecisionDeny, "", authorizer.ErrorConditionEvaluationNotSupported + // + // The context should only be used for timeouts/cancellation/tracing, and should not influence the + // evaluation outcome. Only the given decision and data may infuence the outcome. data must be non-nil. + EvaluateConditions(ctx context.Context, decision ConditionsAwareDecision, data ConditionsData) (authorized Decision, reason string, err error) } +// ErrorConditionEvaluationNotSupported is returned by authorizer implementations +// that do not support condition evaluation. +var ErrorConditionEvaluationNotSupported = errors.New("condition evaluation not supported") + +// AuthorizerFunc implements Authorizer +var _ Authorizer = AuthorizerFunc(nil) + type AuthorizerFunc func(ctx context.Context, a Attributes) (Decision, string, error) func (f AuthorizerFunc) Authorize(ctx context.Context, a Attributes) (Decision, string, error) { return f(ctx, a) } +func (f AuthorizerFunc) ConditionsAwareAuthorize(ctx context.Context, a Attributes) ConditionsAwareDecision { + return ConditionsAwareDecisionFromParts(f.Authorize(ctx, a)) +} + +func (f AuthorizerFunc) EvaluateConditions(_ context.Context, _ ConditionsAwareDecision, _ ConditionsData) (Decision, string, error) { + return DecisionDeny, "", ErrorConditionEvaluationNotSupported +} + // RuleResolver provides a mechanism for resolving the list of rules that apply to a given user within a namespace. type RuleResolver interface { // RulesFor get the list of cluster wide rules, the list of rules in the specific namespace, incomplete status and errors. @@ -172,6 +226,8 @@ func (a AttributesRecord) GetLabelSelector() (labels.Requirements, error) { return a.LabelSelectorRequirements, a.LabelSelectorParsingErr } +// Decision represents an final, unconditional authorization decision. +// The zero value (0) of Decision is DecisionDeny. type Decision int const ( @@ -180,7 +236,8 @@ const ( // DecisionAllow means that an authorizer decided to allow the action. DecisionAllow // DecisionNoOpinion means that an authorizer has no opinion on whether - // to allow or deny an action. + // to allow or deny an action. If there are multiple unioned authorizers, + // this means that the request can thus get allowed by some later authorizer. DecisionNoOpinion ) @@ -196,3 +253,91 @@ func (d Decision) String() string { return fmt.Sprintf("Unknown (%d)", int(d)) } } + +// Condition represents one authorization condition that is part of a ConditionsMap. +// The effect of a condition is defined by whether it is part of the Deny/NoOpinion/Allow +// conditions list in the ConditionsMap. +// +// A Condition must be immutable and thread-safe. +type Condition interface { + // GetID uniquely identifies this condition within the scope of the authorizer + // that authored it. Validated as a Kubernetes label key. + // Any domain of form *.k8s.io or *.kubernetes.io is reserved for Kubernetes use. + // Required. + GetID() string + + // GetType describes the type of the condition, if there are multiple possibilities. + // Should be formatted as a Kubernetes label key. + // Any domain of form *.k8s.io or *.kubernetes.io is reserved for Kubernetes use. + // Optional. Can be omitted if the authorizer already knows how to evaluate the condition. + GetType() string + + // GetCondition returns a string encoding of the condition to be evaluated. + // It is a pure, deterministic function from ConditionsData to a boolean (or error). + // Might or might not be human-readable. + // Optional, if the ID alone is enough for the authorizer to know how to evaluate the condition. + GetCondition() string + + // GetDescription is an optional human-friendly description that can be shown + // as an error message or for debugging. Optional. + GetDescription() string + + // Evaluate evaluates the condition to a boolean, returns an error, or returns "unevaluatable". + // If an authorizer already has a pre-compiled condition, this avoids one serialization roundtrip, + // with potentially expensive deserialization/parsing. However, if the condition underwent a + // serialize/deserialize roundtrip (e.g. when the caller is an aggregated API server), the authorizer + // might have to evaluate the condition from its serialized form using evaluateFunc in + // ConditionsMap.Evaluate. + // Evaluate must be safe to call repeatedly and concurrently. + // + // The context should only be used for timeouts/cancellation/tracing, and should not influence the + // evaluation outcome. Only the condition itself and data can infuence the outcome. + Evaluate(ctx context.Context, data ConditionsData) ConditionEvaluationResult +} + +// EvaluateConditionFunc is a function that is able to concretely evaluate a condition to a boolean or error. +type EvaluateConditionFunc func(ctx context.Context, condition Condition, data ConditionsData) (bool, error) + +// MaybeEvaluateConditionFunc allows potentially evaluating a condition, returning Unevaluatable if a truth value or error cannot be assigned. +type MaybeEvaluateConditionFunc func(ctx context.Context, condition Condition, data ConditionsData) ConditionEvaluationResult + +// AdmissionOperation represents the admission operation, +// for example CREATE, UPDATE, DELETE. The constants are +// defined in k8s.io/apiserver/pkg/admission, but the +// type is defined here, because this package is more generic +// than the admission package (thus avoiding import cycles) +type AdmissionOperation string + +// ConditionsData represents the data available for conditions +// to evaluate against. This is by design a subset of admission.Attributes. +type ConditionsData interface { + // GetName returns the name of the object as presented in the request. On a CREATE operation, the client + // may omit name and rely on the server to generate the name. If that is the case, this method will return + // the empty string + GetName() string + // GetNamespace is the namespace associated with the request (if any) + GetNamespace() string + // GetResource is the name of the resource being requested. This is not the kind. For example: pods + GetResource() schema.GroupVersionResource + // GetSubresource is the name of the subresource being requested. This is a different resource, scoped to the parent resource, but it may have a different kind. + // For instance, /pods has the resource "pods" and the kind "Pod", while /pods/foo/status has the resource "pods", the sub resource "status", and the kind "Pod" + // (because status operates on pods). The binding resource for a pod though may be /pods/foo/binding, which has resource "pods", subresource "binding", and kind "Binding". + GetSubresource() string + // GetOperation is the operation being performed + GetOperation() AdmissionOperation + // GetOperationOptions is the options for the operation being performed + GetOperationOptions() runtime.Object + // IsDryRun indicates that modifications will definitely not be persisted for this request. This is to prevent + // admission controllers with side effects and a method of reconciliation from being overwhelmed. + // However, a value of false for this does not mean that the modification will be persisted, because it + // could still be rejected by a subsequent validation step. + IsDryRun() bool + // GetObject is the object from the incoming request. Only populated for CREATE and UPDATE requests. + GetObject() runtime.Object + // GetOldObject is the existing object in storage. Only populated for UPDATE and DELETE requests. + GetOldObject() runtime.Object + // GetKind is the type of object being manipulated. For example: Pod + GetKind() schema.GroupVersionKind + // GetUserInfo is information about the requesting user + GetUserInfo() user.Info +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesreflect.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesreflect.go index 36f38b3ed..2ff920bd6 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesreflect.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesreflect.go @@ -19,13 +19,16 @@ package common import ( "encoding/json" "fmt" + "reflect" + "sync" + + "sigs.k8s.io/structured-merge-diff/v6/value" + apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "reflect" - "sigs.k8s.io/structured-merge-diff/v6/value" - "sync" + "k8s.io/apiserver/pkg/cel" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" @@ -105,7 +108,7 @@ func TypedToVal(val interface{}, schema Schema) ref.Val { switch listType { case "map": mapKeys := schema.XListMapKeys() - return &typedMapList{typedList: typedList, escapedKeyProps: escapeKeyProps(mapKeys)} + return &typedMapList{typedList: typedList, keyProps: mapKeys, escapedKeyProps: escapeKeyProps(mapKeys)} case "set": return &typedSetList{typedList: typedList} case "atomic": @@ -151,7 +154,8 @@ func TypedToVal(val interface{}, schema Schema) ref.Val { type typedStruct struct { value reflect.Value // Kind is required to be: reflect.Struct - // propSchema finds the schema to use for a particular map key. + // propSchema finds the schema for a given key. + // The key is an unescaped JSON name, not an escaped CEL identifier. propSchema func(key string) (Schema, bool) } @@ -198,37 +202,46 @@ func (s *typedStruct) Value() interface{} { return s.value.Interface() } -func (s *typedStruct) IsSet(field ref.Val) ref.Val { - v, found := s.lookupField(field) +// IsSet returns true if the field is set. escapedField must be a types.String containing the +// escaped CEL identifier. For example, "__if__" for JSON name "if". +func (s *typedStruct) IsSet(escapedField ref.Val) ref.Val { + v, found := s.lookupField(escapedField) if v != nil && types.IsUnknownOrError(v) { return v } return types.Bool(found) } -func (s *typedStruct) Get(key ref.Val) ref.Val { - v, found := s.lookupField(key) +// Get returns the value of a field. escapedKey must be a types.String containing the +// escaped CEL identifier. For example, "__if__" for JSON name "if". +func (s *typedStruct) Get(escapedKey ref.Val) ref.Val { + v, found := s.lookupField(escapedKey) if !found { - return types.NewErr("no such key: %v", key) + return types.NewErr("no such key: %v", escapedKey) } return v } -func (s *typedStruct) lookupField(key ref.Val) (ref.Val, bool) { - keyStr, ok := key.(types.String) +// lookupField finds a field by name. escapedKey must be a types.String containing the escaped +// CEL identifier of the field name. For example, "__if__" for JSON name "if". +func (s *typedStruct) lookupField(escapedKey ref.Val) (ref.Val, bool) { + escapedKeyStr, ok := escapedKey.(types.String) if !ok { - return types.MaybeNoSuchOverloadErr(key), true + return types.MaybeNoSuchOverloadErr(escapedKey), true + } + unescapedFieldName, ok := cel.Unescape(escapedKeyStr.Value().(string)) + if !ok { + return nil, false } - fieldName := keyStr.Value().(string) cacheEntry := value.TypeReflectEntryOf(s.value.Type()) - fieldCache, ok := cacheEntry.Fields()[fieldName] + fieldCache, ok := cacheEntry.Fields()[unescapedFieldName] if !ok { return nil, false } if e := fieldCache.GetFrom(s.value); !fieldCache.CanOmit(e) { - if propSchema, ok := s.propSchema(fieldName); ok { + if propSchema, ok := s.propSchema(unescapedFieldName); ok { v := TypedToVal(e.Interface(), propSchema) if v == types.NullValue { return nil, false @@ -273,7 +286,7 @@ func (t *typedList) Equal(other ref.Val) ref.Val { if sz != oList.Size() { return types.False } - for i := types.Int(0); i < sz; i++ { + for i := range types.Int(sz) { eq := t.Get(i).Equal(oList.Get(i)) if eq != types.True { return eq // either false or error @@ -287,7 +300,7 @@ func (t *typedList) Type() ref.Type { } func (t *typedList) Value() interface{} { - return t.value + return t.value.Interface() } func (t *typedList) Add(other ref.Val) ref.Val { @@ -295,13 +308,16 @@ func (t *typedList) Add(other ref.Val) ref.Val { if !ok { return types.MaybeNoSuchOverloadErr(other) } - resultValue := t.value + sz := t.value.Len() + otherSz, _ := oList.Size().(types.Int) + elements := make([]ref.Val, 0, sz+int(otherSz)) + for i := range sz { + elements = append(elements, t.Get(types.Int(i))) + } for it := oList.Iterator(); it.HasNext() == types.True; { - next := it.Next().Value() - resultValue = reflect.Append(resultValue, reflect.ValueOf(next)) + elements = append(elements, it.Next()) } - - return &typedList{value: resultValue, itemsSchema: t.itemsSchema} + return types.NewRefValList(types.DefaultTypeAdapter, elements) } func (t *typedList) Contains(val ref.Val) ref.Val { @@ -310,7 +326,7 @@ func (t *typedList) Contains(val ref.Val) ref.Val { } var err ref.Val sz := t.value.Len() - for i := 0; i < sz; i++ { + for i := range sz { elem := TypedToVal(t.value.Index(i).Interface(), t.itemsSchema) cmp := elem.Equal(val) b, ok := cmp.(types.Bool) @@ -342,7 +358,7 @@ func (t *typedList) Get(idx ref.Val) ref.Val { func (t *typedList) Iterator() traits.Iterator { elements := make([]ref.Val, t.value.Len()) sz := t.value.Len() - for i := 0; i < sz; i++ { + for i := range sz { elements[i] = TypedToVal(t.value.Index(i).Interface(), t.itemsSchema) } return &sliceIter{typedList: t, elements: elements} @@ -373,6 +389,10 @@ func (it *sliceIter) Next() ref.Val { type typedMapList struct { typedList + // keyProps are unescaped JSON property names + keyProps []string + + // escapedKeyProps are escaped CEL identifiers escapedKeyProps []string sync.Once // for lazy load of mapOfList since it is only needed if Equals is called @@ -383,7 +403,7 @@ func (t *typedMapList) getMap() map[interface{}]interface{} { t.Do(func() { sz := t.value.Len() t.mapOfList = make(map[interface{}]interface{}, sz) - for i := types.Int(0); i < types.Int(sz); i++ { + for i := range types.Int(sz) { v := t.Get(i) e := reflect.ValueOf(v.Value()) t.mapOfList[t.toMapKey(e)] = e.Interface() @@ -401,32 +421,50 @@ func (t *typedMapList) toMapKey(element reflect.Value) interface{} { } cacheEntry := value.TypeReflectEntryOf(element.Type()) var fieldEntries []*value.FieldCacheEntry - for i := 0; i < len(t.escapedKeyProps); i++ { - if ce, ok := cacheEntry.Fields()[t.escapedKeyProps[i]]; !ok { + for i := range len(t.keyProps) { + if ce, ok := cacheEntry.Fields()[t.keyProps[i]]; !ok { // Fields() is keyed by unescaped JSON property names. return types.NewErr("unexpected data format for element of array with x-kubernetes-list-type=map: %T", element) } else { fieldEntries = append(fieldEntries, ce) } } + getKeyValue := func(fieldEntry *value.FieldCacheEntry) interface{} { + v := fieldEntry.GetFrom(element) + for v.Kind() == reflect.Pointer { + if v.IsNil() { + return nil + } + v = v.Elem() + } + raw := v.Interface() + if raw != nil && !reflect.TypeOf(raw).Comparable() { + // %#v includes type information and quotes strings, so the + // serialized form cannot collide with a comparable raw value. + return fmt.Sprintf("%#v", raw) + } + return raw + } + // Arrays are comparable in go and may be used as map keys, but maps and slices are not. // So we can special case small numbers of key props as arrays and fall back to serialization // for larger numbers of key props if len(fieldEntries) == 1 { - return fieldEntries[0].GetFrom(element).Interface() + return getKeyValue(fieldEntries[0]) } if len(fieldEntries) == 2 { - return [2]interface{}{fieldEntries[0].GetFrom(element).Interface(), fieldEntries[1].GetFrom(element).Interface()} + return [2]interface{}{getKeyValue(fieldEntries[0]), getKeyValue(fieldEntries[1])} } if len(fieldEntries) == 3 { - return [3]interface{}{fieldEntries[0].GetFrom(element).Interface(), fieldEntries[1].GetFrom(element).Interface(), fieldEntries[3].GetFrom(element).Interface()} + return [3]interface{}{getKeyValue(fieldEntries[0]), getKeyValue(fieldEntries[1]), getKeyValue(fieldEntries[2])} } key := make([]interface{}, len(fieldEntries)) for i := range fieldEntries { - key[i] = fieldEntries[i].GetFrom(element).Interface() + key[i] = getKeyValue(fieldEntries[i]) } - return fmt.Sprintf("%v", key) + // Serialize to a string for more than 3 keys. %#v quotes strings. + return fmt.Sprintf("%#v", key) } // Equal on a map list ignores list element order. @@ -440,6 +478,7 @@ func (t *typedMapList) Equal(other ref.Val) ref.Val { return types.False } tMap := t.getMap() + seen := make(map[interface{}]struct{}, len(tMap)) for it := oMapList.Iterator(); it.HasNext() == types.True; { v := it.Next() k := t.toMapKey(reflect.ValueOf(v.Value())) @@ -451,44 +490,150 @@ func (t *typedMapList) Equal(other ref.Val) ref.Val { if eq != types.True { return eq // either false or error } + seen[k] = struct{}{} } - return types.True + return types.Bool(len(seen) == len(tMap)) } // Add for a map list `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values // are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with // non-intersecting keys are appended, retaining their partial order. func (t *typedMapList) Add(other ref.Val) ref.Val { - sliceType := t.value.Type() - elementType := sliceType.Elem() oMapList, ok := other.(traits.Lister) if !ok { return types.MaybeNoSuchOverloadErr(other) } sz := t.value.Len() - elements := reflect.MakeSlice(sliceType, sz, sz) - keyToIdx := map[interface{}]int{} - for i := 0; i < sz; i++ { - e := t.Get(types.Int(i)).Value() - re := reflect.ValueOf(e) - k := t.toMapKey(re) - keyToIdx[k] = i - elements.Index(i).Set(re.Convert(elementType)) - } - for it := oMapList.Iterator(); it.HasNext() == types.True; { - e := it.Next() - re := reflect.ValueOf(e.Value()) - k := t.toMapKey(re) + elements := make([]ref.Val, sz) + for i := range sz { + elements[i] = t.Get(types.Int(i)) + } + return addToMapList(elements, oMapList, t.escapedKeyProps) +} + +// addToMapList merges the elements of other into the given map list elements +// according to x-kubernetes-list-type=map semantics: elements of other with +// intersecting keys overwrite the matching entries of elements in place, and +// elements with non-intersecting keys are appended. elements may be mutated in +// place and may be appended to, so callers must not retain or reuse elements +// after the call. +// +// escapedKeyProps must contain the escaped CEL identifiers keys. +func addToMapList(elements []ref.Val, other traits.Lister, escapedKeyProps []string) ref.Val { + keyToIdx := make(map[interface{}]int, len(elements)) + for i, e := range elements { + keyToIdx[refValMapKey(e, escapedKeyProps)] = i + } + for it := other.Iterator(); it.HasNext() == types.True; { + v := it.Next() + k := refValMapKey(v, escapedKeyProps) if overwritePosition, ok := keyToIdx[k]; ok { - elements.Index(overwritePosition).Set(re) + elements[overwritePosition] = v } else { - elements = reflect.Append(elements, re.Convert(elementType)) + elements = append(elements, v) } } - return &typedMapList{ - typedList: typedList{value: elements, itemsSchema: t.itemsSchema}, - escapedKeyProps: t.escapedKeyProps, + return &refValMapList{ + Lister: types.NewRefValList(types.DefaultTypeAdapter, elements), + escapedKeyProps: escapedKeyProps, + } +} + +// refValMapKey returns a valid golang map key for the given element of a map list. +// escapedKeyProps must contain the escaped CEL identifiers of the keys. +func refValMapKey(element ref.Val, escapedKeyProps []string) interface{} { + get := func(escapedProp string) interface{} { + key := types.String(escapedProp) + var v ref.Val + var found bool + switch e := element.(type) { + case traits.Mapper: + v, found = e.Find(key) + case traits.Indexer: + if tester, ok := element.(traits.FieldTester); ok { + found = tester.IsSet(key) == types.True + } + if found { + v = e.Get(key) + } + } + if !found || v == nil || types.IsUnknownOrError(v) { + return nil + } + raw := v.Value() + if raw != nil && !reflect.TypeOf(raw).Comparable() { + // %#v includes type information and quotes strings, so the + // serialized form cannot collide with a comparable raw value. + return fmt.Sprintf("%#v", raw) + } + return raw + } + + if len(escapedKeyProps) == 1 { + return get(escapedKeyProps[0]) + } + if len(escapedKeyProps) == 2 { + return [2]interface{}{get(escapedKeyProps[0]), get(escapedKeyProps[1])} + } + if len(escapedKeyProps) == 3 { + return [3]interface{}{get(escapedKeyProps[0]), get(escapedKeyProps[1]), get(escapedKeyProps[2])} + } + + key := make([]interface{}, len(escapedKeyProps)) + for i, kf := range escapedKeyProps { + key[i] = get(kf) + } + // Serialize to a string for more than 3 keys. %#v quotes strings. + return fmt.Sprintf("%#v", key) +} + +type refValMapList struct { + traits.Lister + escapedKeyProps []string +} + +func (l *refValMapList) Add(other ref.Val) ref.Val { + oMapList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz, _ := l.Size().(types.Int) + elements := make([]ref.Val, int(sz)) + for i := range types.Int(sz) { + elements[i] = l.Get(i) + } + return addToMapList(elements, oMapList, l.escapedKeyProps) +} + +func (l *refValMapList) Equal(other ref.Val) ref.Val { + oMapList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz, _ := l.Size().(types.Int) + if sz != oMapList.Size() { + return types.False + } + keyToElement := make(map[interface{}]ref.Val, int(sz)) + for i := range types.Int(sz) { + e := l.Get(i) + keyToElement[refValMapKey(e, l.escapedKeyProps)] = e + } + seen := make(map[interface{}]struct{}, int(sz)) + for it := oMapList.Iterator(); it.HasNext() == types.True; { + v := it.Next() + k := refValMapKey(v, l.escapedKeyProps) + e, ok := keyToElement[k] + if !ok { + return types.False + } + eq := e.Equal(v) + if eq != types.True { + return eq + } + seen[k] = struct{}{} } + return types.Bool(len(seen) == len(keyToElement)) } type typedSetList struct { @@ -496,23 +641,26 @@ type typedSetList struct { sync.Once // for lazy load of setOfList since it is only needed if Equals is called set map[interface{}]struct{} + setErr ref.Val } -func (t *typedSetList) getSet() map[interface{}]struct{} { - // sets are only allowed to contain scalar elements, which are comparable in go, and can safely be used as - // golang map keys +func (t *typedSetList) getSet() (map[interface{}]struct{}, ref.Val) { t.Do(func() { sz := t.value.Len() t.set = make(map[interface{}]struct{}, sz) - for i := types.Int(0); i < types.Int(sz); i++ { - e := t.Get(i).Value() - t.set[e] = struct{}{} + for i := range types.Int(sz) { + k, err := setElementKey(t.Get(i)) + if err != nil { + t.set, t.setErr = nil, err + return + } + t.set[k] = struct{}{} } }) - return t.set + return t.set, t.setErr } -// Equal on a map list ignores list element order. +// Equal on a set list ignores list element order. func (t *typedSetList) Equal(other ref.Val) ref.Val { oSetList, ok := other.(traits.Lister) if !ok { @@ -522,45 +670,130 @@ func (t *typedSetList) Equal(other ref.Val) ref.Val { if sz != oSetList.Size() { return types.False } - tSet := t.getSet() + tSet, err := t.getSet() + if err != nil { + return err + } + seen := make(map[interface{}]struct{}, len(tSet)) for it := oSetList.Iterator(); it.HasNext() == types.True; { - next := it.Next().Value() - _, ok := tSet[next] - if !ok { + k, err := setElementKey(it.Next()) + if err != nil { + return err + } + if _, ok := tSet[k]; !ok { return types.False } + seen[k] = struct{}{} } - return types.True + return types.Bool(len(seen) == len(tSet)) } // Add for a set list `X + Y` performs a union where the array positions of all elements in `X` are preserved and // non-intersecting elements in `Y` are appended, retaining their partial order. func (t *typedSetList) Add(other ref.Val) ref.Val { - setType := t.value.Type() - elementType := setType.Elem() oSetList, ok := other.(traits.Lister) if !ok { return types.MaybeNoSuchOverloadErr(other) } sz := t.value.Len() - elements := reflect.MakeSlice(setType, sz, sz) - for i := 0; i < sz; i++ { - e := t.Get(types.Int(i)).Value() - re := reflect.ValueOf(e) - elements.Index(i).Set(re.Convert(elementType)) + elements := make([]ref.Val, sz) + for i := range sz { + elements[i] = t.Get(types.Int(i)) + } + return addToSetList(elements, oSetList) +} + +// addToSetList unions the elements of other into the given set list elements +// according to x-kubernetes-list-type=set semantics: the array positions of +// elements are preserved, and elements of other that are not already present +// are appended to maintain partial order. elements may be appended to, +// so callers must not retain or reuse elements after the call. +func addToSetList(elements []ref.Val, other traits.Lister) ref.Val { + set := make(map[interface{}]struct{}, len(elements)) + for _, e := range elements { + k, err := setElementKey(e) + if err != nil { + return err + } + set[k] = struct{}{} } - set := t.getSet() - for it := oSetList.Iterator(); it.HasNext() == types.True; { - e := it.Next().Value() - re := reflect.ValueOf(e) - if _, ok := set[e]; !ok { - set[e] = struct{}{} - elements = reflect.Append(elements, re.Convert(elementType)) + for it := other.Iterator(); it.HasNext() == types.True; { + v := it.Next() + k, err := setElementKey(v) + if err != nil { + return err + } + if _, exists := set[k]; !exists { + set[k] = struct{}{} + elements = append(elements, v) } } - return &typedSetList{ - typedList: typedList{value: elements, itemsSchema: t.itemsSchema}, + return &refValSetList{Lister: types.NewRefValList(types.DefaultTypeAdapter, elements)} +} + +// setElementKey returns a valid golang map key for the given element of a set list. +// Set elements are expected to be scalars; if the element is a non-scalar an error is returned. +func setElementKey(element ref.Val) (value interface{}, err ref.Val) { + switch element.(type) { + case traits.Lister, traits.Mapper: + return nil, types.NewErr("listSet operations are only supported on lists of scalar values") + } + raw := element.Value() + if raw != nil && !reflect.TypeOf(raw).Comparable() { + // %#v includes type information and quotes strings, so the + // serialized form cannot collide with a comparable raw value. + return fmt.Sprintf("%#v", raw), nil } + return raw, nil +} + +type refValSetList struct { + traits.Lister +} + +func (l *refValSetList) Add(other ref.Val) ref.Val { + oSetList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz, _ := l.Size().(types.Int) + elements := make([]ref.Val, int(sz)) + for i := range sz { + elements[i] = l.Get(i) + } + return addToSetList(elements, oSetList) +} + +// Equal on a set list ignores list element order. +func (l *refValSetList) Equal(other ref.Val) ref.Val { + oSetList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz, _ := l.Size().(types.Int) + if sz != oSetList.Size() { + return types.False + } + set := make(map[interface{}]struct{}, int(sz)) + for i := range sz { + k, err := setElementKey(l.Get(i)) + if err != nil { + return err + } + set[k] = struct{}{} + } + seen := make(map[interface{}]struct{}, len(set)) + for it := oSetList.Iterator(); it.HasNext() == types.True; { + k, err := setElementKey(it.Next()) + if err != nil { + return err + } + if _, exists := set[k]; !exists { + return types.False + } + seen[k] = struct{}{} + } + return types.Bool(len(seen) == len(set)) } type typedMap struct { @@ -572,7 +805,7 @@ type typedMap struct { func (t *typedMap) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { switch typeDesc.Kind() { case reflect.Map: - return t.value, nil + return t.value.Interface(), nil default: return nil, fmt.Errorf("type conversion error from '%s' to '%s'", t.Type(), typeDesc) } @@ -617,7 +850,7 @@ func (t *typedMap) Type() ref.Type { } func (t *typedMap) Value() interface{} { - return t.value + return t.value.Interface() } func (t *typedMap) Contains(key ref.Val) ref.Val { @@ -641,6 +874,8 @@ func (t *typedMap) Size() ref.Val { return types.Int(t.value.Len()) } +// Find returns the value of the map entry for the given key, if present. The map keys +// are normal strings, not CEL identifiers, and are not escaped. func (t *typedMap) Find(key ref.Val) (ref.Val, bool) { keyStr, ok := key.(types.String) if !ok { diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesschemalesstyped.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesschemalesstyped.go new file mode 100644 index 000000000..73ecdcbc6 --- /dev/null +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesschemalesstyped.go @@ -0,0 +1,565 @@ +/* +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 common + +import ( + "encoding/base64" + "fmt" + "reflect" + + "github.com/google/cel-go/common/types" + "github.com/google/cel-go/common/types/ref" + "github.com/google/cel-go/common/types/traits" + apiequality "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/util/intstr" + "sigs.k8s.io/structured-merge-diff/v6/value" +) + +// SchemalessTypedToVal wraps a Go value as a CEL ref.Val. +// It mimics how the value would look if it were converted to an unstructured +// map using JSON serialization, but avoids the full allocation by lazily +// traversing the value via reflection and structured-merge-diff value package. +// +// It provides full functional equivalence to runtime.DefaultUnstructuredConverter.ToUnstructured. +// Any behavioral difference is a bug. The returned ref.Val utilizes internal caching +// for lazy reflection, which is not thread-safe and must only be used synchronously within a +// single CEL evaluation. +func SchemalessTypedToVal(val interface{}) ref.Val { + if val == nil { + return types.NullValue + } + + // Fast-path: immediately handle primitive types to completely bypass reflect.ValueOf overhead. + switch typedVal := val.(type) { + case bool: + return types.Bool(typedVal) + case string: + return types.String(typedVal) + case int: + return types.Int(typedVal) + case int32: + return types.Int(typedVal) + case int64: + return types.Int(typedVal) + case float32: + return types.Double(typedVal) + case float64: + return types.Double(typedVal) + case []byte: + if typedVal == nil { + return types.NullValue + } + return types.String(base64.StdEncoding.EncodeToString(typedVal)) + case intstr.IntOrString: + switch typedVal.Type { + case intstr.Int: + return types.Int(typedVal.IntVal) + case intstr.String: + return types.String(typedVal.StrVal) + } + } + + v := reflect.ValueOf(val) + if !v.IsValid() { + return types.NewErr("invalid data, got invalid reflect value: %v", v) + } + + switch v.Kind() { + case reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice: + if v.IsNil() { + return types.NullValue + } + } + + cacheEntry := value.TypeReflectEntryOf(v.Type()) + if cacheEntry.CanConvertToUnstructured() { + if !v.CanAddr() { + ptr := reflect.New(v.Type()) + ptr.Elem().Set(v) + v = ptr.Elem() + } + unstr, err := cacheEntry.ToUnstructured(v) + if err != nil { + return types.NewErr("failed to convert to unstructured: %v", err) + } + if unstr == nil { + return types.NullValue + } + return types.DefaultTypeAdapter.NativeToValue(unstr) + } + switch v.Kind() { + case reflect.Pointer: + if v.IsNil() { + return types.NullValue + } + return SchemalessTypedToVal(v.Elem().Interface()) + case reflect.Slice: + if v.Type().Elem().Kind() == reflect.Uint8 { // byte, relection return slice of Uint8 for bytes. + return types.String(base64.StdEncoding.EncodeToString(v.Bytes())) + } + return &reflectSchemalessTypedList{value: v} + case reflect.Map: + return &reflectSchemalessTypedMap{value: v} + case reflect.Struct: + return &reflectSchemalessTypedStruct{value: v} + // Match type aliases to primitives by kind + case reflect.Bool: + return types.Bool(v.Bool()) + case reflect.String: + return types.String(v.String()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return types.Int(v.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + uVal := v.Uint() + if uVal > 9223372036854775807 { // math.MaxInt64 + return types.NewErr("unsigned value %d does not fit into int64 (overflow)", uVal) + } + return types.Int(uVal) + case reflect.Float32, reflect.Float64: + return types.Double(v.Float()) + default: + return types.NewErr("unsupported Go type for CEL: %v", v.Type()) + } +} + +var _ traits.Lister = &reflectSchemalessTypedList{} + +// reflectSchemalessTypedList wraps a Go slice/array as a lazy CEL Lister. +// fieldCache is NOT thread-safe, as CEL-Go's synchronous value evaluation contract +// guarantees that a single wrapped value is only ever accessed by a single goroutine. +type reflectSchemalessTypedList struct { + value reflect.Value + fieldCache []ref.Val +} + +func (l *reflectSchemalessTypedList) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { + switch typeDesc.Kind() { + case reflect.Slice: + return l.value.Interface(), nil + default: + return nil, fmt.Errorf("type conversion error from '%s' to '%s'", l.Type(), typeDesc) + } +} + +func (l *reflectSchemalessTypedList) ConvertToType(typeValue ref.Type) ref.Val { + switch typeValue { + case types.ListType: + return l + case types.TypeType: + return types.ListType + } + return types.NewErr("type conversion error from '%s' to '%s'", l.Type(), typeValue.TypeName()) +} + +func (l *reflectSchemalessTypedList) Equal(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz := l.Size().(types.Int) + if sz != otherList.Size().(types.Int) { + return types.False + } + for i := range sz { + v1 := l.Get(i) + v2 := otherList.Get(i) + if v1.Equal(v2) != types.True { + return types.False + } + } + return types.True +} + +func (l *reflectSchemalessTypedList) Type() ref.Type { + return types.ListType +} + +func (l *reflectSchemalessTypedList) Value() interface{} { + return l.value.Interface() +} + +func (l *reflectSchemalessTypedList) Contains(val ref.Val) ref.Val { + sz := l.Size().(types.Int) + for i := range sz { + v := l.Get(i) + if v.Equal(val) == types.True { + return types.True + } + } + return types.False +} + +func (l *reflectSchemalessTypedList) Add(other ref.Val) ref.Val { + otherList, ok := other.(traits.Lister) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + sz := l.value.Len() + otherSz, _ := otherList.Size().(types.Int) + elements := make([]ref.Val, 0, sz+int(otherSz)) + for i := range sz { + elements = append(elements, l.Get(types.Int(i))) + } + it := otherList.Iterator() + for it.HasNext() == types.True { + elements = append(elements, it.Next()) + } + return types.NewRefValList(types.DefaultTypeAdapter, elements) +} + +func (l *reflectSchemalessTypedList) Get(index ref.Val) ref.Val { + idx, ok := index.(types.Int) + if !ok { + return types.ValOrErr(index, "unsupported index type: %T", index) + } + if idx < 0 || int(idx) >= l.value.Len() { + return types.NewErr("index out of bounds: %d", idx) + } + i := int(idx) + if l.fieldCache == nil { + l.fieldCache = make([]ref.Val, l.value.Len()) + } + if cached := l.fieldCache[i]; cached != nil { + return cached + } + v := SchemalessTypedToVal(l.value.Index(i).Interface()) + l.fieldCache[i] = v + return v +} + +func (l *reflectSchemalessTypedList) Iterator() traits.Iterator { + return &reflectSchemalessTypedListIterator{reflectSchemalessTypedList: l, idx: 0} +} + +func (l *reflectSchemalessTypedList) Size() ref.Val { + return types.Int(l.value.Len()) +} + +type reflectSchemalessTypedListIterator struct { + *reflectSchemalessTypedList + idx int +} + +func (it *reflectSchemalessTypedListIterator) HasNext() ref.Val { + return types.Bool(it.idx < it.reflectSchemalessTypedList.value.Len()) +} + +func (it *reflectSchemalessTypedListIterator) Next() ref.Val { + if it.idx >= it.reflectSchemalessTypedList.value.Len() { + return types.NewErr("no more elements") + } + val := it.reflectSchemalessTypedList.Get(types.Int(it.idx)) + it.idx++ + return val +} + +var _ traits.Mapper = &reflectSchemalessTypedMap{} + +// reflectSchemalessTypedMap wraps a Go map as a lazy CEL Mapper. +// fieldCache is NOT thread-safe, as CEL-Go's synchronous value evaluation contract +// guarantees that a single wrapped value is only ever accessed by a single goroutine. +type reflectSchemalessTypedMap struct { + value reflect.Value + fieldCache map[string]ref.Val +} + +func (m *reflectSchemalessTypedMap) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { + if m.value.Type().AssignableTo(typeDesc) { + return m.value.Interface(), nil + } + return nil, fmt.Errorf("type conversion error from '%s' to '%s'", m.Type(), typeDesc) +} + +func (m *reflectSchemalessTypedMap) ConvertToType(typeValue ref.Type) ref.Val { + switch typeValue { + case types.MapType: + return m + case types.TypeType: + return types.MapType + } + return types.NewErr("type conversion error from '%s' to '%s'", m.Type(), typeValue.TypeName()) +} + +func (m *reflectSchemalessTypedMap) Equal(other ref.Val) ref.Val { + otherMap, ok := other.(traits.Mapper) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + if m.Size() != otherMap.Size() { + return types.False + } + it := m.Iterator() + for it.HasNext() == types.True { + key := it.Next() + v1, _ := m.Find(key) + v2, found := otherMap.Find(key) + if !found || v1.Equal(v2) != types.True { + return types.False + } + } + return types.True +} + +func (m *reflectSchemalessTypedMap) Type() ref.Type { + return types.MapType +} + +func (m *reflectSchemalessTypedMap) Value() interface{} { + return m.value.Interface() +} + +func (m *reflectSchemalessTypedMap) Contains(key ref.Val) ref.Val { + v, found := m.Find(key) + if v != nil && types.IsError(v) { + return v + } + return types.Bool(found) +} + +func (m *reflectSchemalessTypedMap) Find(key ref.Val) (ref.Val, bool) { + keyVal, ok := key.(types.String) + if !ok { + return types.ValOrErr(key, "unsupported map key type: %T", key), false + } + fieldName := string(keyVal) + if m.fieldCache != nil { + if cached, ok := m.fieldCache[fieldName]; ok { + return cached, cached != nil + } + } + + var result ref.Val + found := false + + keyType := m.value.Type().Key() + if keyType.Kind() == reflect.String { + reflectKey := reflect.ValueOf(fieldName).Convert(keyType) + val := m.value.MapIndex(reflectKey) + if val.IsValid() { + result = SchemalessTypedToVal(val.Interface()) + found = true + } + } + + if m.fieldCache == nil { + m.fieldCache = make(map[string]ref.Val) + } + m.fieldCache[fieldName] = result + return result, found +} + +func (m *reflectSchemalessTypedMap) Get(key ref.Val) ref.Val { + v, found := m.Find(key) + if !found { + if v != nil && types.IsError(v) { + return v + } + return types.ValOrErr(key, "no such key: %v", key) + } + return v +} + +func (m *reflectSchemalessTypedMap) Iterator() traits.Iterator { + return &reflectSchemalessTypedMapIterator{reflectSchemalessTypedMap: m, keys: m.value.MapKeys(), idx: 0} +} + +func (m *reflectSchemalessTypedMap) Size() ref.Val { + return types.Int(m.value.Len()) +} + +type reflectSchemalessTypedMapIterator struct { + *reflectSchemalessTypedMap + keys []reflect.Value + idx int +} + +func (it *reflectSchemalessTypedMapIterator) HasNext() ref.Val { + return types.Bool(it.idx < len(it.keys)) +} + +func (it *reflectSchemalessTypedMapIterator) Next() ref.Val { + if it.idx >= len(it.keys) { + return types.NewErr("no more elements") + } + val := types.String(it.keys[it.idx].String()) + it.idx++ + return val +} + +var _ traits.Mapper = &reflectSchemalessTypedStruct{} + +// reflectSchemalessTypedStruct wraps a Go struct as a lazy CEL Mapper. +// fieldCache is NOT thread-safe, as CEL-Go's synchronous value evaluation contract +// guarantees that a single wrapped value is only ever accessed by a single goroutine. +type reflectSchemalessTypedStruct struct { + value reflect.Value + fieldCache map[string]ref.Val +} + +func (s *reflectSchemalessTypedStruct) ConvertToNative(typeDesc reflect.Type) (interface{}, error) { + if s.value.Type().AssignableTo(typeDesc) { + return s.value.Interface(), nil + } + return nil, fmt.Errorf("type conversion error from struct type %v to %v", s.value.Type(), typeDesc) +} + +func (s *reflectSchemalessTypedStruct) ConvertToType(typeValue ref.Type) ref.Val { + switch typeValue { + case types.MapType: + return s + case types.TypeType: + return types.MapType + } + return types.NewErr("type conversion error from struct to %s", typeValue.TypeName()) +} + +func (s *reflectSchemalessTypedStruct) Equal(other ref.Val) ref.Val { + otherStruct, ok := other.(*reflectSchemalessTypedStruct) + if ok { + return types.Bool(apiequality.Semantic.DeepEqual(s.value.Interface(), otherStruct.value.Interface())) + } + otherMap, ok := other.(traits.Mapper) + if !ok { + return types.MaybeNoSuchOverloadErr(other) + } + if s.Size() != otherMap.Size() { + return types.False + } + it := s.Iterator() + for it.HasNext() == types.True { + key := it.Next() + v1, _ := s.Find(key) + v2, found := otherMap.Find(key) + if !found { + return types.False + } + eq := v1.Equal(v2) + if eq != types.True { + return eq + } + } + return types.True +} + +func (s *reflectSchemalessTypedStruct) Type() ref.Type { + return types.MapType // Unstructured behaves exactly as a Map +} + +func (s *reflectSchemalessTypedStruct) Value() interface{} { + return s.value.Interface() +} + +func (s *reflectSchemalessTypedStruct) IsSet(field ref.Val) ref.Val { + v, found := s.lookupField(field) + if v != nil && types.IsUnknownOrError(v) { + return v + } + return types.Bool(found) +} + +func (s *reflectSchemalessTypedStruct) Find(key ref.Val) (ref.Val, bool) { + return s.lookupField(key) +} + +func (s *reflectSchemalessTypedStruct) Get(key ref.Val) ref.Val { + v, found := s.lookupField(key) + if !found { + return types.ValOrErr(key, "no such key: %v", key) + } + return v +} + +func (s *reflectSchemalessTypedStruct) Contains(key ref.Val) ref.Val { + v, found := s.Find(key) + if v != nil && types.IsError(v) { + return v + } + return types.Bool(found) +} + +func (s *reflectSchemalessTypedStruct) lookupField(key ref.Val) (ref.Val, bool) { + keyStr, ok := key.(types.String) + if !ok { + return types.ValOrErr(key, "unsupported map key type: %T", key), true + } + fieldName := keyStr.Value().(string) + + if s.fieldCache != nil { + if cached, ok := s.fieldCache[fieldName]; ok { + return cached, cached != nil + } + } + + var result ref.Val + found := false + + cacheEntry := value.TypeReflectEntryOf(s.value.Type()) + fieldCache, ok := cacheEntry.Fields()[fieldName] + if ok { + if e := fieldCache.GetFrom(s.value); !fieldCache.CanOmit(e) { + result = SchemalessTypedToVal(e.Interface()) + found = true + } + } + + if s.fieldCache == nil { + s.fieldCache = make(map[string]ref.Val) + } + s.fieldCache[fieldName] = result + return result, found +} + +func (s *reflectSchemalessTypedStruct) Size() ref.Val { + cacheEntry := value.TypeReflectEntryOf(s.value.Type()) + count := 0 + for _, fieldCache := range cacheEntry.Fields() { + if e := fieldCache.GetFrom(s.value); !fieldCache.CanOmit(e) { + count++ + } + } + return types.Int(count) +} + +func (s *reflectSchemalessTypedStruct) Iterator() traits.Iterator { + cacheEntry := value.TypeReflectEntryOf(s.value.Type()) + var keys []string + for fieldName, fieldCache := range cacheEntry.Fields() { + if e := fieldCache.GetFrom(s.value); !fieldCache.CanOmit(e) { + keys = append(keys, string(fieldName)) + } + } + return &reflectSchemalessTypedStructIterator{reflectSchemalessTypedStruct: s, keys: keys, idx: 0} +} + +type reflectSchemalessTypedStructIterator struct { + *reflectSchemalessTypedStruct + keys []string + idx int +} + +func (it *reflectSchemalessTypedStructIterator) HasNext() ref.Val { + return types.Bool(it.idx < len(it.keys)) +} + +func (it *reflectSchemalessTypedStructIterator) Next() ref.Val { + if it.idx >= len(it.keys) { + return types.NewErr("no more elements") + } + val := types.String(it.keys[it.idx]) + it.idx++ + return val +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesunstructured.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesunstructured.go index 229916624..377f885b7 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesunstructured.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/common/valuesunstructured.go @@ -281,7 +281,8 @@ func (t *unstructuredMapList) toMapKey(element interface{}) interface{} { for i, kf := range t.escapedKeyProps { key[i] = eObj[kf] } - return fmt.Sprintf("%v", key) + // Serialize to a string for more than 3 keys. %#v quotes strings. + return fmt.Sprintf("%#v", key) } // Equal on a map list ignores list element order. @@ -295,6 +296,7 @@ func (t *unstructuredMapList) Equal(other ref.Val) ref.Val { return types.False } tMap := t.getMap() + seen := make(map[interface{}]struct{}, len(tMap)) for it := oMapList.Iterator(); it.HasNext() == types.True; { v := it.Next() k := t.toMapKey(v.Value()) @@ -306,8 +308,9 @@ func (t *unstructuredMapList) Equal(other ref.Val) ref.Val { if eq != types.True { return eq // either false or error } + seen[k] = struct{}{} } - return types.True + return types.Bool(len(seen) == len(tMap)) } // Add for a map list `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values @@ -318,26 +321,11 @@ func (t *unstructuredMapList) Add(other ref.Val) ref.Val { if !ok { return types.MaybeNoSuchOverloadErr(other) } - elements := make([]interface{}, len(t.elements)) - keyToIdx := map[interface{}]int{} - for i, e := range t.elements { - k := t.toMapKey(e) - keyToIdx[k] = i - elements[i] = e - } - for it := oMapList.Iterator(); it.HasNext() == types.True; { - v := it.Next().Value() - k := t.toMapKey(v) - if overwritePosition, ok := keyToIdx[k]; ok { - elements[overwritePosition] = v - } else { - elements = append(elements, v) - } - } - return &unstructuredMapList{ - unstructuredList: unstructuredList{elements: elements, itemsSchema: t.itemsSchema}, - escapedKeyProps: t.escapedKeyProps, + elements := make([]ref.Val, len(t.elements)) + for i := range t.elements { + elements[i] = t.Get(types.Int(i)) } + return addToMapList(elements, oMapList, t.escapedKeyProps) } // escapeKeyProps returns identifiers with Escape applied to each. @@ -361,21 +349,25 @@ type unstructuredSetList struct { sync.Once // for lazy load of setOfList since it is only needed if Equals is called set map[interface{}]struct{} + setErr ref.Val } -func (t *unstructuredSetList) getSet() map[interface{}]struct{} { - // sets are only allowed to contain scalar elements, which are comparable in go, and can safely be used as - // golang map keys +func (t *unstructuredSetList) getSet() (map[interface{}]struct{}, ref.Val) { t.Do(func() { t.set = make(map[interface{}]struct{}, len(t.elements)) - for _, e := range t.elements { - t.set[e] = struct{}{} + for i := range t.elements { + k, err := setElementKey(t.Get(types.Int(i))) + if err != nil { + t.set, t.setErr = nil, err + return + } + t.set[k] = struct{}{} } }) - return t.set + return t.set, t.setErr } -// Equal on a map list ignores list element order. +// Equal on a set list ignores list element order. func (t *unstructuredSetList) Equal(other ref.Val) ref.Val { oSetList, ok := other.(traits.Lister) if !ok { @@ -385,15 +377,22 @@ func (t *unstructuredSetList) Equal(other ref.Val) ref.Val { if sz != oSetList.Size() { return types.False } - tSet := t.getSet() + tSet, err := t.getSet() + if err != nil { + return err + } + seen := make(map[interface{}]struct{}, len(tSet)) for it := oSetList.Iterator(); it.HasNext() == types.True; { - next := it.Next().Value() - _, ok := tSet[next] - if !ok { + k, err := setElementKey(it.Next()) + if err != nil { + return err + } + if _, ok := tSet[k]; !ok { return types.False } + seen[k] = struct{}{} } - return types.True + return types.Bool(len(seen) == len(tSet)) } // Add for a set list `X + Y` performs a union where the array positions of all elements in `X` are preserved and @@ -403,18 +402,11 @@ func (t *unstructuredSetList) Add(other ref.Val) ref.Val { if !ok { return types.MaybeNoSuchOverloadErr(other) } - elements := t.elements - set := t.getSet() - for it := oSetList.Iterator(); it.HasNext() == types.True; { - next := it.Next().Value() - if _, ok := set[next]; !ok { - set[next] = struct{}{} - elements = append(elements, next) - } - } - return &unstructuredSetList{ - unstructuredList: unstructuredList{elements: elements, itemsSchema: t.itemsSchema}, + elements := make([]ref.Val, len(t.elements)) + for i := range t.elements { + elements[i] = t.Get(types.Int(i)) } + return addToSetList(elements, oSetList) } // unstructuredList represents an unstructured data instance of an OpenAPI array with x-kubernetes-list-type=atomic (the default). @@ -489,13 +481,15 @@ func (t *unstructuredList) Add(other ref.Val) ref.Val { if !ok { return types.MaybeNoSuchOverloadErr(other) } - elements := t.elements + otherSz, _ := oList.Size().(types.Int) + elements := make([]ref.Val, 0, len(t.elements)+int(otherSz)) + for i := range t.elements { + elements = append(elements, t.Get(types.Int(i))) + } for it := oList.Iterator(); it.HasNext() == types.True; { - next := it.Next().Value() - elements = append(elements, next) + elements = append(elements, it.Next()) } - - return &unstructuredList{elements: elements, itemsSchema: t.itemsSchema} + return types.NewRefValList(types.DefaultTypeAdapter, elements) } func (t *unstructuredList) Contains(val ref.Val) ref.Val { diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/environment/base.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/environment/base.go index 91bdc6cb1..be310c506 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/environment/base.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/environment/base.go @@ -20,7 +20,6 @@ import ( "fmt" "strconv" "sync" - "sync/atomic" "github.com/google/cel-go/cel" "github.com/google/cel-go/checker" @@ -31,9 +30,7 @@ import ( "k8s.io/apimachinery/pkg/util/version" celconfig "k8s.io/apiserver/pkg/apis/cel" "k8s.io/apiserver/pkg/cel/library" - genericfeatures "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/util/compatibility" - utilfeature "k8s.io/apiserver/pkg/util/feature" basecompatibility "k8s.io/component-base/compatibility" ) @@ -72,7 +69,6 @@ var baseOpts = []VersionedOptions{ UnversionedLib(library.URLs), UnversionedLib(library.Regex), - UnversionedLib(library.Lists), // cel-go v0.17.7 change the cost of has() from 0 to 1, but also provided the CostEstimatorOptions option to preserve the old behavior, so we enabled it at the same time we bumped our cel version to v0.17.7. // Since it is a regression fix, we apply it uniformly to all code use v0.17.7. @@ -87,6 +83,13 @@ var baseOpts = []VersionedOptions{ cel.CostTrackerOptions(interpreter.PresenceTestHasCost(false)), }, }, + { + IntroducedVersion: version.MajorMinor(1, 0), + RemovedVersion: version.MajorMinor(1, 37), + EnvOptions: []cel.EnvOption{ + library.Lists(library.ListsVersion(0)), + }, + }, { IntroducedVersion: version.MajorMinor(1, 27), EnvOptions: []cel.EnvOption{ @@ -151,18 +154,6 @@ var baseOpts = []VersionedOptions{ // Authz selectors { IntroducedVersion: version.MajorMinor(1, 31), - FeatureEnabled: func() bool { - enabled := utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AuthorizeWithSelectors) - authzSelectorsLibraryInit.Do(func() { - // Record the first time feature enablement was checked for this library. - // This is checked from integration tests to ensure no cached cel envs - // are constructed before feature enablement is effectively set. - authzSelectorsLibraryEnabled.Store(enabled) - // Uncomment to debug where the first initialization is coming from if needed. - // debug.PrintStack() - }) - return enabled - }, EnvOptions: []cel.EnvOption{ UnversionedLib(library.AuthzSelectors), }, @@ -188,22 +179,15 @@ var baseOpts = []VersionedOptions{ ext.Lists(ext.ListsVersion(3)), }, }, + { + IntroducedVersion: version.MajorMinor(1, 37), + EnvOptions: []cel.EnvOption{ + library.Lists(library.ListsVersion(1)), + }, + }, StrictCostOpt, } -var ( - authzSelectorsLibraryInit sync.Once - authzSelectorsLibraryEnabled atomic.Value -) - -// AuthzSelectorsLibraryEnabled returns whether the AuthzSelectors library was enabled when it was constructed. -// If it has not been contructed yet, this returns `false, false`. -// This is solely for the benefit of the integration tests making sure feature gates get correctly parsed before AuthzSelector ever has to check for enablement. -func AuthzSelectorsLibraryEnabled() (enabled, constructed bool) { - enabled, constructed = authzSelectorsLibraryEnabled.Load().(bool) - return -} - var StrictCostOpt = VersionedOptions{ // This is to configure the cost calculation for extended libraries IntroducedVersion: version.MajorMinor(1, 0), diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/authz.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/authz.go index 77332cff8..beefaf645 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/authz.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/authz.go @@ -24,8 +24,6 @@ import ( "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" - genericfeatures "k8s.io/apiserver/pkg/features" - utilfeature "k8s.io/apiserver/pkg/util/feature" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" @@ -619,11 +617,11 @@ type Resource interface { GetSubresource() string } -func NewAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer) ref.Val { +func NewAuthorizerVal(userInfo user.Info, authorizer authorizer.UnconditionalAuthorizer) ref.Val { return authorizerVal{receiverOnlyObjectVal: receiverOnlyVal(AuthorizerType), userInfo: userInfo, authAuthorizer: authorizer} } -func NewResourceAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer, requestResource Resource) ref.Val { +func NewResourceAuthorizerVal(userInfo user.Info, authorizer authorizer.UnconditionalAuthorizer, requestResource Resource) ref.Val { a := authorizerVal{receiverOnlyObjectVal: receiverOnlyVal(AuthorizerType), userInfo: userInfo, authAuthorizer: authorizer} resource := requestResource.GetResource() g := a.groupCheck(resource.Group) @@ -637,7 +635,7 @@ func NewResourceAuthorizerVal(userInfo user.Info, authorizer authorizer.Authoriz type authorizerVal struct { receiverOnlyObjectVal userInfo user.Info - authAuthorizer authorizer.Authorizer + authAuthorizer authorizer.UnconditionalAuthorizer } func (a authorizerVal) pathCheck(path string) pathCheckVal { @@ -708,22 +706,20 @@ func (a resourceCheckVal) Authorize(ctx context.Context, verb string) ref.Val { User: a.groupCheck.authorizer.userInfo, } - if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AuthorizeWithSelectors) { - if len(a.fieldSelector) > 0 { - selector, err := fields.ParseSelector(a.fieldSelector) - if err != nil { - attr.FieldSelectorRequirements, attr.FieldSelectorParsingErr = nil, err - } else { - attr.FieldSelectorRequirements, attr.FieldSelectorParsingErr = selector.Requirements(), nil - } + if len(a.fieldSelector) > 0 { + selector, err := fields.ParseSelector(a.fieldSelector) + if err != nil { + attr.FieldSelectorRequirements, attr.FieldSelectorParsingErr = nil, err + } else { + attr.FieldSelectorRequirements, attr.FieldSelectorParsingErr = selector.Requirements(), nil } - if len(a.labelSelector) > 0 { - requirements, err := labels.ParseToRequirements(a.labelSelector) - if err != nil { - attr.LabelSelectorRequirements, attr.LabelSelectorParsingErr = nil, err - } else { - attr.LabelSelectorRequirements, attr.LabelSelectorParsingErr = requirements, nil - } + } + if len(a.labelSelector) > 0 { + requirements, err := labels.ParseToRequirements(a.labelSelector) + if err != nil { + attr.LabelSelectorRequirements, attr.LabelSelectorParsingErr = nil, err + } else { + attr.LabelSelectorRequirements, attr.LabelSelectorParsingErr = requirements, nil } } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/cost.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/cost.go index 1eb68e16f..80c3a850b 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/cost.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/cost.go @@ -101,7 +101,7 @@ func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, re cost := selectorCostEstimate(checker.SizeEstimate{Min: selectorLength, Max: selectorLength}) return &cost.Max } - case "isSorted", "sum", "max", "min", "indexOf", "lastIndexOf": + case "isSorted", "sum", "max", "min", "indexOf", "lastIndexOf", "includes": var cost uint64 if len(args) > 0 { cost += traversalCost(args[0]) // these O(n) operations all cost roughly the cost of a single traversal @@ -287,7 +287,7 @@ func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *ch if len(args) == 1 { return &checker.CallEstimate{CostEstimate: selectorCostEstimate(l.sizeEstimate(args[0]))} } - case "isSorted", "sum", "max", "min", "indexOf", "lastIndexOf": + case "isSorted", "sum", "max", "min", "indexOf", "lastIndexOf", "includes": if target != nil { // Charge 1 cost for comparing each element in the list elCost := checker.CostEstimate{Min: 1, Max: 1} @@ -300,7 +300,12 @@ func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *ch elCost = elCost.Add(sz.MultiplyByCostFactor(common.StringTraversalCostFactor)) } return &checker.CallEstimate{CostEstimate: l.sizeEstimate(*target).MultiplyByCost(elCost)} - } else { // the target is a string, which is supported by indexOf and lastIndexOf + } else if function == "includes" { + // Since target can be a list under DynType, the worst case is a list comparison of size n, + // where each comparison costs 1. + return &checker.CallEstimate{CostEstimate: l.sizeEstimate(*target).MultiplyByCost(elCost)} + } else { + // the target is a string, which is supported by indexOf and lastIndexOf return &checker.CallEstimate{CostEstimate: l.sizeEstimate(*target).MultiplyByCostFactor(common.StringTraversalCostFactor)} } } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/lists.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/lists.go index 1f61b1181..e68c215e6 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/lists.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/lists.go @@ -18,6 +18,7 @@ package library import ( "fmt" + "math" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" @@ -87,13 +88,45 @@ import ( // ['a', 'b', 'b', 'c'].lastIndexOf('b') // returns 2 // [1.0].indexOf(1.1) // returns -1 // [].indexOf('string') // returns -1 -func Lists() cel.EnvOption { - return cel.Lib(listsLib) +// +// includes +// +// Returns true if the target list contains the element, or if the target is equal to the element. +// +// .includes() +// +// Examples: +// +// [1, 2, 3].includes(2) // returns true +// [1, 2, 3].includes(4) // returns false +// 'model-a'.includes('model-a') // returns true +// 'model-a'.includes('model-b') // returns false +// +// ListsOption is a functional interface for configuring the lists library. +type ListsOption func(*lists) *lists + +// ListsVersion sets the version of the lists library to use. +func ListsVersion(version uint32) ListsOption { + return func(lib *lists) *lists { + lib.version = version + return lib + } } -var listsLib = &lists{} +// Lists provides a CEL function library extension of list utility functions. +func Lists(options ...ListsOption) cel.EnvOption { + l := &lists{} + for _, o := range options { + l = o(l) + } + return cel.Lib(l) +} + +var listsLib = &lists{version: math.MaxUint32} -type lists struct{} +type lists struct { + version uint32 +} func (*lists) LibraryName() string { return "kubernetes.lists" @@ -103,8 +136,45 @@ func (*lists) Types() []*cel.Type { return []*cel.Type{} } -func (*lists) declarations() map[string][]cel.FunctionOpt { - return listsLibraryDecls +func (l *lists) declarations() map[string][]cel.FunctionOpt { + decls := map[string][]cel.FunctionOpt{ + "isSorted": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { + return cel.MemberOverload(fmt.Sprintf("list_%s_is_sorted_bool", name), + []*cel.Type{cel.ListType(paramType)}, cel.BoolType, cel.UnaryBinding(isSorted)) + }), + "sum": templatedOverloads(summableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { + return cel.MemberOverload(fmt.Sprintf("list_%s_sum_%s", name, name), + []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(func(list ref.Val) ref.Val { + return sum( + func() ref.Val { + return zeroValuesOfSummableTypes[name] + })(list) + })) + }), + "max": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { + return cel.MemberOverload(fmt.Sprintf("list_%s_max_%s", name, name), + []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(max())) + }), + "min": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { + return cel.MemberOverload(fmt.Sprintf("list_%s_min_%s", name, name), + []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(min())) + }), + "indexOf": { + cel.MemberOverload("list_a_index_of_int", []*cel.Type{cel.ListType(paramA), paramA}, cel.IntType, + cel.BinaryBinding(indexOf)), + }, + "lastIndexOf": { + cel.MemberOverload("list_a_last_index_of_int", []*cel.Type{cel.ListType(paramA), paramA}, cel.IntType, + cel.BinaryBinding(lastIndexOf)), + }, + } + if l.version >= 1 { + decls["includes"] = []cel.FunctionOpt{ + cel.MemberOverload("list_includes_dyn_dyn", []*cel.Type{cel.DynType, cel.DynType}, cel.BoolType, + cel.BinaryBinding(includes)), + } + } + return decls } var paramA = cel.TypeParamType("A") @@ -141,48 +211,21 @@ var comparableTypes = []namedCELType{ {typeName: "bytes", celType: cel.BytesType}, } -// WARNING: All library additions or modifications must follow -// https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/2876-crd-validation-expression-language#function-library-updates -var listsLibraryDecls = map[string][]cel.FunctionOpt{ - "isSorted": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { - return cel.MemberOverload(fmt.Sprintf("list_%s_is_sorted_bool", name), - []*cel.Type{cel.ListType(paramType)}, cel.BoolType, cel.UnaryBinding(isSorted)) - }), - "sum": templatedOverloads(summableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { - return cel.MemberOverload(fmt.Sprintf("list_%s_sum_%s", name, name), - []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(func(list ref.Val) ref.Val { - return sum( - func() ref.Val { - return zeroValuesOfSummableTypes[name] - })(list) - })) - }), - "max": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { - return cel.MemberOverload(fmt.Sprintf("list_%s_max_%s", name, name), - []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(max())) - }), - "min": templatedOverloads(comparableTypes, func(name string, paramType *cel.Type) cel.FunctionOpt { - return cel.MemberOverload(fmt.Sprintf("list_%s_min_%s", name, name), - []*cel.Type{cel.ListType(paramType)}, paramType, cel.UnaryBinding(min())) - }), - "indexOf": { - cel.MemberOverload("list_a_index_of_int", []*cel.Type{cel.ListType(paramA), paramA}, cel.IntType, - cel.BinaryBinding(indexOf)), - }, - "lastIndexOf": { - cel.MemberOverload("list_a_last_index_of_int", []*cel.Type{cel.ListType(paramA), paramA}, cel.IntType, - cel.BinaryBinding(lastIndexOf)), - }, -} - -func (*lists) CompileOptions() []cel.EnvOption { +func (l *lists) CompileOptions() []cel.EnvOption { options := []cel.EnvOption{} - for name, overloads := range listsLibraryDecls { + for name, overloads := range l.declarations() { options = append(options, cel.Function(name, overloads...)) } return options } +// IncludesOption returns the EnvOption to register the includes function directly. +func IncludesOption() cel.EnvOption { + return cel.Function("includes", + cel.MemberOverload("list_includes_dyn_dyn", []*cel.Type{cel.DynType, cel.DynType}, cel.BoolType, + cel.BinaryBinding(includes))) +} + func (*lists) ProgramOptions() []cel.ProgramOption { return []cel.ProgramOption{} } @@ -311,6 +354,24 @@ func lastIndexOf(list ref.Val, item ref.Val) ref.Val { return types.Int(-1) } +func includes(target, arg ref.Val) ref.Val { + if list, ok := target.(traits.Lister); ok { + it := list.Iterator() + for it.HasNext() == types.True { + item := it.Next() + if item.Equal(arg) == types.True { + return types.True + } + } + return types.False + } + + if target.Equal(arg) == types.True { + return types.True + } + return types.False +} + // templatedOverloads returns overloads for each of the provided types. The template function is called with each type // name (map key) and type to construct the overloads. func templatedOverloads(types []namedCELType, template func(name string, t *cel.Type) cel.FunctionOpt) []cel.FunctionOpt { diff --git a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/quantity.go b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/quantity.go index f3fd8b1c5..011c383c4 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/cel/library/quantity.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/cel/library/quantity.go @@ -320,7 +320,7 @@ func quantityAdd(arg ref.Val, other ref.Val) ref.Val { return types.MaybeNoSuchOverloadErr(arg) } - copy := *q + copy := q.DeepCopy() copy.Add(*q2) return &apiservercel.Quantity{ Quantity: ©, @@ -340,7 +340,7 @@ func quantityAddInt(arg ref.Val, other ref.Val) ref.Val { q2Converted := *resource.NewQuantity(q2, resource.DecimalExponent) - copy := *q + copy := q.DeepCopy() copy.Add(q2Converted) return &apiservercel.Quantity{ Quantity: ©, @@ -358,7 +358,7 @@ func quantitySub(arg ref.Val, other ref.Val) ref.Val { return types.MaybeNoSuchOverloadErr(arg) } - copy := *q + copy := q.DeepCopy() copy.Sub(*q2) return &apiservercel.Quantity{ Quantity: ©, @@ -378,7 +378,7 @@ func quantitySubInt(arg ref.Val, other ref.Val) ref.Val { q2Converted := *resource.NewQuantity(q2, resource.DecimalExponent) - copy := *q + copy := q.DeepCopy() copy.Sub(q2Converted) return &apiservercel.Quantity{ Quantity: ©, diff --git a/constraint/vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go b/constraint/vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go index 1cf14d892..ea6ee3a6e 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go @@ -27,8 +27,6 @@ import ( metainternalversionscheme "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" - genericfeatures "k8s.io/apiserver/pkg/features" - utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/klog/v2" ) @@ -258,19 +256,17 @@ func (r *RequestInfoFactory) NewRequestInfo(req *http.Request) (*RequestInfo, er requestInfo.Verb = "deletecollection" } - if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AuthorizeWithSelectors) { - // Don't support selector authorization on requests that used the deprecated verb-via-path mechanism, since they don't support selectors consistently. - // There are multi-object and single-object watch endpoints, and only the multi-object one supports selectors. - if !verbViaPathPrefix && verbsWithSelectors.Has(requestInfo.Verb) { - // interestingly these are parsed above, but the current structure there means that if one (or anything) in the - // listOptions fails to decode, the field and label selectors are lost. - // therefore, do the straight query param read here. - if vals := req.URL.Query()["fieldSelector"]; len(vals) > 0 { - requestInfo.FieldSelector = vals[0] - } - if vals := req.URL.Query()["labelSelector"]; len(vals) > 0 { - requestInfo.LabelSelector = vals[0] - } + // Don't support selector authorization on requests that used the deprecated verb-via-path mechanism, since they don't support selectors consistently. + // There are multi-object and single-object watch endpoints, and only the multi-object one supports selectors. + if !verbViaPathPrefix && verbsWithSelectors.Has(requestInfo.Verb) { + // interestingly these are parsed above, but the current structure there means that if one (or anything) in the + // listOptions fails to decode, the field and label selectors are lost. + // therefore, do the straight query param read here. + if vals := req.URL.Query()["fieldSelector"]; len(vals) > 0 { + requestInfo.FieldSelector = vals[0] + } + if vals := req.URL.Query()["labelSelector"]; len(vals) > 0 { + requestInfo.LabelSelector = vals[0] } } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/features/kube_features.go b/constraint/vendor/k8s.io/apiserver/pkg/features/kube_features.go index dbe776e8a..9b22ba488 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/features/kube_features.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/features/kube_features.go @@ -44,10 +44,12 @@ const ( // Assigns each kube-apiserver an ID in a cluster. APIServerIdentity featuregate.Feature = "APIServerIdentity" - // owner: @dashpole + // owner: @pmengelbert + // kep: https://kep.k8s.io/6060 // - // Add support for distributed tracing in the API Server - APIServerTracing featuregate.Feature = "APIServerTracing" + // Controls whether the apiserver supports dispensing tokens for authenticating + // the Kubernetes API Server and Aggregated API Servers to webhooks. + APIServerWebhookAuthenticationToken featuregate.Feature = "APIServerWebhookAuthenticationToken" // owner: @linxiulei // @@ -66,7 +68,7 @@ const ( // Allow user.DefaultInfo.UID to be set from x509 cert during cert auth. AllowParsingUserUIDFromCertAuth featuregate.Feature = "AllowParsingUserUIDFromCertAuth" - // owner: @stlaz @tkashem @dgrisonnet + // owner: @stlaz @tkashem @dgrisonnet @ibihim // kep: https://kep.k8s.io/3926 // // Enables the cluster admin to identify resources that fail to @@ -75,23 +77,6 @@ const ( // resources using the Kubernetes API only. AllowUnsafeMalformedObjectDeletion featuregate.Feature = "AllowUnsafeMalformedObjectDeletion" - // owner: @vinayakankugoyal - // kep: https://kep.k8s.io/4633 - // - // Allows us to enable anonymous auth for only certain apiserver endpoints. - AnonymousAuthConfigurableEndpoints featuregate.Feature = "AnonymousAuthConfigurableEndpoints" - - // owner: @deads2k - // kep: https://kep.k8s.io/4601 - // - // Allows authorization to use field and label selectors. - AuthorizeWithSelectors featuregate.Feature = "AuthorizeWithSelectors" - - // owner: @serathius - // - // Replaces watch cache hashmap implementation with a btree based one, bringing performance improvements. - BtreeWatchCache featuregate.Feature = "BtreeWatchCache" - // owner: @benluddy // kep: https://kep.k8s.io/4222 // @@ -103,11 +88,12 @@ const ( // Enables concurrent watch object decoding to avoid starving watch cache when conversion webhook is installed. ConcurrentWatchObjectDecode featuregate.Feature = "ConcurrentWatchObjectDecode" - // owner: @serathius - // kep: http://kep.k8s.io/2340 + // owner: @yedou37 // - // Allow the API server to serve consistent lists from cache - ConsistentListFromCache featuregate.Feature = "ConsistentListFromCache" + // Skip the timeout fallback to storage when a consistent LIST from cache cannot be served, + // and return a retryable response instead. + // See https://github.com/kubernetes/kubernetes/issues/138494. + ConsistentListFromCacheSkipTimeoutFallback featuregate.Feature = "ConsistentListFromCacheSkipTimeoutFallback" // owner: @enj @qiujian16 // kep: https://kep.k8s.io/5284 @@ -125,10 +111,10 @@ const ( // kep: http://kep.k8s.io/5073 // beta: v1.33 // - // Enables running declarative validation of APIs, where declared. When enabled, APIs with - // declarative validation rules will validate objects using the generated - // declarative validation code and compare the results to the regular imperative validation. - // See DeclarativeValidationBeta for more. + // When enabled, results of declarative validation are compared against handwritten + // validation and mismatches are logged as metrics. Declarative validation itself is + // always executed independent of this gate; per-tag enforcement is controlled by the + // lifecycle prefix and the DeclarativeValidationBeta gate. DeclarativeValidation featuregate.Feature = "DeclarativeValidation" // owner: @jpbetz @aaron-prindle @yongruilin @@ -141,11 +127,10 @@ const ( // In Shadow mode, declarative validation is executed and mismatches against handwritten // validation are logged as metrics, but failures do not reject requests. // Handwritten validation remains authoritative and enforced. - // Enforcement logic for resources using WithDeclarativeEnforcement(): + // Enforcement by lifecycle prefix: // - Standard tags (no prefix): Always Enforced (Bypasses this gate). // - Beta tags (+k8s:beta): Enforced when this gate is enabled (default), otherwise Shadowed. // - Alpha tags (+k8s:alpha): Always Shadowed. - // This gate has no effect if the master DeclarativeValidation feature gate is disabled. DeclarativeValidationBeta featuregate.Feature = "DeclarativeValidationBeta" // owner: @jpbetz @aaron-prindle @yongruilin @@ -168,6 +153,19 @@ const ( // Enabled cache inconsistency detection. DetectCacheInconsistency featuregate.Feature = "DetectCacheInconsistency" + // owner: @jefftree + // + // Enables the RangeStream RPC for list operations in etcd. + EtcdRangeStream featuregate.Feature = "EtcdRangeStream" + + // owner: @aramase @BenTheElder + // kep: https://kep.k8s.io/5793 + // + // Enables excluding the same set of authentication and authorization virtual resources + // from ValidatingAdmissionWebhook and MutatingAdmissionWebhook that ValidatingAdmissionPolicy + // and MutatingAdmissionPolicy already exclude. + ExcludeAdmissionWebhookVirtualResources featuregate.Feature = "ExcludeAdmissionWebhookVirtualResources" + // owner: @aramase // kep: https://kep.k8s.io/3299 // deprecated: v1.28 @@ -210,17 +208,6 @@ const ( // headers when forwarding requests to the servers serving the aggregated API. RemoteRequestHeaderUID featuregate.Feature = "RemoteRequestHeaderUID" - // owner: @wojtek-t - // - // Enables resilient watchcache initialization to avoid controlplane - // overload. - ResilientWatchCacheInitialization featuregate.Feature = "ResilientWatchCacheInitialization" - - // owner: @jpbetz - // Resource create requests using generateName are retried automatically by the apiserver - // if the generated name conflicts with an existing resource name, up to a maximum number of 7 retries. - RetryGenerateName featuregate.Feature = "RetryGenerateName" - // owner: @cici37 // // Allow watch cache to create a watch on a dedicated RPC. @@ -251,20 +238,6 @@ const ( // document. StorageVersionHash featuregate.Feature = "StorageVersionHash" - // owner: @serathius - // Allow API server JSON encoder to encode collections item by item, instead of all at once. - StreamingCollectionEncodingToJSON featuregate.Feature = "StreamingCollectionEncodingToJSON" - - // owner: @serathius - // Allow API server Protobuf encoder to encode collections item by item, instead of all at once. - StreamingCollectionEncodingToProtobuf featuregate.Feature = "StreamingCollectionEncodingToProtobuf" - - // owner: @aramase, @enj, @nabokihms - // kep: https://kep.k8s.io/3331 - // - // Enables Structured Authentication Configuration - StructuredAuthenticationConfiguration featuregate.Feature = "StructuredAuthenticationConfiguration" - // owner: @aramase, @enj, @nabokihms // kep: https://kep.k8s.io/3331 // @@ -318,6 +291,19 @@ const ( // // Allow the API server to stream individual items instead of chunking WatchList featuregate.Feature = "WatchList" + + // owner: @p0lyn0mial + // + // Enables compression for WatchList responses + WatchListCompression featuregate.Feature = "WatchListCompression" + + // owner: @aojea + // beta: v1.37 + // + // Enables using a custom resolving RoundTripper to load-balance admission + // webhook requests across service endpoints instead of caching connections + // by service name. + WebhookRoundTripLoadBalancing featuregate.Feature = "WebhookRoundTripLoadBalancing" ) func init() { @@ -342,10 +328,8 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.26"), Default: true, PreRelease: featuregate.Beta}, }, - APIServerTracing: { - {Version: version.MustParse("1.22"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.27"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.37 + APIServerWebhookAuthenticationToken: { + {Version: version.MustParse("1.37"), Default: false, PreRelease: featuregate.Alpha}, }, APIServingWithRoutine: { @@ -364,23 +348,7 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate AllowUnsafeMalformedObjectDeletion: { {Version: version.MustParse("1.32"), Default: false, PreRelease: featuregate.Alpha}, - }, - - AnonymousAuthConfigurableEndpoints: { - {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - - AuthorizeWithSelectors: { - {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.37 - }, - - BtreeWatchCache: { - {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, }, CBORServingAndStorage: { @@ -389,12 +357,11 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate ConcurrentWatchObjectDecode: { {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Beta}, + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, }, - ConsistentListFromCache: { - {Version: version.MustParse("1.28"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.31"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, + ConsistentListFromCacheSkipTimeoutFallback: { + {Version: version.MustParse("1.37"), Default: false, PreRelease: featuregate.Alpha}, }, ConstrainedImpersonation: { @@ -419,12 +386,21 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate DeclarativeValidationTakeover: { {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Beta}, {Version: version.MustParse("1.36"), Default: false, PreRelease: featuregate.Deprecated}, + {Version: version.MustParse("1.37"), Default: false, PreRelease: featuregate.Deprecated, LockToDefault: true}, }, DetectCacheInconsistency: { {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.Beta}, }, + EtcdRangeStream: { + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, + }, + + ExcludeAdmissionWebhookVirtualResources: { + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, + }, + KMSv1: { {Version: version.MustParse("1.0"), Default: true, PreRelease: featuregate.GA}, {Version: version.MustParse("1.28"), Default: true, PreRelease: featuregate.Deprecated}, @@ -438,6 +414,7 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate ManifestBasedAdmissionControlConfig: { {Version: version.MustParse("1.36"), Default: false, PreRelease: featuregate.Alpha}, + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, }, MutatingAdmissionPolicy: { @@ -456,17 +433,6 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, }, - ResilientWatchCacheInitialization: { - {Version: version.MustParse("1.31"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - - RetryGenerateName: { - {Version: version.MustParse("1.30"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.31"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.32"), Default: true, LockToDefault: true, PreRelease: featuregate.GA}, - }, - SeparateCacheWatchRPC: { {Version: version.MustParse("1.28"), Default: true, PreRelease: featuregate.Beta}, {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Deprecated}, @@ -490,22 +456,6 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.15"), Default: true, PreRelease: featuregate.Beta}, }, - StreamingCollectionEncodingToJSON: { - {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - - StreamingCollectionEncodingToProtobuf: { - {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - - StructuredAuthenticationConfiguration: { - {Version: version.MustParse("1.29"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.30"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // GA and LockToDefault in 1.34, remove in 1.37 - }, - StructuredAuthenticationConfigurationEgressSelector: { {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.Beta}, }, @@ -531,6 +481,7 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate WatchCacheInitializationPostStartHook: { {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Beta}, {Version: version.MustParse("1.36"), Default: true, PreRelease: featuregate.Beta}, + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, }, WatchList: { @@ -540,4 +491,12 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Beta}, {Version: version.MustParse("1.34"), Default: true, PreRelease: featuregate.Beta}, }, + + WatchListCompression: { + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, + }, + + WebhookRoundTripLoadBalancing: { + {Version: version.MustParse("1.37"), Default: true, PreRelease: featuregate.Beta}, + }, } diff --git a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/authentication.go b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/authentication.go index 0816b45a1..6ccc5fa8c 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/authentication.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/authentication.go @@ -29,9 +29,7 @@ import ( corev1 "k8s.io/api/core/v1" utilnet "k8s.io/apimachinery/pkg/util/net" - "k8s.io/apiserver/pkg/features" egressselector "k8s.io/apiserver/pkg/server/egressselector" - "k8s.io/apiserver/pkg/util/feature" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" @@ -59,9 +57,7 @@ func NewDefaultAuthenticationInfoResolverWrapper( if err != nil { return nil, err } - if feature.DefaultFeatureGate.Enabled(features.APIServerTracing) { - ret.Wrap(tracing.WrapperFor(tp)) - } + ret.Wrap(tracing.WrapperFor(tp)) if egressSelector != nil { networkContext := egressselector.ControlPlane.AsNetworkContext() @@ -84,9 +80,7 @@ func NewDefaultAuthenticationInfoResolverWrapper( if err != nil { return nil, err } - if feature.DefaultFeatureGate.Enabled(features.APIServerTracing) { - ret.Wrap(tracing.WrapperFor(tp)) - } + ret.Wrap(tracing.WrapperFor(tp)) if egressSelector != nil { networkContext := egressselector.Cluster.AsNetworkContext() diff --git a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/client.go b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/client.go index 63ea4e266..078e4377c 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/client.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/client.go @@ -22,6 +22,7 @@ import ( "errors" "fmt" "net" + "net/http" "net/url" "strconv" "strings" @@ -30,6 +31,8 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" utilerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apiserver/pkg/features" + utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/apiserver/pkg/util/x509metrics" "k8s.io/client-go/rest" "k8s.io/utils/lru" @@ -194,20 +197,36 @@ func (cm *ClientManager) hookClientConfig(cc ClientConfig) (*rest.Config, error) cfg.TLSClientConfig.ServerName = serverName } - delegateDialer := cfg.Dial - if delegateDialer == nil { - var d net.Dialer - delegateDialer = d.DialContext - } - cfg.Dial = func(ctx context.Context, network, addr string) (net.Conn, error) { - if addr == host { - u, err := cm.serviceResolver.ResolveEndpoint(cc.Service.Namespace, cc.Service.Name, port) - if err != nil { - return nil, err + if !utilfeature.DefaultFeatureGate.Enabled(features.WebhookRoundTripLoadBalancing) { + delegateDialer := cfg.Dial + if delegateDialer == nil { + var d net.Dialer + delegateDialer = d.DialContext + } + cfg.Dial = func(ctx context.Context, network, addr string) (net.Conn, error) { + if addr == host { + u, err := cm.serviceResolver.ResolveEndpoint(cc.Service.Namespace, cc.Service.Name, port) + if err != nil { + return nil, err + } + addr = u.Host } - addr = u.Host + return delegateDialer(ctx, network, addr) } - return delegateDialer(ctx, network, addr) + } else { + // Use a custom roundtripper since http transport caches + // the connections by the URL. Host. The service resolver + // provides the actual endpoint address, if we use a custom + // dialer then the cached connection may not be closed. + cfg.Wrap(func(rt http.RoundTripper) http.RoundTripper { + return &resolvingRoundTripper{ + delegate: rt, + serviceResolver: cm.serviceResolver, + namespace: cc.Service.Namespace, + serviceName: cc.Service.Name, + port: port, + } + }) } return complete(cfg) @@ -255,3 +274,36 @@ func isLocalHost(u *url.URL) bool { } return false } + +// resolvingRoundTripper is a roundtripper that resolves the endpoint address +// for the given service and updates the request URL to use the resolved endpoint address. +type resolvingRoundTripper struct { + delegate http.RoundTripper + serviceResolver ServiceResolver + namespace string + serviceName string + port int32 +} + +func (r *resolvingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + serverName := r.serviceName + "." + r.namespace + ".svc" + host := net.JoinHostPort(serverName, strconv.Itoa(int(r.port))) + if req.URL.Host != host { + return r.delegate.RoundTrip(req) + } + u, err := r.serviceResolver.ResolveEndpoint(r.namespace, r.serviceName, r.port) + if err != nil { + return nil, err + } + newReq := req.Clone(req.Context()) + // Preserve the original Host header + if len(newReq.Host) == 0 { + newReq.Host = req.URL.Host + } + newReq.URL.Host = u.Host + return r.delegate.RoundTrip(newReq) +} + +func (r *resolvingRoundTripper) WrappedRoundTripper() http.RoundTripper { + return r.delegate +} diff --git a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/metrics.go b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/metrics.go index 67fc8fabe..c7b6f26e7 100644 --- a/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/metrics.go +++ b/constraint/vendor/k8s.io/apiserver/pkg/util/webhook/metrics.go @@ -30,7 +30,7 @@ var x509MissingSANCounter = metrics.NewCounter( "in their serving certificate OR the number of connection failures " + "due to the lack of x509 certificate SAN extension missing " + "(either/or, based on the runtime environment)", - StabilityLevel: metrics.ALPHA, + StabilityLevel: metrics.BETA, }, ) @@ -42,7 +42,7 @@ var x509InsecureSHA1Counter = metrics.NewCounter( Help: "Counts the number of requests to servers with insecure SHA1 signatures " + "in their serving certificate OR the number of connection failures " + "due to the insecure SHA1 signatures (either/or, based on the runtime environment)", - StabilityLevel: metrics.ALPHA, + StabilityLevel: metrics.BETA, }, ) diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicy.go index f99f055b3..ae3d2f1fc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicyApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicybinding.go index 4bb30baa6..bea8a4a0f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBindingApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go index dcb0b81cc..926f15936 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go @@ -32,7 +32,7 @@ import ( // // MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object. type MutatingWebhookConfigurationApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // webhooks is a list of webhooks and the affected resources and operations. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/namedrulewithoperations.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/namedrulewithoperations.go index 326337c8c..aaffe6cc1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/namedrulewithoperations.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/namedrulewithoperations.go @@ -30,7 +30,7 @@ type NamedRuleWithOperationsApplyConfiguration struct { // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` // RuleWithOperations is a tuple of Operations and Resources. - RuleWithOperationsApplyConfiguration `json:",inline"` + RuleWithOperationsApplyConfiguration `json:""` } // NamedRuleWithOperationsApplyConfiguration constructs a declarative configuration of the NamedRuleWithOperations type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go index 575e1ab35..6692ef939 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go @@ -35,7 +35,7 @@ type RuleWithOperationsApplyConfiguration struct { Operations []admissionregistrationv1.OperationType `json:"operations,omitempty"` // Rule is embedded, it describes other criteria of the rule, like // APIGroups, APIVersions, Resources, etc. - RuleApplyConfiguration `json:",inline"` + RuleApplyConfiguration `json:""` } // RuleWithOperationsApplyConfiguration constructs a declarative configuration of the RuleWithOperations type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicy.go index 6e06ed3e5..a007d5057 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. type ValidatingAdmissionPolicyApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicybinding.go index 590aabda8..8fcc72c6d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBindingApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go index c3ac1fafd..d668f26de 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go @@ -32,7 +32,7 @@ import ( // // ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. type ValidatingWebhookConfigurationApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // webhooks is a list of webhooks and the affected resources and operations. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicy.go index 678e4d612..4c0ceff12 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicyApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go index 5286ce24c..124218090 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go index 45c12f191..5caf9c571 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go @@ -31,7 +31,7 @@ type NamedRuleWithOperationsApplyConfiguration struct { // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` // RuleWithOperations is a tuple of Operations and Resources. - v1.RuleWithOperationsApplyConfiguration `json:",inline"` + v1.RuleWithOperationsApplyConfiguration `json:""` } // NamedRuleWithOperationsApplyConfiguration constructs a declarative configuration of the NamedRuleWithOperations type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go index 9191eaab2..6a591f4d5 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. type ValidatingAdmissionPolicyApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go index ad61dad08..0db11e2b0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicy.go index 9dbdd7dbd..64ac2a936 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // MutatingAdmissionPolicy describes the definition of an admission mutation policy that mutates the object coming into admission chain. type MutatingAdmissionPolicyApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go index 560d1b146..7aeacf4f4 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type MutatingAdmissionPolicyBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the MutatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go index 63bce1540..5668e07c8 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go @@ -33,7 +33,7 @@ import ( // MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object. // Deprecated in v1.16, planned for removal in v1.19. Use admissionregistration.k8s.io/v1 MutatingWebhookConfiguration instead. type MutatingWebhookConfigurationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // webhooks is a list of webhooks and the affected resources and operations. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/namedrulewithoperations.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/namedrulewithoperations.go index 0da66790c..20a327ccc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/namedrulewithoperations.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/namedrulewithoperations.go @@ -31,7 +31,7 @@ type NamedRuleWithOperationsApplyConfiguration struct { // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` // RuleWithOperations is a tuple of Operations and Resources. - v1.RuleWithOperationsApplyConfiguration `json:",inline"` + v1.RuleWithOperationsApplyConfiguration `json:""` } // NamedRuleWithOperationsApplyConfiguration constructs a declarative configuration of the NamedRuleWithOperations type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicy.go index bc1ad6473..e72794335 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicy.go @@ -32,7 +32,7 @@ import ( // // ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it. type ValidatingAdmissionPolicyApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicybinding.go index fd658f9a4..d202ccb73 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingadmissionpolicybinding.go @@ -42,7 +42,7 @@ import ( // Adding/removing policies, bindings, or params can not affect whether a // given (policy, binding, param) combination is within its own CEL budget. type ValidatingAdmissionPolicyBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the desired behavior of the ValidatingAdmissionPolicyBinding. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go index dd53f3b33..cf4440d8c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go @@ -33,7 +33,7 @@ import ( // ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. // Deprecated in v1.16, planned for removal in v1.19. Use admissionregistration.k8s.io/v1 ValidatingWebhookConfiguration instead. type ValidatingWebhookConfigurationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // webhooks is a list of webhooks and the affected resources and operations. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go index 46b2349b1..236f0d665 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go @@ -32,7 +32,7 @@ import ( // // Storage version of a specific resource. type StorageVersionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata. // The name is .. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go index 8a01c0d75..1e4b09060 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go @@ -41,7 +41,7 @@ import ( // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevisionApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go index cc8f33f29..c2c0ded3e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go @@ -32,7 +32,7 @@ import ( // // DaemonSet represents the configuration of a daemon set. type DaemonSetApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go index 771ca0a75..0fa84e16e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go @@ -32,7 +32,7 @@ import ( // // Deployment enables declarative updates for Pods and ReplicaSets. type DeploymentApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go index 63f11a218..689ee1e39 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go @@ -32,7 +32,7 @@ import ( // // ReplicaSet ensures that a specified number of pod replicas are running at any given time. type ReplicaSetApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. // Standard object's metadata. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go index e3dc20463..b07c56514 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go @@ -38,7 +38,7 @@ import ( // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. type StatefulSetApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go index 6d2fdbefc..4b3eb6d25 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go @@ -43,7 +43,7 @@ import ( // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevisionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go index e8195218c..66cfa1fe4 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go @@ -34,7 +34,7 @@ import ( // more information. // Deployment enables declarative updates for Pods and ReplicaSets. type DeploymentApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Specification of the desired behavior of the Deployment. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go index 361ed68a9..392336c03 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go @@ -40,7 +40,7 @@ import ( // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. type StatefulSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines the desired identities of pods in this set. Spec *StatefulSetSpecApplyConfiguration `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go index 3047440ca..250d4ab5d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go @@ -36,7 +36,7 @@ type StatefulSetSpecApplyConfiguration struct { // TODO: Consider a rename of this field. Replicas *int32 `json:"replicas,omitempty"` // selector is a label query over pods that should match the replica count. - // If empty, defaulted to labels on the pod template. + // It must match the pod template's labels. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors Selector *v1.LabelSelectorApplyConfiguration `json:"selector,omitempty"` // template is the object that describes the pod that will be created if diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go index 8ffacf61c..120ebff87 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go @@ -43,7 +43,7 @@ import ( // it may be subject to name and representation changes in future releases, and clients should not // depend on its stability. It is primarily for internal use by controllers. type ControllerRevisionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go index 12b6150a3..f7cdd6e74 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go @@ -34,7 +34,7 @@ import ( // more information. // DaemonSet represents the configuration of a daemon set. type DaemonSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go index 4add5ae25..6d714e194 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go @@ -34,7 +34,7 @@ import ( // more information. // Deployment enables declarative updates for Pods and ReplicaSets. type DeploymentApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Specification of the desired behavior of the Deployment. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go index ea35da04c..d34d5db25 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go @@ -34,7 +34,7 @@ import ( // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. type ReplicaSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go index ca62809fc..42f5cc553 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go @@ -30,7 +30,7 @@ import ( // // Scale represents a scaling request for a resource. type ScaleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go index 5649c1184..fc52c9ccf 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go @@ -40,7 +40,7 @@ import ( // The StatefulSet guarantees that a given network identity will always // map to the same storage identity. type StatefulSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines the desired identities of pods in this set. Spec *StatefulSetSpecApplyConfiguration `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go index f3bd14380..ad35e2884 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go @@ -32,8 +32,8 @@ import ( // // configuration of a horizontal pod autoscaler. type HorizontalPodAutoscalerApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Spec *HorizontalPodAutoscalerSpecApplyConfiguration `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go index bf58371a9..e4f0c72e1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go @@ -23,7 +23,7 @@ package v1 // // specification of a horizontal pod autoscaler. type HorizontalPodAutoscalerSpecApplyConfiguration struct { - // reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption + // scaleTargetRef is the reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption // and will set the desired number of pods by using its Scale subresource. ScaleTargetRef *CrossVersionObjectReferenceApplyConfiguration `json:"scaleTargetRef,omitempty"` // minReplicas is the lower limit for the number of replicas to which the autoscaler diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go index a491c5ac8..ea605a98b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go @@ -29,8 +29,8 @@ import ( // // Scale represents a scaling request for a resource. type ScaleApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Spec *ScaleSpecApplyConfiguration `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go index e001653fc..13de61084 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go @@ -34,7 +34,7 @@ import ( // autoscaler, which automatically manages the replica count of any resource // implementing the scale subresource based on the metrics specified. type HorizontalPodAutoscalerApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go index 75bb49852..9d43ddc1b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go @@ -42,6 +42,10 @@ type HorizontalPodAutoscalerConditionApplyConfiguration struct { // message is a human-readable explanation containing details about // the transition Message *string `json:"message,omitempty"` + // 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. + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` } // HorizontalPodAutoscalerConditionApplyConfiguration constructs a declarative configuration of the HorizontalPodAutoscalerCondition type for use with @@ -89,3 +93,11 @@ func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value s b.Message = &value return b } + +// WithObservedGeneration sets the ObservedGeneration 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 ObservedGeneration field is set to the value of the last call. +func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerConditionApplyConfiguration { + b.ObservedGeneration = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go index cebb11aa6..ad0556b0a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go @@ -36,8 +36,7 @@ import ( // window is chosen. // // The tolerance is applied to the metric values and prevents scaling too -// eagerly for small metric variations. (Note that setting a tolerance requires -// the beta HPAConfigurableTolerance feature gate to be enabled.) +// eagerly for small metric variations. type HPAScalingRulesApplyConfiguration struct { // stabilizationWindowSeconds is the number of seconds for which past recommendations should be // considered while scaling up or scaling down. @@ -62,9 +61,6 @@ type HPAScalingRulesApplyConfiguration struct { // For example, if autoscaling is configured with a memory consumption target of 100Mi, // and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be // triggered when the actual consumption falls below 95Mi or exceeds 101Mi. - // - // This is an beta field and requires the HPAConfigurableTolerance feature - // gate to be enabled. Tolerance *resource.Quantity `json:"tolerance,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go index 7c1a2cb0d..0092a3135 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go @@ -43,7 +43,7 @@ type MetricStatusApplyConfiguration struct { // Kubernetes, and have special scaling options on top of those available // to normal per-pod metrics using the "pods" source. Resource *ResourceMetricStatusApplyConfiguration `json:"resource,omitempty"` - // container resource refers to a resource metric (such as those specified in + // containerResource refers to a resource metric (such as those specified in // requests and limits) known to Kubernetes describing a single container in each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go index 9cd743d3e..609c6e024 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go @@ -32,7 +32,7 @@ type MetricValueStatusApplyConfiguration struct { // averageValue is the current value of the average of the // metric across all relevant pods (as a quantity) AverageValue *resource.Quantity `json:"averageValue,omitempty"` - // currentAverageUtilization is the current value of the average of the + // averageUtilization is the current value of the average of the // resource metric across all relevant pods, represented as a percentage of // the requested value of the resource for the pods. AverageUtilization *int32 `json:"averageUtilization,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go index ec5da782a..dc43e05d9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go @@ -28,7 +28,7 @@ type ObjectMetricStatusApplyConfiguration struct { Metric *MetricIdentifierApplyConfiguration `json:"metric,omitempty"` // current contains the current value for the given metric Current *MetricValueStatusApplyConfiguration `json:"current,omitempty"` - // DescribedObject specifies the descriptions of a object,such as kind,name apiVersion + // describedObject specifies the descriptions of a object,such as kind,name apiVersion DescribedObject *CrossVersionObjectReferenceApplyConfiguration `json:"describedObject,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go index 2fbd48963..d6d8f0a8b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go @@ -32,7 +32,7 @@ import ( // // CronJob represents the configuration of a single cron job. type CronJobApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/job.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/job.go index 02d59f0ec..42da14b3e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/job.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/job.go @@ -32,7 +32,7 @@ import ( // // Job represents the configuration of a single job. type JobApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobschedulingconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobschedulingconfiguration.go new file mode 100644 index 000000000..21845d801 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobschedulingconfiguration.go @@ -0,0 +1,98 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + v1alpha3 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha3" +) + +// JobSchedulingConfigurationApplyConfiguration represents a declarative configuration of the JobSchedulingConfiguration type for use +// with apply. +// +// JobSchedulingConfiguration composes the reusable workload-aware +// scheduling building blocks. +type JobSchedulingConfigurationApplyConfiguration struct { + // SchedulingPolicy defines the scheduling policy for this Job. + // Exactly one of Basic or Gang must be set. + // This field is immutable after creation: the policy may not be added or + // removed. The policy variant (basic/gang) is frozen by hand-written + // validation; only schedulingPolicy.gang.minCount may be changed. + SchedulingPolicy *v1alpha3.WorkloadPodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // SchedulingConstraints defines scheduling constraints (e.g. topology) + // for the Job's pods. + // This field is immutable after creation. + SchedulingConstraints *v1alpha3.WorkloadPodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // DisruptionMode defines the mode in which the Job's pods can be disrupted. + // One of Single, All. + // This field is immutable after creation: it may not be added or removed, + // and the selected mode may not be changed. + DisruptionMode *v1alpha3.WorkloadPodGroupDisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // ResourceClaims defines which ResourceClaims may be shared among Pods in + // the Job. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // At most 4 claims may be set, matching the limit on the resulting PodGroup. + // This list is immutable after creation: entries may neither be added, + // removed, nor modified. + ResourceClaims []v1alpha3.WorkloadPodGroupResourceClaimApplyConfiguration `json:"resourceClaims,omitempty"` +} + +// JobSchedulingConfigurationApplyConfiguration constructs a declarative configuration of the JobSchedulingConfiguration type for use with +// apply. +func JobSchedulingConfiguration() *JobSchedulingConfigurationApplyConfiguration { + return &JobSchedulingConfigurationApplyConfiguration{} +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *JobSchedulingConfigurationApplyConfiguration) WithSchedulingPolicy(value *v1alpha3.WorkloadPodGroupSchedulingPolicyApplyConfiguration) *JobSchedulingConfigurationApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *JobSchedulingConfigurationApplyConfiguration) WithSchedulingConstraints(value *v1alpha3.WorkloadPodGroupSchedulingConstraintsApplyConfiguration) *JobSchedulingConfigurationApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *JobSchedulingConfigurationApplyConfiguration) WithDisruptionMode(value *v1alpha3.WorkloadPodGroupDisruptionModeApplyConfiguration) *JobSchedulingConfigurationApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithResourceClaims adds the given value to the ResourceClaims field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ResourceClaims field. +func (b *JobSchedulingConfigurationApplyConfiguration) WithResourceClaims(values ...*v1alpha3.WorkloadPodGroupResourceClaimApplyConfiguration) *JobSchedulingConfigurationApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResourceClaims") + } + b.ResourceClaims = append(b.ResourceClaims, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go index 81064df75..ea3d54b06 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go @@ -160,6 +160,15 @@ type JobSpecApplyConfiguration struct { // characters as defined by RFC 3986. The value cannot exceed 63 characters. // This field is immutable. ManagedBy *string `json:"managedBy,omitempty"` + // scheduling defines the Workload-aware Scheduling configuration for this Job. + // When set, it specifies the scheduling policy (basic or gang), topology + // constraints, disruption mode, and shared resource claims. + // When omitted, the Job defaults to the basic scheduling policy, which behaves + // as standard pod-by-pod scheduling. + // This field is alpha-level and requires the WorkloadWithJob feature gate. + // This field is immutable, including whether it is set at all, only + // policy.gang.minCount may be changed after creation. + Scheduling *JobSchedulingConfigurationApplyConfiguration `json:"scheduling,omitempty"` } // JobSpecApplyConfiguration constructs a declarative configuration of the JobSpec type for use with @@ -295,3 +304,11 @@ func (b *JobSpecApplyConfiguration) WithManagedBy(value string) *JobSpecApplyCon b.ManagedBy = &value return b } + +// WithScheduling sets the Scheduling 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 Scheduling field is set to the value of the last call. +func (b *JobSpecApplyConfiguration) WithScheduling(value *JobSchedulingConfigurationApplyConfiguration) *JobSpecApplyConfiguration { + b.Scheduling = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go index 0e11fd9be..8260f4b6d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go @@ -69,9 +69,6 @@ type JobStatusApplyConfiguration struct { Failed *int32 `json:"failed,omitempty"` // The number of pods which are terminating (in phase Pending or Running // and have a deletionTimestamp). - // - // This field is beta-level. The job controller populates the field when - // the feature gate JobPodReplacementPolicy is enabled (enabled by default). Terminating *int32 `json:"terminating,omitempty"` // completedIndexes holds the completed indexes when .spec.completionMode = // "Indexed" in a text format. The indexes are represented as decimal integers diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go index f0ab32de4..6b3a33f37 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go @@ -32,7 +32,7 @@ import ( // // CronJob represents the configuration of a single cron job. type CronJobApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go index 0769c9f2c..58bfd595c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go @@ -41,7 +41,7 @@ import ( // (with the "kubernetes.io/kube-apiserver-client" signerName), // or to obtain certificates from custom non-Kubernetes signers. type CertificateSigningRequestApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the certificate request, and is immutable after creation. // Only the request, signerName, expirationSeconds, and usages fields can be set on creation. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundle.go new file mode 100644 index 000000000..387954864 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundle.go @@ -0,0 +1,288 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + certificatesv1 "k8s.io/api/certificates/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ClusterTrustBundleApplyConfiguration represents a declarative configuration of the ClusterTrustBundle type for use +// with apply. +// +// ClusterTrustBundle is a cluster-scoped container for X.509 trust anchors +// (root certificates). +// +// ClusterTrustBundle objects are considered to be readable by any authenticated +// user in the cluster, because they can be mounted by pods using the +// `clusterTrustBundle` projection. All service accounts have read access to +// ClusterTrustBundles by default. Users who only have namespace-level access +// to a cluster can read ClusterTrustBundles by impersonating a serviceaccount +// that they have access to. +// +// It can be optionally associated with a particular signer, in which case it +// contains one valid set of trust anchors for that signer. Signers may have +// multiple associated ClusterTrustBundles; each is an independent set of trust +// anchors for that signer. Admission control is used to enforce that only users +// with permissions on the signer can create or modify the corresponding bundle. +type ClusterTrustBundleApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:""` + // metadata contains the object metadata. + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec contains the signer (if any) and trust anchors. + Spec *ClusterTrustBundleSpecApplyConfiguration `json:"spec,omitempty"` +} + +// ClusterTrustBundle constructs a declarative configuration of the ClusterTrustBundle type for use with +// apply. +func ClusterTrustBundle(name string) *ClusterTrustBundleApplyConfiguration { + b := &ClusterTrustBundleApplyConfiguration{} + b.WithName(name) + b.WithKind("ClusterTrustBundle") + b.WithAPIVersion("certificates.k8s.io/v1") + return b +} + +// ExtractClusterTrustBundleFrom extracts the applied configuration owned by fieldManager from +// clusterTrustBundle for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// clusterTrustBundle must be a unmodified ClusterTrustBundle API object that was retrieved from the Kubernetes API. +// ExtractClusterTrustBundleFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractClusterTrustBundleFrom(clusterTrustBundle *certificatesv1.ClusterTrustBundle, fieldManager string, subresource string) (*ClusterTrustBundleApplyConfiguration, error) { + b := &ClusterTrustBundleApplyConfiguration{} + err := managedfields.ExtractInto(clusterTrustBundle, internal.Parser().Type("io.k8s.api.certificates.v1.ClusterTrustBundle"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(clusterTrustBundle.Name) + + b.WithKind("ClusterTrustBundle") + b.WithAPIVersion("certificates.k8s.io/v1") + return b, nil +} + +// ExtractClusterTrustBundle extracts the applied configuration owned by fieldManager from +// clusterTrustBundle. If no managedFields are found in clusterTrustBundle for fieldManager, a +// ClusterTrustBundleApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// clusterTrustBundle must be a unmodified ClusterTrustBundle API object that was retrieved from the Kubernetes API. +// ExtractClusterTrustBundle provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractClusterTrustBundle(clusterTrustBundle *certificatesv1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error) { + return ExtractClusterTrustBundleFrom(clusterTrustBundle, fieldManager, "") +} + +func (b ClusterTrustBundleApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithKind(value string) *ClusterTrustBundleApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithAPIVersion(value string) *ClusterTrustBundleApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithName(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithGenerateName(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithNamespace(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithUID(value types.UID) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithResourceVersion(value string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithGeneration(value int64) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ClusterTrustBundleApplyConfiguration) WithLabels(entries map[string]string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ClusterTrustBundleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ClusterTrustBundleApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ClusterTrustBundleApplyConfiguration) WithFinalizers(values ...string) *ClusterTrustBundleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ClusterTrustBundleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *ClusterTrustBundleApplyConfiguration) WithSpec(value *ClusterTrustBundleSpecApplyConfiguration) *ClusterTrustBundleApplyConfiguration { + b.Spec = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *ClusterTrustBundleApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *ClusterTrustBundleApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ClusterTrustBundleApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *ClusterTrustBundleApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundlespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundlespec.go new file mode 100644 index 000000000..5b7bb1038 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/clustertrustbundlespec.go @@ -0,0 +1,79 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// ClusterTrustBundleSpecApplyConfiguration represents a declarative configuration of the ClusterTrustBundleSpec type for use +// with apply. +// +// ClusterTrustBundleSpec contains the signer and trust anchors. +type ClusterTrustBundleSpecApplyConfiguration struct { + // signerName indicates the associated signer, if any. + // + // In order to create or update a ClusterTrustBundle that sets signerName, + // you must have the following cluster-scoped permission: + // group=certificates.k8s.io resource=signers resourceName= + // verb=attest. + // + // If signerName is not empty, then the ClusterTrustBundle object must be + // named with the signer name as a prefix (translating slashes to colons). + // For example, for the signer name `example.com/foo`, valid + // ClusterTrustBundle object names include `example.com:foo:abc` and + // `example.com:foo:v1`. + // + // If signerName is empty, then the ClusterTrustBundle object's name must + // not have such a prefix. + // + // List/watch requests for ClusterTrustBundles can filter on this field + // using a `spec.signerName=NAME` field selector. + SignerName *string `json:"signerName,omitempty"` + // trustBundle contains the individual X.509 trust anchors for this + // bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates. + // + // The data must consist only of PEM certificate blocks that parse as valid + // X.509 certificates. Each certificate must include a basic constraints + // extension with the CA bit set. The API server will reject objects that + // contain duplicate certificates, or that use PEM block headers. + // + // Users of ClusterTrustBundles, including Kubelet, are free to reorder and + // deduplicate certificate blocks in this file according to their own logic, + // as well as to drop PEM block headers and inter-block data. + TrustBundle *string `json:"trustBundle,omitempty"` +} + +// ClusterTrustBundleSpecApplyConfiguration constructs a declarative configuration of the ClusterTrustBundleSpec type for use with +// apply. +func ClusterTrustBundleSpec() *ClusterTrustBundleSpecApplyConfiguration { + return &ClusterTrustBundleSpecApplyConfiguration{} +} + +// WithSignerName sets the SignerName 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 SignerName field is set to the value of the last call. +func (b *ClusterTrustBundleSpecApplyConfiguration) WithSignerName(value string) *ClusterTrustBundleSpecApplyConfiguration { + b.SignerName = &value + return b +} + +// WithTrustBundle sets the TrustBundle 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 TrustBundle field is set to the value of the last call. +func (b *ClusterTrustBundleSpecApplyConfiguration) WithTrustBundle(value string) *ClusterTrustBundleSpecApplyConfiguration { + b.TrustBundle = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequest.go new file mode 100644 index 000000000..41ecc78d8 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequest.go @@ -0,0 +1,295 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + certificatesv1 "k8s.io/api/certificates/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// PodCertificateRequestApplyConfiguration represents a declarative configuration of the PodCertificateRequest type for use +// with apply. +// +// PodCertificateRequest encodes a pod requesting a certificate from a given +// signer. +// +// Kubelets use this API to implement podCertificate projected volumes +type PodCertificateRequestApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:""` + // metadata contains the object metadata. + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec contains the details about the certificate being requested. + Spec *PodCertificateRequestSpecApplyConfiguration `json:"spec,omitempty"` + // status contains the issued certificate, and a standard set of conditions. + Status *PodCertificateRequestStatusApplyConfiguration `json:"status,omitempty"` +} + +// PodCertificateRequest constructs a declarative configuration of the PodCertificateRequest type for use with +// apply. +func PodCertificateRequest(name, namespace string) *PodCertificateRequestApplyConfiguration { + b := &PodCertificateRequestApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("PodCertificateRequest") + b.WithAPIVersion("certificates.k8s.io/v1") + return b +} + +// ExtractPodCertificateRequestFrom extracts the applied configuration owned by fieldManager from +// podCertificateRequest for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// podCertificateRequest must be a unmodified PodCertificateRequest API object that was retrieved from the Kubernetes API. +// ExtractPodCertificateRequestFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractPodCertificateRequestFrom(podCertificateRequest *certificatesv1.PodCertificateRequest, fieldManager string, subresource string) (*PodCertificateRequestApplyConfiguration, error) { + b := &PodCertificateRequestApplyConfiguration{} + err := managedfields.ExtractInto(podCertificateRequest, internal.Parser().Type("io.k8s.api.certificates.v1.PodCertificateRequest"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(podCertificateRequest.Name) + b.WithNamespace(podCertificateRequest.Namespace) + + b.WithKind("PodCertificateRequest") + b.WithAPIVersion("certificates.k8s.io/v1") + return b, nil +} + +// ExtractPodCertificateRequest extracts the applied configuration owned by fieldManager from +// podCertificateRequest. If no managedFields are found in podCertificateRequest for fieldManager, a +// PodCertificateRequestApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// podCertificateRequest must be a unmodified PodCertificateRequest API object that was retrieved from the Kubernetes API. +// ExtractPodCertificateRequest provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractPodCertificateRequest(podCertificateRequest *certificatesv1.PodCertificateRequest, fieldManager string) (*PodCertificateRequestApplyConfiguration, error) { + return ExtractPodCertificateRequestFrom(podCertificateRequest, fieldManager, "") +} + +// ExtractPodCertificateRequestStatus extracts the applied configuration owned by fieldManager from +// podCertificateRequest for the status subresource. +func ExtractPodCertificateRequestStatus(podCertificateRequest *certificatesv1.PodCertificateRequest, fieldManager string) (*PodCertificateRequestApplyConfiguration, error) { + return ExtractPodCertificateRequestFrom(podCertificateRequest, fieldManager, "status") +} + +func (b PodCertificateRequestApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithKind(value string) *PodCertificateRequestApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithAPIVersion(value string) *PodCertificateRequestApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithName(value string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithGenerateName(value string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithNamespace(value string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithUID(value types.UID) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithResourceVersion(value string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithGeneration(value int64) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *PodCertificateRequestApplyConfiguration) WithLabels(entries map[string]string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *PodCertificateRequestApplyConfiguration) WithAnnotations(entries map[string]string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *PodCertificateRequestApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *PodCertificateRequestApplyConfiguration) WithFinalizers(values ...string) *PodCertificateRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *PodCertificateRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithSpec(value *PodCertificateRequestSpecApplyConfiguration) *PodCertificateRequestApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *PodCertificateRequestApplyConfiguration) WithStatus(value *PodCertificateRequestStatusApplyConfiguration) *PodCertificateRequestApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *PodCertificateRequestApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *PodCertificateRequestApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *PodCertificateRequestApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *PodCertificateRequestApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequestspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequestspec.go new file mode 100644 index 000000000..a952f1652 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequestspec.go @@ -0,0 +1,189 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + types "k8s.io/apimachinery/pkg/types" +) + +// PodCertificateRequestSpecApplyConfiguration represents a declarative configuration of the PodCertificateRequestSpec type for use +// with apply. +// +// PodCertificateRequestSpec describes the certificate request. All fields are +// immutable after creation. +type PodCertificateRequestSpecApplyConfiguration struct { + // signerName indicates the requested signer. + // + // All signer names beginning with `kubernetes.io` are reserved for use by + // the Kubernetes project. There is currently one well-known signer + // documented by the Kubernetes project, + // `kubernetes.io/kube-apiserver-client-pod`, which will issue client + // certificates understood by kube-apiserver. It is currently + // unimplemented. + SignerName *string `json:"signerName,omitempty"` + // podName is the name of the pod into which the certificate will be mounted. + PodName *string `json:"podName,omitempty"` + // podUID is the UID of the pod into which the certificate will be mounted. + PodUID *types.UID `json:"podUID,omitempty"` + // serviceAccountName is the name of the service account the pod is running as. + ServiceAccountName *string `json:"serviceAccountName,omitempty"` + // serviceAccountUID is the UID of the service account the pod is running as. + ServiceAccountUID *types.UID `json:"serviceAccountUID,omitempty"` + // nodeName is the name of the node the pod is assigned to. + NodeName *types.NodeName `json:"nodeName,omitempty"` + // nodeUID is the UID of the node the pod is assigned to. + NodeUID *types.UID `json:"nodeUID,omitempty"` + // maxExpirationSeconds is the maximum lifetime permitted for the + // certificate. + // + // If omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver + // will reject values shorter than 3600 (1 hour). The maximum allowable + // value is 7862400 (91 days). + // + // The signer implementation is then free to issue a certificate with any + // lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 + // seconds (1 hour). This constraint is enforced by kube-apiserver. + // `kubernetes.io` signers will never issue certificates with a lifetime + // longer than 24 hours. + MaxExpirationSeconds *int32 `json:"maxExpirationSeconds,omitempty"` + // A PKCS#10 certificate signing request (DER-serialized) generated by + // Kubelet using the subject private key. + // + // Most signer implementations will ignore the contents of the CSR except to + // extract the subject public key. The API server automatically verifies the + // CSR signature during admission, so the signer does not need to repeat the + // verification. CSRs generated by kubelet are completely empty. + // + // The subject public key must be one of RSA3072, RSA4096, ECDSAP256, + // ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in + // the future. + // + // Signer implementations do not need to support all key types supported by + // kube-apiserver and kubelet. If a signer does not support the key type + // used for a given PodCertificateRequest, it must deny the request by + // setting a status.conditions entry with a type of "Denied" and a reason of + // "UnsupportedKeyType". It may also suggest a key type that it does support + // in the message field. + StubPKCS10Request []byte `json:"stubPKCS10Request,omitempty"` + // unverifiedUserAnnotations allow pod authors to pass additional information to + // the signer implementation. Kubernetes does not restrict or validate this + // metadata in any way. + // + // Entries are subject to the same validation as object metadata annotations, + // with the addition that all keys must be domain-prefixed. No restrictions + // are placed on values, except an overall size limitation on the entire field. + // + // Signers should document the keys and values they support. Signers should + // deny requests that contain keys they do not recognize. + UnverifiedUserAnnotations map[string]string `json:"unverifiedUserAnnotations,omitempty"` +} + +// PodCertificateRequestSpecApplyConfiguration constructs a declarative configuration of the PodCertificateRequestSpec type for use with +// apply. +func PodCertificateRequestSpec() *PodCertificateRequestSpecApplyConfiguration { + return &PodCertificateRequestSpecApplyConfiguration{} +} + +// WithSignerName sets the SignerName 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 SignerName field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithSignerName(value string) *PodCertificateRequestSpecApplyConfiguration { + b.SignerName = &value + return b +} + +// WithPodName sets the PodName 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 PodName field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithPodName(value string) *PodCertificateRequestSpecApplyConfiguration { + b.PodName = &value + return b +} + +// WithPodUID sets the PodUID 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 PodUID field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithPodUID(value types.UID) *PodCertificateRequestSpecApplyConfiguration { + b.PodUID = &value + return b +} + +// WithServiceAccountName sets the ServiceAccountName 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 ServiceAccountName field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithServiceAccountName(value string) *PodCertificateRequestSpecApplyConfiguration { + b.ServiceAccountName = &value + return b +} + +// WithServiceAccountUID sets the ServiceAccountUID 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 ServiceAccountUID field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithServiceAccountUID(value types.UID) *PodCertificateRequestSpecApplyConfiguration { + b.ServiceAccountUID = &value + return b +} + +// WithNodeName sets the NodeName 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 NodeName field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithNodeName(value types.NodeName) *PodCertificateRequestSpecApplyConfiguration { + b.NodeName = &value + return b +} + +// WithNodeUID sets the NodeUID 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 NodeUID field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithNodeUID(value types.UID) *PodCertificateRequestSpecApplyConfiguration { + b.NodeUID = &value + return b +} + +// WithMaxExpirationSeconds sets the MaxExpirationSeconds 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 MaxExpirationSeconds field is set to the value of the last call. +func (b *PodCertificateRequestSpecApplyConfiguration) WithMaxExpirationSeconds(value int32) *PodCertificateRequestSpecApplyConfiguration { + b.MaxExpirationSeconds = &value + return b +} + +// WithStubPKCS10Request adds the given value to the StubPKCS10Request field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the StubPKCS10Request field. +func (b *PodCertificateRequestSpecApplyConfiguration) WithStubPKCS10Request(values ...byte) *PodCertificateRequestSpecApplyConfiguration { + for i := range values { + b.StubPKCS10Request = append(b.StubPKCS10Request, values[i]) + } + return b +} + +// WithUnverifiedUserAnnotations puts the entries into the UnverifiedUserAnnotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the UnverifiedUserAnnotations field, +// overwriting an existing map entries in UnverifiedUserAnnotations field with the same key. +func (b *PodCertificateRequestSpecApplyConfiguration) WithUnverifiedUserAnnotations(entries map[string]string) *PodCertificateRequestSpecApplyConfiguration { + if b.UnverifiedUserAnnotations == nil && len(entries) > 0 { + b.UnverifiedUserAnnotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.UnverifiedUserAnnotations[k] = v + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequeststatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequeststatus.go new file mode 100644 index 000000000..e10dd930a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1/podcertificaterequeststatus.go @@ -0,0 +1,133 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// PodCertificateRequestStatusApplyConfiguration represents a declarative configuration of the PodCertificateRequestStatus type for use +// with apply. +// +// PodCertificateRequestStatus describes the status of the request, and holds +// the certificate data if the request is issued. +type PodCertificateRequestStatusApplyConfiguration struct { + // conditions applied to the request. + // + // The types "Issued", "Denied", and "Failed" have special handling. At + // most one of these conditions may be present, and they must have status + // "True". + // + // If the request is denied with `Reason=UnsupportedKeyType`, the signer may + // suggest a key type that will work in the message field. + Conditions []metav1.ConditionApplyConfiguration `json:"conditions,omitempty"` + // certificateChain is populated with an issued certificate by the signer. + // This field is set via the /status subresource. Once populated, this field + // is immutable. + // + // If the certificate signing request is denied, a condition of type + // "Denied" is added and this field remains empty. If the signer cannot + // issue the certificate, a condition of type "Failed" is added and this + // field remains empty. + // + // Validation requirements: + // 1. certificateChain must consist of one or more PEM-formatted certificates. + // 2. Each entry must be a valid PEM-wrapped, DER-encoded ASN.1 Certificate as + // described in section 4 of RFC5280. + // + // If more than one block is present, and the definition of the requested + // spec.signerName does not indicate otherwise, the first block is the + // issued certificate, and subsequent blocks should be treated as + // intermediate certificates and presented in TLS handshakes. When + // projecting the chain into a pod volume, kubelet will drop any data + // in-between the PEM blocks, as well as any PEM block headers. + CertificateChain *string `json:"certificateChain,omitempty"` + // notBefore is the time at which the certificate becomes valid. The value + // must be the same as the notBefore value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + NotBefore *apismetav1.Time `json:"notBefore,omitempty"` + // beginRefreshAt is the time at which the kubelet should begin trying to + // refresh the certificate. This field is set via the /status subresource, + // and must be set at the same time as certificateChain. Once populated, + // this field is immutable. + // + // This field is only a hint. Kubelet may start refreshing before or after + // this time if necessary. + BeginRefreshAt *apismetav1.Time `json:"beginRefreshAt,omitempty"` + // notAfter is the time at which the certificate expires. The value must be + // the same as the notAfter value in the leaf certificate in + // certificateChain. This field is set via the /status subresource. Once + // populated, it is immutable. The signer must set this field at the same + // time it sets certificateChain. + NotAfter *apismetav1.Time `json:"notAfter,omitempty"` +} + +// PodCertificateRequestStatusApplyConfiguration constructs a declarative configuration of the PodCertificateRequestStatus type for use with +// apply. +func PodCertificateRequestStatus() *PodCertificateRequestStatusApplyConfiguration { + return &PodCertificateRequestStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *PodCertificateRequestStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *PodCertificateRequestStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithCertificateChain sets the CertificateChain 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 CertificateChain field is set to the value of the last call. +func (b *PodCertificateRequestStatusApplyConfiguration) WithCertificateChain(value string) *PodCertificateRequestStatusApplyConfiguration { + b.CertificateChain = &value + return b +} + +// WithNotBefore sets the NotBefore 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 NotBefore field is set to the value of the last call. +func (b *PodCertificateRequestStatusApplyConfiguration) WithNotBefore(value apismetav1.Time) *PodCertificateRequestStatusApplyConfiguration { + b.NotBefore = &value + return b +} + +// WithBeginRefreshAt sets the BeginRefreshAt 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 BeginRefreshAt field is set to the value of the last call. +func (b *PodCertificateRequestStatusApplyConfiguration) WithBeginRefreshAt(value apismetav1.Time) *PodCertificateRequestStatusApplyConfiguration { + b.BeginRefreshAt = &value + return b +} + +// WithNotAfter sets the NotAfter 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 NotAfter field is set to the value of the last call. +func (b *PodCertificateRequestStatusApplyConfiguration) WithNotAfter(value apismetav1.Time) *PodCertificateRequestStatusApplyConfiguration { + b.NotAfter = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go index 9c26cdb91..7fdaae5b0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go @@ -40,13 +40,13 @@ import ( // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users // with permissions on the signer can create or modify the corresponding bundle. type ClusterTrustBundleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata contains the object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the signer (if any) and trust anchors. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go index 05e16d205..256e0f504 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go @@ -32,7 +32,7 @@ import ( // // Describes a certificate signing request type CertificateSigningRequestApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the certificate request, and is immutable after creation. // Only the request, signerName, expirationSeconds, and usages fields can be set on creation. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/clustertrustbundle.go index 7f8be00ce..5c70207c6 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/clustertrustbundle.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/clustertrustbundle.go @@ -40,13 +40,13 @@ import ( // to a cluster can read ClusterTrustBundles by impersonating a serviceaccount // that they have access to. // -// It can be optionally associated with a particular assigner, in which case it +// It can be optionally associated with a particular signer, in which case it // contains one valid set of trust anchors for that signer. Signers may have // multiple associated ClusterTrustBundles; each is an independent set of trust // anchors for that signer. Admission control is used to enforce that only users // with permissions on the signer can create or modify the corresponding bundle. type ClusterTrustBundleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata contains the object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the signer (if any) and trust anchors. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/podcertificaterequest.go index 447172552..bf12e23c0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/podcertificaterequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/certificates/v1beta1/podcertificaterequest.go @@ -35,7 +35,7 @@ import ( // // Kubelets use this API to implement podCertificate projected volumes type PodCertificateRequestApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // metadata contains the object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the details about the certificate being requested. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go index de1833975..4dce4ca8a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go @@ -32,7 +32,8 @@ import ( // // Lease defines a lease concept. type LeaseApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the specification of the Lease. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go index 4dca58e2e..05470ca61 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go @@ -44,11 +44,11 @@ type LeaseSpecApplyConfiguration struct { // leaseTransitions is the number of transitions of a lease between // holders. LeaseTransitions *int32 `json:"leaseTransitions,omitempty"` - // Strategy indicates the strategy for picking the leader for coordinated leader election. + // strategy indicates the strategy for picking the leader for coordinated leader election. // If the field is not specified, there is no active coordination for this lease. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. Strategy *coordinationv1.CoordinatedLeaseStrategy `json:"strategy,omitempty"` - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. // This field can only be set if Strategy is also set. PreferredHolder *string `json:"preferredHolder,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidate.go index 73150cb43..25a2a000d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidate.go @@ -33,7 +33,8 @@ import ( // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. type LeaseCandidateApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the specification of the Lease. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidatespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidatespec.go index 44a2db06f..e6ab4897d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidatespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1alpha2/leasecandidatespec.go @@ -28,15 +28,15 @@ import ( // // LeaseCandidateSpec is a specification of a Lease. type LeaseCandidateSpecApplyConfiguration struct { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // This field is immutable. LeaseName *string `json:"leaseName,omitempty"` - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. PingTime *v1.MicroTime `json:"pingTime,omitempty"` - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -44,14 +44,14 @@ type LeaseCandidateSpecApplyConfiguration struct { // since the last renew. The PingTime field is updated regularly to prevent // garbage collection for still active LeaseCandidates. RenewTime *v1.MicroTime `json:"renewTime,omitempty"` - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. BinaryVersion *string `json:"binaryVersion,omitempty"` - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" EmulationVersion *string `json:"emulationVersion,omitempty"` - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go index 38263059a..dccfdca8a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go @@ -32,7 +32,8 @@ import ( // // Lease defines a lease concept. type LeaseApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the specification of the Lease. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidate.go index 4670d9d2b..bfd45d103 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidate.go @@ -33,7 +33,8 @@ import ( // LeaseCandidate defines a candidate for a Lease object. // Candidates are created such that coordinated leader election will pick the best leader from the list of candidates. type LeaseCandidateApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec contains the specification of the Lease. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidatespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidatespec.go index 6b146dc49..3aed4ccc2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidatespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasecandidatespec.go @@ -28,17 +28,17 @@ import ( // // LeaseCandidateSpec is a specification of a Lease. type LeaseCandidateSpecApplyConfiguration struct { - // LeaseName is the name of the lease for which this candidate is contending. + // leaseName is the name of the lease for which this candidate is contending. // The limits on this field are the same as on Lease.name. Multiple lease candidates // may reference the same Lease.name. // This field is immutable. LeaseName *string `json:"leaseName,omitempty"` - // PingTime is the last time that the server has requested the LeaseCandidate + // pingTime is the last time that the server has requested the LeaseCandidate // to renew. It is only done during leader election to check if any // LeaseCandidates have become ineligible. When PingTime is updated, the // LeaseCandidate will respond by updating RenewTime. PingTime *v1.MicroTime `json:"pingTime,omitempty"` - // RenewTime is the time that the LeaseCandidate was last updated. + // renewTime is the time that the LeaseCandidate was last updated. // Any time a Lease needs to do leader election, the PingTime field // is updated to signal to the LeaseCandidate that they should update // the RenewTime. @@ -46,14 +46,14 @@ type LeaseCandidateSpecApplyConfiguration struct { // since the last renew. The PingTime field is updated regularly to prevent // garbage collection for still active LeaseCandidates. RenewTime *v1.MicroTime `json:"renewTime,omitempty"` - // BinaryVersion is the binary version. It must be in a semver format without leading `v`. + // binaryVersion is the binary version. It must be in a semver format without leading `v`. // This field is required. BinaryVersion *string `json:"binaryVersion,omitempty"` - // EmulationVersion is the emulation version. It must be in a semver format without leading `v`. + // emulationVersion is the emulation version. It must be in a semver format without leading `v`. // EmulationVersion must be less than or equal to BinaryVersion. // This field is required when strategy is "OldestEmulationVersion" EmulationVersion *string `json:"emulationVersion,omitempty"` - // Strategy is the strategy that coordinated leader election will use for picking the leader. + // strategy is the strategy that coordinated leader election will use for picking the leader. // If multiple candidates for the same Lease return different strategies, the strategy provided // by the candidate with the latest BinaryVersion will be used. If there is still conflict, // this is a user error and coordinated leader election will not operate the Lease until resolved. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go index db40b8359..ec4ee1190 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go @@ -44,10 +44,10 @@ type LeaseSpecApplyConfiguration struct { // leaseTransitions is the number of transitions of a lease between // holders. LeaseTransitions *int32 `json:"leaseTransitions,omitempty"` - // Strategy indicates the strategy for picking the leader for coordinated leader election + // strategy indicates the strategy for picking the leader for coordinated leader election. // (Alpha) Using this field requires the CoordinatedLeaderElection feature gate to be enabled. Strategy *coordinationv1.CoordinatedLeaseStrategy `json:"strategy,omitempty"` - // PreferredHolder signals to a lease holder that the lease has a + // preferredHolder signals to a lease holder that the lease has a // more optimal holder and should be given up. PreferredHolder *string `json:"preferredHolder,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/clustertrustbundleprojection.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/clustertrustbundleprojection.go index 00eec6b37..8964d84f2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/clustertrustbundleprojection.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/clustertrustbundleprojection.go @@ -49,6 +49,10 @@ type ClusterTrustBundleProjectionApplyConfiguration struct { Optional *bool `json:"optional,omitempty"` // Relative path from the volume root to write the bundle. Path *string `json:"path,omitempty"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + User *int64 `json:"user,omitempty"` } // ClusterTrustBundleProjectionApplyConfiguration constructs a declarative configuration of the ClusterTrustBundleProjection type for use with @@ -96,3 +100,11 @@ func (b *ClusterTrustBundleProjectionApplyConfiguration) WithPath(value string) b.Path = &value return b } + +// WithUser sets the User 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 User field is set to the value of the last call. +func (b *ClusterTrustBundleProjectionApplyConfiguration) WithUser(value int64) *ClusterTrustBundleProjectionApplyConfiguration { + b.User = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go index 5b9b7f32c..b356d1ee3 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go @@ -33,7 +33,7 @@ import ( // ComponentStatus (and ComponentStatusList) holds the cluster validation info. // Deprecated: This API is deprecated in v1.19+ type ComponentStatusApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmap.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmap.go index d63848204..6a181e325 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmap.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmap.go @@ -32,7 +32,7 @@ import ( // // ConfigMap holds configuration data for pods to consume. type ConfigMapApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` @@ -54,6 +54,8 @@ type ConfigMapApplyConfiguration struct { // the Data field, this is enforced during validation process. // Using this field will require 1.10+ apiserver and // kubelet. + // Note: BinaryData keys are not currently propagated to container env vars + // via ConfigMapKeyRef or ConfigMapRef env sources; only Data keys are used. BinaryData map[string][]byte `json:"binaryData,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go index c2c067b2c..b50b3f11d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go @@ -26,9 +26,10 @@ package v1 // // The contents of the target ConfigMap's Data field will represent the // key-value pairs as environment variables. +// Keys in the BinaryData field are not currently propagated to container env vars. type ConfigMapEnvSourceApplyConfiguration struct { // The ConfigMap to select from. - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // Specify whether the ConfigMap must be defined Optional *bool `json:"optional,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go index 415edded5..384db766a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go @@ -24,8 +24,9 @@ package v1 // Selects a key from a ConfigMap. type ConfigMapKeySelectorApplyConfiguration struct { // The ConfigMap to select from. - LocalObjectReferenceApplyConfiguration `json:",inline"` - // The key to select. + LocalObjectReferenceApplyConfiguration `json:""` + // The key to select from the ConfigMap's Data field. + // Keys in the BinaryData field are not currently propagated to container env vars. Key *string `json:"key,omitempty"` // Specify whether the ConfigMap or its key must be defined Optional *bool `json:"optional,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go index 0357ca998..9af0ca301 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go @@ -29,7 +29,7 @@ package v1 // Note that this is identical to a configmap volume source without the default // mode. type ConfigMapProjectionApplyConfiguration struct { - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // items if unspecified, each key-value pair in the Data field of the referenced // ConfigMap will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go index b8a6a333f..158857b8b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go @@ -28,7 +28,7 @@ package v1 // the items element is populated with specific mappings of keys to paths. // ConfigMap volumes support ownership management and SELinux relabeling. type ConfigMapVolumeSourceApplyConfiguration struct { - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // items if unspecified, each key-value pair in the Data field of the referenced // ConfigMap will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be @@ -47,6 +47,10 @@ type ConfigMapVolumeSourceApplyConfiguration struct { DefaultMode *int32 `json:"defaultMode,omitempty"` // optional specify whether the ConfigMap or its keys must be defined Optional *bool `json:"optional,omitempty"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + DefaultUser *int64 `json:"defaultUser,omitempty"` } // ConfigMapVolumeSourceApplyConfiguration constructs a declarative configuration of the ConfigMapVolumeSource type for use with @@ -91,3 +95,11 @@ func (b *ConfigMapVolumeSourceApplyConfiguration) WithOptional(value bool) *Conf b.Optional = &value return b } + +// WithDefaultUser sets the DefaultUser 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 DefaultUser field is set to the value of the last call. +func (b *ConfigMapVolumeSourceApplyConfiguration) WithDefaultUser(value int64) *ConfigMapVolumeSourceApplyConfiguration { + b.DefaultUser = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go index 9028f3133..99eb736fa 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go @@ -37,6 +37,10 @@ type DownwardAPIVolumeFileApplyConfiguration struct { // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. Mode *int32 `json:"mode,omitempty"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + User *int64 `json:"user,omitempty"` } // DownwardAPIVolumeFileApplyConfiguration constructs a declarative configuration of the DownwardAPIVolumeFile type for use with @@ -76,3 +80,11 @@ func (b *DownwardAPIVolumeFileApplyConfiguration) WithMode(value int32) *Downwar b.Mode = &value return b } + +// WithUser sets the User 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 User field is set to the value of the last call. +func (b *DownwardAPIVolumeFileApplyConfiguration) WithUser(value int64) *DownwardAPIVolumeFileApplyConfiguration { + b.User = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go index 42e726689..308b05780 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go @@ -35,6 +35,10 @@ type DownwardAPIVolumeSourceApplyConfiguration struct { // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. DefaultMode *int32 `json:"defaultMode,omitempty"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + DefaultUser *int64 `json:"defaultUser,omitempty"` } // DownwardAPIVolumeSourceApplyConfiguration constructs a declarative configuration of the DownwardAPIVolumeSource type for use with @@ -63,3 +67,11 @@ func (b *DownwardAPIVolumeSourceApplyConfiguration) WithDefaultMode(value int32) b.DefaultMode = &value return b } + +// WithDefaultUser sets the DefaultUser 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 DefaultUser field is set to the value of the last call. +func (b *DownwardAPIVolumeSourceApplyConfiguration) WithDefaultUser(value int64) *DownwardAPIVolumeSourceApplyConfiguration { + b.DefaultUser = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go index 97f71e8d2..b79a874d6 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go @@ -41,6 +41,15 @@ type EmptyDirVolumeSourceApplyConfiguration struct { // The default is nil which means that the limit is undefined. // More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir SizeLimit *resource.Quantity `json:"sizeLimit,omitempty"` + // mode specifies the permission bits for the emptyDir directory, in numeric + // notation (e.g., 0755, 01777). Must be a value between 0000 and 01777. + // If not specified, defaults to 0777. + // This might be in conflict with other options that affect the file + // mode, like fsGroup. If fsGroup is specified, the fsGroup permissions + // will override the mode specified here. + // This field has no effect on Windows. + // This field is alpha and requires EmptyDirVolumeMode featuregate to be enabled. + Mode *int32 `json:"mode,omitempty"` } // EmptyDirVolumeSourceApplyConfiguration constructs a declarative configuration of the EmptyDirVolumeSource type for use with @@ -64,3 +73,11 @@ func (b *EmptyDirVolumeSourceApplyConfiguration) WithSizeLimit(value resource.Qu b.SizeLimit = &value return b } + +// WithMode sets the Mode 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 Mode field is set to the value of the last call. +func (b *EmptyDirVolumeSourceApplyConfiguration) WithMode(value int32) *EmptyDirVolumeSourceApplyConfiguration { + b.Mode = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go index a13cd30e8..45861f369 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go @@ -49,7 +49,7 @@ import ( // // Deprecated: This API is deprecated in v1.33+. Use discoveryv1.EndpointSlice. type EndpointsApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go index 43d97a6ef..3b3d1698c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go @@ -38,7 +38,7 @@ type EphemeralContainerApplyConfiguration struct { // specific to ephemeral containers. Fields in common with Container are in the // following inlined struct so than an EphemeralContainer may easily be converted // to a Container. - EphemeralContainerCommonApplyConfiguration `json:",inline"` + EphemeralContainerCommonApplyConfiguration `json:""` // If set, the name of the container from PodSpec that this ephemeral container targets. // The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. // If not set then the ephemeral container uses the namespaces configured in the Pod spec. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/event.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/event.go index 676a719b2..80f48d4ee 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/event.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/event.go @@ -37,7 +37,7 @@ import ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type EventApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/evictionresponder.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/evictionresponder.go new file mode 100644 index 000000000..9decf94dd --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/evictionresponder.go @@ -0,0 +1,70 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// EvictionResponderApplyConfiguration represents a declarative configuration of the EvictionResponder type for use +// with apply. +// +// EvictionResponder allows you to specify the responder reacting to an Eviction. +// Responders should observe and communicate through the Eviction Resource API to help with +// the graceful eviction of a target (e.g. termination of a pod). +type EvictionResponderApplyConfiguration struct { + // name allows you to identify the responder responding to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field must be unique for each responder. + // This field is required. + Name *string `json:"name,omitempty"` + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required. + Priority *int32 `json:"priority,omitempty"` +} + +// EvictionResponderApplyConfiguration constructs a declarative configuration of the EvictionResponder type for use with +// apply. +func EvictionResponder() *EvictionResponderApplyConfiguration { + return &EvictionResponderApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *EvictionResponderApplyConfiguration) WithName(value string) *EvictionResponderApplyConfiguration { + b.Name = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *EvictionResponderApplyConfiguration) WithPriority(value int32) *EvictionResponderApplyConfiguration { + b.Priority = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go index 40f5f9ecf..05534f6bc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go @@ -18,6 +18,10 @@ limitations under the License. package v1 +import ( + corev1 "k8s.io/api/core/v1" +) + // GRPCActionApplyConfiguration represents a declarative configuration of the GRPCAction type for use // with apply. // @@ -30,6 +34,11 @@ type GRPCActionApplyConfiguration struct { // // If this is not specified, the default behavior is defined by gRPC. Service *string `json:"service,omitempty"` + // mode specifies the connection mode for the gRPC health probe. + // Set to "TLS" to use TLS without certificate verification. + // Set to "Plaintext" to use a plaintext (insecure) connection explicitly. + // If not specified, the probe uses a plaintext (insecure) connection. + Mode *corev1.GRPCProbeMode `json:"mode,omitempty"` } // GRPCActionApplyConfiguration constructs a declarative configuration of the GRPCAction type for use with @@ -53,3 +62,11 @@ func (b *GRPCActionApplyConfiguration) WithService(value string) *GRPCActionAppl b.Service = &value return b } + +// WithMode sets the Mode 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 Mode field is set to the value of the last call. +func (b *GRPCActionApplyConfiguration) WithMode(value corev1.GRPCProbeMode) *GRPCActionApplyConfiguration { + b.Mode = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go index 3f892c752..ec4ac6ee6 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go @@ -42,6 +42,9 @@ type HTTPGetActionApplyConfiguration struct { Scheme *corev1.URIScheme `json:"scheme,omitempty"` // Custom headers to set in the request. HTTP allows repeated headers. HTTPHeaders []HTTPHeaderApplyConfiguration `json:"httpHeaders,omitempty"` + // Protocol selects the wire protocol for the probe connection. + // Nil defaults to HTTP/1.1. + Protocol *corev1.HTTPProtocol `json:"protocol,omitempty"` } // HTTPGetActionApplyConfiguration constructs a declarative configuration of the HTTPGetAction type for use with @@ -94,3 +97,11 @@ func (b *HTTPGetActionApplyConfiguration) WithHTTPHeaders(values ...*HTTPHeaderA } return b } + +// WithProtocol sets the Protocol 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 Protocol field is set to the value of the last call. +func (b *HTTPGetActionApplyConfiguration) WithProtocol(value corev1.HTTPProtocol) *HTTPGetActionApplyConfiguration { + b.Protocol = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go index 75ce1130a..317554c74 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go @@ -37,6 +37,10 @@ type KeyToPathApplyConfiguration struct { // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. Mode *int32 `json:"mode,omitempty"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + User *int64 `json:"user,omitempty"` } // KeyToPathApplyConfiguration constructs a declarative configuration of the KeyToPath type for use with @@ -68,3 +72,11 @@ func (b *KeyToPathApplyConfiguration) WithMode(value int32) *KeyToPathApplyConfi b.Mode = &value return b } + +// WithUser sets the User 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 User field is set to the value of the last call. +func (b *KeyToPathApplyConfiguration) WithUser(value int64) *KeyToPathApplyConfiguration { + b.User = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go index 84a9fca31..e4da20c65 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go @@ -32,7 +32,7 @@ import ( // // LimitRange sets resource usage limits for each kind of resource in a Namespace. type LimitRangeApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/namespace.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/namespace.go index a5bf0f946..ab5c1b00d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/namespace.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/namespace.go @@ -33,7 +33,7 @@ import ( // Namespace provides a scope for Names. // Use of multiple namespaces is optional. type NamespaceApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/node.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/node.go index ff45b8994..511f02053 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/node.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/node.go @@ -33,7 +33,7 @@ import ( // Node is a worker node in Kubernetes. // Each node will have a unique identifier in the cache (i.e. in etcd). type NodeApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatablemappedresources.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatablemappedresources.go new file mode 100644 index 000000000..aab1093bd --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatablemappedresources.go @@ -0,0 +1,59 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableMappedResourcesApplyConfiguration represents a declarative configuration of the NodeAllocatableMappedResources type for use +// with apply. +// +// NodeAllocatableMappedResources describes mapped node allocatable resource allocations. +type NodeAllocatableMappedResourcesApplyConfiguration struct { + // Name is the name of the resource (e.g., cpu, memory). + Name *corev1.ResourceName `json:"name,omitempty"` + // Quantity is the total node allocatable resource capacity allocated for the claim. + // This claim's allocated devices is shared by all the containers referencing the claim. + // Kubelet adds this value to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. + Quantity *resource.Quantity `json:"quantity,omitempty"` +} + +// NodeAllocatableMappedResourcesApplyConfiguration constructs a declarative configuration of the NodeAllocatableMappedResources type for use with +// apply. +func NodeAllocatableMappedResources() *NodeAllocatableMappedResourcesApplyConfiguration { + return &NodeAllocatableMappedResourcesApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *NodeAllocatableMappedResourcesApplyConfiguration) WithName(value corev1.ResourceName) *NodeAllocatableMappedResourcesApplyConfiguration { + b.Name = &value + return b +} + +// WithQuantity sets the Quantity 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 Quantity field is set to the value of the last call. +func (b *NodeAllocatableMappedResourcesApplyConfiguration) WithQuantity(value resource.Quantity) *NodeAllocatableMappedResourcesApplyConfiguration { + b.Quantity = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableoverheadresources.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableoverheadresources.go new file mode 100644 index 000000000..fa7ca9442 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableoverheadresources.go @@ -0,0 +1,77 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableOverheadResourcesApplyConfiguration represents a declarative configuration of the NodeAllocatableOverheadResources type for use +// with apply. +// +// NodeAllocatableOverheadResources describes auxiliary overhead resource allocations. +type NodeAllocatableOverheadResourcesApplyConfiguration struct { + // Name is the name of the resource (e.g., cpu, memory). + Name *corev1.ResourceName `json:"name,omitempty"` + // PerPod is the flat overhead quantity allocated per pod. + // Adding to each container limit allows individual containers to utilize the overhead, while the parent pod-level cgroup limit caps the total usage at the pod boundary where the overhead is accounted for exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + PerPod *resource.Quantity `json:"perPod,omitempty"` + // PerContainer is the variable overhead quantity applied for each container referencing the claim. + // The container references are recorded in `nodeAllocatableResourceClaimStatuses.containers`. + // The total overhead quantity allocated for the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + // At least one of PerPod or PerContainer must be specified. Specifying neither is an invalid configuration. + PerContainer *resource.Quantity `json:"perContainer,omitempty"` +} + +// NodeAllocatableOverheadResourcesApplyConfiguration constructs a declarative configuration of the NodeAllocatableOverheadResources type for use with +// apply. +func NodeAllocatableOverheadResources() *NodeAllocatableOverheadResourcesApplyConfiguration { + return &NodeAllocatableOverheadResourcesApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *NodeAllocatableOverheadResourcesApplyConfiguration) WithName(value corev1.ResourceName) *NodeAllocatableOverheadResourcesApplyConfiguration { + b.Name = &value + return b +} + +// WithPerPod sets the PerPod 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 PerPod field is set to the value of the last call. +func (b *NodeAllocatableOverheadResourcesApplyConfiguration) WithPerPod(value resource.Quantity) *NodeAllocatableOverheadResourcesApplyConfiguration { + b.PerPod = &value + return b +} + +// WithPerContainer sets the PerContainer 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 PerContainer field is set to the value of the last call. +func (b *NodeAllocatableOverheadResourcesApplyConfiguration) WithPerContainer(value resource.Quantity) *NodeAllocatableOverheadResourcesApplyConfiguration { + b.PerContainer = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableresourceclaimstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableresourceclaimstatus.go index 6e384b002..9c67c7f9b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableresourceclaimstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodeallocatableresourceclaimstatus.go @@ -18,11 +18,6 @@ limitations under the License. package v1 -import ( - corev1 "k8s.io/api/core/v1" - resource "k8s.io/apimachinery/pkg/api/resource" -) - // NodeAllocatableResourceClaimStatusApplyConfiguration represents a declarative configuration of the NodeAllocatableResourceClaimStatus type for use // with apply. // @@ -32,8 +27,12 @@ type NodeAllocatableResourceClaimStatusApplyConfiguration struct { ResourceClaimName *string `json:"resourceClaimName,omitempty"` // Containers lists the names of all containers in this pod that reference the claim. Containers []string `json:"containers,omitempty"` - // Resources is a map of the node-allocatable resource name to the aggregate quantity allocated to the claim. - Resources map[corev1.ResourceName]resource.Quantity `json:"resources,omitempty"` + // Mapping contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].mapping` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + Mapping []NodeAllocatableMappedResourcesApplyConfiguration `json:"mapping,omitempty"` + // Overhead contains allocations through devices mapped in the device spec's `nodeAllocatableResources[...].overhead` field. + // This is used by kubelet for pod level and container-level cgroup enforcement. + Overhead []NodeAllocatableOverheadResourcesApplyConfiguration `json:"overhead,omitempty"` } // NodeAllocatableResourceClaimStatusApplyConfiguration constructs a declarative configuration of the NodeAllocatableResourceClaimStatus type for use with @@ -60,16 +59,28 @@ func (b *NodeAllocatableResourceClaimStatusApplyConfiguration) WithContainers(va return b } -// WithResources puts the entries into the Resources field in the declarative configuration +// WithMapping adds the given value to the Mapping field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the Resources field, -// overwriting an existing map entries in Resources field with the same key. -func (b *NodeAllocatableResourceClaimStatusApplyConfiguration) WithResources(entries map[corev1.ResourceName]resource.Quantity) *NodeAllocatableResourceClaimStatusApplyConfiguration { - if b.Resources == nil && len(entries) > 0 { - b.Resources = make(map[corev1.ResourceName]resource.Quantity, len(entries)) +// If called multiple times, values provided by each call will be appended to the Mapping field. +func (b *NodeAllocatableResourceClaimStatusApplyConfiguration) WithMapping(values ...*NodeAllocatableMappedResourcesApplyConfiguration) *NodeAllocatableResourceClaimStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithMapping") + } + b.Mapping = append(b.Mapping, *values[i]) } - for k, v := range entries { - b.Resources[k] = v + return b +} + +// WithOverhead adds the given value to the Overhead field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Overhead field. +func (b *NodeAllocatableResourceClaimStatusApplyConfiguration) WithOverhead(values ...*NodeAllocatableOverheadResourcesApplyConfiguration) *NodeAllocatableResourceClaimStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOverhead") + } + b.Overhead = append(b.Overhead, *values[i]) } return b } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodepodpreemptionpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodepodpreemptionpolicy.go new file mode 100644 index 000000000..62c0a00ae --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodepodpreemptionpolicy.go @@ -0,0 +1,47 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// NodePodPreemptionPolicyApplyConfiguration represents a declarative configuration of the NodePodPreemptionPolicy type for use +// with apply. +// +// NodePodPreemptionPolicy defines the node-level policies governing preemption for pods on this node. +type NodePodPreemptionPolicyApplyConfiguration struct { + // DisableResizePreemption lists the owners (e.g., autoscalers, operators, administrators) + // that have requested to disable scheduler and Kubelet preemption for in-place pod resize on this node. + // If this list is non-empty, resize-induced preemption is disabled on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + DisableResizePreemption []string `json:"disableResizePreemption,omitempty"` +} + +// NodePodPreemptionPolicyApplyConfiguration constructs a declarative configuration of the NodePodPreemptionPolicy type for use with +// apply. +func NodePodPreemptionPolicy() *NodePodPreemptionPolicyApplyConfiguration { + return &NodePodPreemptionPolicyApplyConfiguration{} +} + +// WithDisableResizePreemption adds the given value to the DisableResizePreemption field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DisableResizePreemption field. +func (b *NodePodPreemptionPolicyApplyConfiguration) WithDisableResizePreemption(values ...string) *NodePodPreemptionPolicyApplyConfiguration { + for i := range values { + b.DisableResizePreemption = append(b.DisableResizePreemption, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go index b53ed21d7..2839ed767 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go @@ -41,6 +41,9 @@ type NodeSpecApplyConfiguration struct { // Deprecated. Not all kubelets will set this field. Remove field after 1.13. // see: https://issues.k8s.io/61966 DoNotUseExternalID *string `json:"externalID,omitempty"` + // PodPreemptionPolicy controls the node-level preemption behaviors for pods on this node. + // This is an alpha field and requires enabling the InPlacePodVerticalScalingSchedulerPreemption feature gate. + PodPreemptionPolicy *NodePodPreemptionPolicyApplyConfiguration `json:"podPreemptionPolicy,omitempty"` } // NodeSpecApplyConfiguration constructs a declarative configuration of the NodeSpec type for use with @@ -111,3 +114,11 @@ func (b *NodeSpecApplyConfiguration) WithDoNotUseExternalID(value string) *NodeS b.DoNotUseExternalID = &value return b } + +// WithPodPreemptionPolicy sets the PodPreemptionPolicy 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 PodPreemptionPolicy field is set to the value of the last call. +func (b *NodeSpecApplyConfiguration) WithPodPreemptionPolicy(value *NodePodPreemptionPolicyApplyConfiguration) *NodeSpecApplyConfiguration { + b.PodPreemptionPolicy = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go index 70b8a7819..14a4680b2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go @@ -49,6 +49,8 @@ type NodeSystemInfoApplyConfiguration struct { Architecture *string `json:"architecture,omitempty"` // Swap Info reported by the node. Swap *NodeSwapStatusApplyConfiguration `json:"swap,omitempty"` + // Whether the node is running in a user namespace. + RunningInUserNamespace *bool `json:"runningInUserNamespace,omitempty"` } // NodeSystemInfoApplyConfiguration constructs a declarative configuration of the NodeSystemInfo type for use with @@ -144,3 +146,11 @@ func (b *NodeSystemInfoApplyConfiguration) WithSwap(value *NodeSwapStatusApplyCo b.Swap = value return b } + +// WithRunningInUserNamespace sets the RunningInUserNamespace 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 RunningInUserNamespace field is set to the value of the last call. +func (b *NodeSystemInfoApplyConfiguration) WithRunningInUserNamespace(value bool) *NodeSystemInfoApplyConfiguration { + b.RunningInUserNamespace = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go index 4ef8ed4b5..34da80ab9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go @@ -34,7 +34,7 @@ import ( // It is analogous to a node. // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes type PersistentVolumeApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go index d77417f35..1f86f61f7 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go @@ -32,7 +32,7 @@ import ( // // PersistentVolumeClaim is a user's request for and claim to a persistent volume type PersistentVolumeClaimApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go index 8710769b7..1761f7bf3 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go @@ -53,8 +53,8 @@ type PersistentVolumeClaimSpecApplyConfiguration struct { // * An existing PVC (PersistentVolumeClaim) // If the provisioner or an external controller can support the specified data source, // it will create a new volume based on the contents of the specified data source. - // When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, - // and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. + // dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be + // copied to dataSource when dataSourceRef.namespace is not specified. // If the namespace is specified, then dataSourceRef will not be copied to dataSource. DataSource *TypedLocalObjectReferenceApplyConfiguration `json:"dataSource,omitempty"` // dataSourceRef specifies the object from which to populate the volume with data, if a non-empty @@ -78,7 +78,6 @@ type PersistentVolumeClaimSpecApplyConfiguration struct { // specified. // * While dataSource only allows local objects, dataSourceRef allows objects // in any namespaces. - // (Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. // (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled. DataSourceRef *TypedObjectReferenceApplyConfiguration `json:"dataSourceRef,omitempty"` // volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go index ee2d5adbd..c910005eb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go @@ -98,6 +98,9 @@ type PersistentVolumeClaimStatusApplyConfiguration struct { // ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. // When this is unset, there is no ModifyVolume operation being attempted. ModifyVolumeStatus *ModifyVolumeStatusApplyConfiguration `json:"modifyVolumeStatus,omitempty"` + // healthStatus contains the latest controller-reported health information + // for the volume bound to this claim. + HealthStatus *VolumeHealthStatusApplyConfiguration `json:"healthStatus,omitempty"` } // PersistentVolumeClaimStatusApplyConfiguration constructs a declarative configuration of the PersistentVolumeClaimStatus type for use with @@ -182,3 +185,11 @@ func (b *PersistentVolumeClaimStatusApplyConfiguration) WithModifyVolumeStatus(v b.ModifyVolumeStatus = value return b } + +// WithHealthStatus sets the HealthStatus 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 HealthStatus field is set to the value of the last call. +func (b *PersistentVolumeClaimStatusApplyConfiguration) WithHealthStatus(value *VolumeHealthStatusApplyConfiguration) *PersistentVolumeClaimStatusApplyConfiguration { + b.HealthStatus = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go index 8c1661022..72fb8f540 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go @@ -31,7 +31,7 @@ type PersistentVolumeSpecApplyConfiguration struct { // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity Capacity *corev1.ResourceList `json:"capacity,omitempty"` // persistentVolumeSource is the actual volume backing the persistent volume. - PersistentVolumeSourceApplyConfiguration `json:",inline"` + PersistentVolumeSourceApplyConfiguration `json:""` // accessModes contains all ways the volume can be mounted. // More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes AccessModes []corev1.PersistentVolumeAccessMode `json:"accessModes,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/pod.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/pod.go index d10d38de1..815c0b4b6 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/pod.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/pod.go @@ -33,7 +33,7 @@ import ( // Pod is a collection of containers that can run on a host. This resource is created // by clients and scheduled onto hosts. type PodApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podcertificateprojection.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podcertificateprojection.go index 0d951a894..3c10f37e0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podcertificateprojection.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podcertificateprojection.go @@ -89,6 +89,10 @@ type PodCertificateProjectionApplyConfiguration struct { // Signers should document the keys and values they support. Signers should // deny requests that contain keys they do not recognize. UserAnnotations map[string]string `json:"userAnnotations,omitempty"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + User *int64 `json:"user,omitempty"` } // PodCertificateProjectionApplyConfiguration constructs a declarative configuration of the PodCertificateProjection type for use with @@ -158,3 +162,11 @@ func (b *PodCertificateProjectionApplyConfiguration) WithUserAnnotations(entries } return b } + +// WithUser sets the User 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 User field is set to the value of the last call. +func (b *PodCertificateProjectionApplyConfiguration) WithUser(value int64) *PodCertificateProjectionApplyConfiguration { + b.User = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go index a6f1629ed..951ced04b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go @@ -121,11 +121,8 @@ type PodSecurityContextApplyConfiguration struct { // Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes // whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their // CSIDriver instance. Other volumes are always re-labelled recursively. - // "MountOption" value is allowed only when SELinuxMount feature gate is enabled. // - // If not specified and SELinuxMount feature gate is enabled, "MountOption" is used. - // If not specified and SELinuxMount feature gate is disabled, "MountOption" is used for ReadWriteOncePod volumes - // and "Recursive" for all other volumes. + // If not specified, "MountOption" is used. // // This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers. // diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podspec.go index e67c18c41..f46481dab 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podspec.go @@ -172,6 +172,8 @@ type PodSpecApplyConfiguration struct { EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // PreemptionPolicy is the Policy for preempting pods with lower priority. // One of Never, PreemptLowerPriority. + // When Priority Admission Controller is enabled, it prevents users from setting + // this field. The admission controller populates this field from PriorityClassName. // Defaults to PreemptLowerPriority if unset. PreemptionPolicy *corev1.PreemptionPolicy `json:"preemptionPolicy,omitempty"` // Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. @@ -270,7 +272,6 @@ type PodSpecApplyConfiguration struct { // - `hostNetwork` must be set to false. // // This field must be a valid DNS subdomain as defined in RFC 1123 and contain at most 64 characters. - // Requires the HostnameOverride feature gate to be enabled. HostnameOverride *string `json:"hostnameOverride,omitempty"` // SchedulingGroup provides a reference to the immediate scheduling runtime // grouping object that this Pod belongs to. @@ -285,6 +286,22 @@ type PodSpecApplyConfiguration struct { // recreated with different policies. Doing this during pod scheduling // may result in the placement not conforming to the expected policies. SchedulingGroup *PodSchedulingGroupApplyConfiguration `json:"schedulingGroup,omitempty"` + // evictionResponders reference responders that react to Evictions based on EvictionRequests. + // Responders should observe and communicate through the Eviction Resource API to help with + // the graceful termination of a pod. The responders are selected sequentially, according to + // their specified priority. + // + // Responders should periodically report on an eviction progress by updating the + // .status.responders[].heartbeatTime field of the Eviction object. If this field is not updated + // within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the eviction + // is passed over to the next responder with a lower priority. If there is no other responder, + // the last default imperative-eviction.k8s.io/evictor responder with a priority of 100 will + // evict the pod using the imperative Eviction API (pods//eviction subresource). + // + // The maximum length of the responders list is 10. + // Responders are not supported when the pod is part of a PodGroup (.spec.schedulingGroup is set). + // This field can only be set on creation and is immutable afterwards. + EvictionResponders []EvictionResponderApplyConfiguration `json:"evictionResponders,omitempty"` } // PodSpecApplyConfiguration constructs a declarative configuration of the PodSpec type for use with @@ -689,3 +706,16 @@ func (b *PodSpecApplyConfiguration) WithSchedulingGroup(value *PodSchedulingGrou b.SchedulingGroup = value return b } + +// WithEvictionResponders adds the given value to the EvictionResponders field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the EvictionResponders field. +func (b *PodSpecApplyConfiguration) WithEvictionResponders(values ...*EvictionResponderApplyConfiguration) *PodSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithEvictionResponders") + } + b.EvictionResponders = append(b.EvictionResponders, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go index 8328d9cdb..1bc37b507 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go @@ -145,6 +145,9 @@ type PodStatusApplyConfiguration struct { // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). // Examples include "cpu", "memory", "ephemeral-storage", and hugepages. NodeAllocatableResourceClaimStatuses []NodeAllocatableResourceClaimStatusApplyConfiguration `json:"nodeAllocatableResourceClaimStatuses,omitempty"` + // volumeHealth contains node-reported health for each volume the pod is using. + // Populated by the kubelet on the pod's node. + VolumeHealth []PodVolumeHealthApplyConfiguration `json:"volumeHealth,omitempty"` } // PodStatusApplyConfiguration constructs a declarative configuration of the PodStatus type for use with @@ -360,3 +363,16 @@ func (b *PodStatusApplyConfiguration) WithNodeAllocatableResourceClaimStatuses(v } return b } + +// WithVolumeHealth adds the given value to the VolumeHealth field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the VolumeHealth field. +func (b *PodStatusApplyConfiguration) WithVolumeHealth(values ...*PodVolumeHealthApplyConfiguration) *PodStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithVolumeHealth") + } + b.VolumeHealth = append(b.VolumeHealth, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go index a4a2e300e..a78cd0430 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go @@ -32,7 +32,7 @@ import ( // // PodTemplate describes a template for creating copies of a predefined pod. type PodTemplateApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podvolumehealth.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podvolumehealth.go new file mode 100644 index 000000000..f17399dff --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/podvolumehealth.go @@ -0,0 +1,74 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// PodVolumeHealthApplyConfiguration represents a declarative configuration of the PodVolumeHealth type for use +// with apply. +// +// PodVolumeHealth contains health information for a volume used by a pod, +// reported by the CSI node plugin via the kubelet. +type PodVolumeHealthApplyConfiguration struct { + // name matches an entry in pod.spec.volumes. + Name *string `json:"name,omitempty"` + // conditions is the set of adverse conditions reported by + // the CSI node plugin for this volume on this node. + // At most 16 conditions may be reported. + HealthConditions []VolumeHealthConditionApplyConfiguration `json:"healthConditions,omitempty"` + // lastTransitionTime is when the current set of conditions first appeared. + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` +} + +// PodVolumeHealthApplyConfiguration constructs a declarative configuration of the PodVolumeHealth type for use with +// apply. +func PodVolumeHealth() *PodVolumeHealthApplyConfiguration { + return &PodVolumeHealthApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodVolumeHealthApplyConfiguration) WithName(value string) *PodVolumeHealthApplyConfiguration { + b.Name = &value + return b +} + +// WithHealthConditions adds the given value to the HealthConditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the HealthConditions field. +func (b *PodVolumeHealthApplyConfiguration) WithHealthConditions(values ...*VolumeHealthConditionApplyConfiguration) *PodVolumeHealthApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithHealthConditions") + } + b.HealthConditions = append(b.HealthConditions, *values[i]) + } + return b +} + +// WithLastTransitionTime sets the LastTransitionTime 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 LastTransitionTime field is set to the value of the last call. +func (b *PodVolumeHealthApplyConfiguration) WithLastTransitionTime(value metav1.Time) *PodVolumeHealthApplyConfiguration { + b.LastTransitionTime = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/probe.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/probe.go index e6b3ddd7c..5ea41ea5c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/probe.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/probe.go @@ -25,7 +25,7 @@ package v1 // alive or ready to receive traffic. type ProbeApplyConfiguration struct { // The action taken to determine the health of a container - ProbeHandlerApplyConfiguration `json:",inline"` + ProbeHandlerApplyConfiguration `json:""` // Number of seconds after the container has started before liveness probes are initiated. // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes InitialDelaySeconds *int32 `json:"initialDelaySeconds,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go index a17e4d1df..c00e9ca6c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go @@ -33,6 +33,10 @@ type ProjectedVolumeSourceApplyConfiguration struct { // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. DefaultMode *int32 `json:"defaultMode,omitempty"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + DefaultUser *int64 `json:"defaultUser,omitempty"` } // ProjectedVolumeSourceApplyConfiguration constructs a declarative configuration of the ProjectedVolumeSource type for use with @@ -61,3 +65,11 @@ func (b *ProjectedVolumeSourceApplyConfiguration) WithDefaultMode(value int32) * b.DefaultMode = &value return b } + +// WithDefaultUser sets the DefaultUser 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 DefaultUser field is set to the value of the last call. +func (b *ProjectedVolumeSourceApplyConfiguration) WithDefaultUser(value int64) *ProjectedVolumeSourceApplyConfiguration { + b.DefaultUser = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go index a6416c4b7..8d8c43547 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go @@ -32,7 +32,7 @@ import ( // // ReplicationController represents the configuration of a replication controller. type ReplicationControllerApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // If the Labels of a ReplicationController are empty, they are defaulted to // be the same as the Pod(s) that the replication controller manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go index 6489d2928..475135b07 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go @@ -32,7 +32,7 @@ import ( // // ResourceQuota sets aggregate quota restrictions enforced per namespace type ResourceQuotaApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcestatus.go index 511164e7c..b418ff4cb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcestatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/resourcestatus.go @@ -28,8 +28,13 @@ import ( // ResourceStatus represents the status of a single resource allocated to a Pod. type ResourceStatusApplyConfiguration struct { // Name of the resource. Must be unique within the pod and in case of non-DRA resource, match one of the resources from the pod spec. - // For DRA resources, the value must be "claim:/". - // When this status is reported about a container, the "claim_name" and "request" must match one of the claims of this container. + // For DRA resources, the value must be "claim:/" when + // container.resources.claims[*].request is set or "claim:" when + // container.resources.claims[*].request is empty. + // For DRA-backed extended resources, "claim:/" is used + // when the claim name and request name are recorded in pod.status.extendedResourceClaimStatus. + // When this status is reported about a container, the "claim_name" and "request" + // must match one of the claims of this container. Name *corev1.ResourceName `json:"name,omitempty"` // List of unique resources health. Each element in the list contains an unique resource ID and its health. // At a minimum, for the lifetime of a Pod, resource ID must uniquely identify the resource allocated to the Pod on the Node. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secret.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secret.go index 42be77931..e4b12ad2b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secret.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secret.go @@ -33,7 +33,7 @@ import ( // Secret holds secret data of a certain type. The total bytes of the values in // the Data field must be less than MaxSecretSize bytes. type SecretApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go index 21a6b7524..bb2f7243e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go @@ -28,7 +28,7 @@ package v1 // key-value pairs as environment variables. type SecretEnvSourceApplyConfiguration struct { // The Secret to select from. - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // Specify whether the Secret must be defined Optional *bool `json:"optional,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go index 8e83bc813..71d48813c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go @@ -24,7 +24,7 @@ package v1 // SecretKeySelector selects a key of a Secret. type SecretKeySelectorApplyConfiguration struct { // The name of the secret in the pod's namespace to select from. - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // The key of the secret to select from. Must be a valid secret key. Key *string `json:"key,omitempty"` // Specify whether the Secret or its key must be defined diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go index 87016d9fa..879ed4bf4 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go @@ -28,7 +28,7 @@ package v1 // Note that this is identical to a secret volume source without the default // mode. type SecretProjectionApplyConfiguration struct { - LocalObjectReferenceApplyConfiguration `json:",inline"` + LocalObjectReferenceApplyConfiguration `json:""` // items if unspecified, each key-value pair in the Data field of the referenced // Secret will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go index bdc098535..a4c37ae01 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go @@ -48,6 +48,10 @@ type SecretVolumeSourceApplyConfiguration struct { DefaultMode *int32 `json:"defaultMode,omitempty"` // optional field specify whether the Secret or its keys must be defined Optional *bool `json:"optional,omitempty"` + // defaultUser is Optional: The owner UID of the created files by default. + // The defaultUser field is only used as a fallback when the item-level user field is unset. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + DefaultUser *int64 `json:"defaultUser,omitempty"` } // SecretVolumeSourceApplyConfiguration constructs a declarative configuration of the SecretVolumeSource type for use with @@ -92,3 +96,11 @@ func (b *SecretVolumeSourceApplyConfiguration) WithOptional(value bool) *SecretV b.Optional = &value return b } + +// WithDefaultUser sets the DefaultUser 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 DefaultUser field is set to the value of the last call. +func (b *SecretVolumeSourceApplyConfiguration) WithDefaultUser(value int64) *SecretVolumeSourceApplyConfiguration { + b.DefaultUser = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/service.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/service.go index b0e667824..432aa14ee 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/service.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/service.go @@ -34,7 +34,7 @@ import ( // (for example 3306) that the proxy listens on, and the selector that determines which pods // will answer requests sent through the proxy. type ServiceApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go index d43934777..2104cb4e4 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go @@ -35,7 +35,7 @@ import ( // * a principal that can be authenticated and authorized // * a set of secrets type ServiceAccountApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go index e2bf69bc4..93b13a289 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go @@ -41,6 +41,10 @@ type ServiceAccountTokenProjectionApplyConfiguration struct { // path is the path relative to the mount point of the file to project the // token into. Path *string `json:"path,omitempty"` + // user is Optional: The owner UID of the created file. + // If specified, the item-level user field takes precedence over defaultUser. + // (Alpha) This field requires the AtomicWriteVolumeUserFields feature gate to be enabled. + User *int64 `json:"user,omitempty"` } // ServiceAccountTokenProjectionApplyConfiguration constructs a declarative configuration of the ServiceAccountTokenProjection type for use with @@ -72,3 +76,11 @@ func (b *ServiceAccountTokenProjectionApplyConfiguration) WithPath(value string) b.Path = &value return b } + +// WithUser sets the User 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 User field is set to the value of the last call. +func (b *ServiceAccountTokenProjectionApplyConfiguration) WithUser(value int64) *ServiceAccountTokenProjectionApplyConfiguration { + b.User = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volume.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volume.go index 2e4c0e6ad..a2e0b3fc9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volume.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volume.go @@ -30,7 +30,7 @@ type VolumeApplyConfiguration struct { // volumeSource represents the location and type of the mounted volume. // If not specified, the Volume is implied to be an EmptyDir. // This implied behavior is deprecated and will be removed in a future version. - VolumeSourceApplyConfiguration `json:",inline"` + VolumeSourceApplyConfiguration `json:""` } // VolumeApplyConfiguration constructs a declarative configuration of the Volume type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthcondition.go new file mode 100644 index 000000000..26fa8d140 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthcondition.go @@ -0,0 +1,73 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// VolumeHealthConditionApplyConfiguration represents a declarative configuration of the VolumeHealthCondition type for use +// with apply. +// +// VolumeHealthCondition represents an adverse health condition reported for a volume. +type VolumeHealthConditionApplyConfiguration struct { + // status is the machine-parseable health category. + // Possible values: + // - "Inaccessible": the volume cannot be accessed. + // - "DataLoss": data loss has been detected on the volume. + // - "Degraded": the volume is functioning with reduced capability. + Status *corev1.VolumeHealthStatusType `json:"status,omitempty"` + // reason is a brief CamelCase machine-parseable reason. + // Together with status it forms the unique identity of a condition entry. + // Maximum permitted length of a reason is 256 bytes. + Reason *string `json:"reason,omitempty"` + // message is a human-readable description. + // Maximum permitted length of a message is 1024 bytes. + Message *string `json:"message,omitempty"` +} + +// VolumeHealthConditionApplyConfiguration constructs a declarative configuration of the VolumeHealthCondition type for use with +// apply. +func VolumeHealthCondition() *VolumeHealthConditionApplyConfiguration { + return &VolumeHealthConditionApplyConfiguration{} +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *VolumeHealthConditionApplyConfiguration) WithStatus(value corev1.VolumeHealthStatusType) *VolumeHealthConditionApplyConfiguration { + b.Status = &value + return b +} + +// WithReason sets the Reason 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 Reason field is set to the value of the last call. +func (b *VolumeHealthConditionApplyConfiguration) WithReason(value string) *VolumeHealthConditionApplyConfiguration { + b.Reason = &value + return b +} + +// WithMessage sets the Message 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 Message field is set to the value of the last call. +func (b *VolumeHealthConditionApplyConfiguration) WithMessage(value string) *VolumeHealthConditionApplyConfiguration { + b.Message = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthstatus.go new file mode 100644 index 000000000..23d3b22c8 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumehealthstatus.go @@ -0,0 +1,64 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// VolumeHealthStatusApplyConfiguration represents a declarative configuration of the VolumeHealthStatus type for use +// with apply. +// +// VolumeHealthStatus contains health information for a volume reported +// by the CSI controller plugin. +type VolumeHealthStatusApplyConfiguration struct { + // conditions is the set of adverse conditions reported by + // the CSI controller plugin. An empty list means no adverse condition. + // At most 16 conditions may be reported. + HealthConditions []VolumeHealthConditionApplyConfiguration `json:"healthConditions,omitempty"` + // lastTransitionTime is when the current set of conditions first appeared. + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` +} + +// VolumeHealthStatusApplyConfiguration constructs a declarative configuration of the VolumeHealthStatus type for use with +// apply. +func VolumeHealthStatus() *VolumeHealthStatusApplyConfiguration { + return &VolumeHealthStatusApplyConfiguration{} +} + +// WithHealthConditions adds the given value to the HealthConditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the HealthConditions field. +func (b *VolumeHealthStatusApplyConfiguration) WithHealthConditions(values ...*VolumeHealthConditionApplyConfiguration) *VolumeHealthStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithHealthConditions") + } + b.HealthConditions = append(b.HealthConditions, *values[i]) + } + return b +} + +// WithLastTransitionTime sets the LastTransitionTime 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 LastTransitionTime field is set to the value of the last call. +func (b *VolumeHealthStatusApplyConfiguration) WithLastTransitionTime(value metav1.Time) *VolumeHealthStatusApplyConfiguration { + b.LastTransitionTime = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go index 83b71eb65..35e77e3da 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go @@ -49,8 +49,7 @@ type VolumeMountApplyConfiguration struct { // // If this field is not specified, it is treated as an equivalent of Disabled. RecursiveReadOnly *corev1.RecursiveReadOnlyMode `json:"recursiveReadOnly,omitempty"` - // Path within the container at which the volume should be mounted. Must - // not contain ':'. + // Path within the container at which the volume should be mounted. MountPath *string `json:"mountPath,omitempty"` // Path within the volume from which the container's volume should be mounted. // Defaults to "" (volume's root). @@ -67,6 +66,13 @@ type VolumeMountApplyConfiguration struct { // Defaults to "" (volume's root). // SubPathExpr and SubPath are mutually exclusive. SubPathExpr *string `json:"subPathExpr,omitempty"` + // bindMountOptions is the list of additional bind mount options to apply when + // mounting this volume into the container. Allowed values are noexec, + // nodev, and nosuid. These are Linux mount options and have no effect on + // Windows nodes. + // This field is not supported with image volumes. + // This is an alpha field and requires enabling the VolumeBindMountOptions feature gate. + BindMountOptions []string `json:"bindMountOptions,omitempty"` } // VolumeMountApplyConfiguration constructs a declarative configuration of the VolumeMount type for use with @@ -130,3 +136,13 @@ func (b *VolumeMountApplyConfiguration) WithSubPathExpr(value string) *VolumeMou b.SubPathExpr = &value return b } + +// WithBindMountOptions adds the given value to the BindMountOptions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the BindMountOptions field. +func (b *VolumeMountApplyConfiguration) WithBindMountOptions(values ...string) *VolumeMountApplyConfiguration { + for i := range values { + b.BindMountOptions = append(b.BindMountOptions, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go index cba77dd57..705dd0be4 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go @@ -37,7 +37,7 @@ import ( // by listing EndpointSlices in the service's namespace whose `kubernetes.io/service-name` // label contains the service's name. type EndpointSliceApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // addressType specifies the type of address carried by this EndpointSlice. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go index 4d40de54a..2a1ac2ca9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go @@ -34,7 +34,7 @@ import ( // For a given service there may be multiple EndpointSlice objects, selected by // labels, which must be joined to produce the full set of endpoints. type EndpointSliceApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // addressType specifies the type of address carried by this EndpointSlice. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1/event.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1/event.go index 122cccad7..e5c572173 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1/event.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1/event.go @@ -38,8 +38,8 @@ import ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type EventApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // eventTime is the time when this Event was first observed. It is required. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go index cf6068f47..a4a6abe6d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go @@ -38,8 +38,8 @@ import ( // continued existence of events with that Reason. Events should be // treated as informative, best-effort, supplemental data. type EventApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // eventTime is the time when this Event was first observed. It is required. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go index 452f9b1c2..c6968fec9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go @@ -34,7 +34,7 @@ import ( // more information. // DaemonSet represents the configuration of a daemon set. type DaemonSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go index 6d0e5f89c..27a554b12 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go @@ -34,7 +34,7 @@ import ( // more information. // Deployment enables declarative updates for Pods and ReplicaSets. type DeploymentApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Specification of the desired behavior of the Deployment. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go index ba82ba9be..8b6ed56e0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go @@ -36,7 +36,7 @@ import ( // based virtual hosting etc. // DEPRECATED - This group version of Ingress is deprecated by networking.k8s.io/v1beta1 Ingress. See the release notes for more information. type IngressApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go index 91ebcf89f..323574f09 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go @@ -53,7 +53,7 @@ type IngressRuleApplyConfiguration struct { // just traffic matching the host to the default backend or all traffic to the // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. - IngressRuleValueApplyConfiguration `json:",inline"` + IngressRuleValueApplyConfiguration `json:""` } // IngressRuleApplyConfiguration constructs a declarative configuration of the IngressRule type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go index 64d95e492..860d8ec7e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go @@ -33,7 +33,7 @@ import ( // DEPRECATED 1.9 - This group version of NetworkPolicy is deprecated by networking/v1/NetworkPolicy. // NetworkPolicy describes what network traffic is allowed for a set of Pods type NetworkPolicyApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go index 02d6cbffe..2dfa8fdcb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go @@ -34,7 +34,7 @@ import ( // more information. // ReplicaSet ensures that a specified number of pod replicas are running at any given time. type ReplicaSetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go index 9637d58c8..8542fa666 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go @@ -30,7 +30,7 @@ import ( // // represents a scaling request for a resource. type ScaleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschema.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschema.go index 1bfc945a3..085dd1bf9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschema.go @@ -33,7 +33,7 @@ import ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". type FlowSchemaApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschemacondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschemacondition.go index a9023615d..fa6c67205 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschemacondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/flowschemacondition.go @@ -32,8 +32,7 @@ type FlowSchemaConditionApplyConfiguration struct { // Required. Type *flowcontrolv1.FlowSchemaConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfiguration.go index d64c3acb6..ae87170fd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfiguration.go @@ -32,7 +32,7 @@ import ( // // PriorityLevelConfiguration represents the configuration of a priority level. type PriorityLevelConfigurationApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfigurationcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfigurationcondition.go index 82b9547d5..ea7be15dc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfigurationcondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1/prioritylevelconfigurationcondition.go @@ -32,8 +32,7 @@ type PriorityLevelConfigurationConditionApplyConfiguration struct { // Required. Type *flowcontrolv1.PriorityLevelConfigurationConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go index 80a1f720f..dbd3a5f29 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go @@ -33,7 +33,7 @@ import ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". type FlowSchemaApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go index 9462bbd02..aa926a1be 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go @@ -32,8 +32,7 @@ type FlowSchemaConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta1.FlowSchemaConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta1.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go index 8fecf8688..1f34672a1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go @@ -32,7 +32,7 @@ import ( // // PriorityLevelConfiguration represents the configuration of a priority level. type PriorityLevelConfigurationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go index a2ebf71fc..af4dc6a3a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go @@ -32,8 +32,7 @@ type PriorityLevelConfigurationConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta1.PriorityLevelConfigurationConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta1.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go index 394f24b99..a083ea91e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go @@ -33,7 +33,7 @@ import ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". type FlowSchemaApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go index 6bebc912c..2706b563c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go @@ -32,8 +32,7 @@ type FlowSchemaConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta2.FlowSchemaConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta2.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go index a60827b63..56cb3557a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go @@ -32,7 +32,7 @@ import ( // // PriorityLevelConfiguration represents the configuration of a priority level. type PriorityLevelConfigurationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go index 26a8b6624..a6c789886 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go @@ -32,8 +32,7 @@ type PriorityLevelConfigurationConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta2.PriorityLevelConfigurationConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta2.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go index 0079748b6..19e43e5cb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go @@ -33,7 +33,7 @@ import ( // FlowSchema defines the schema of a group of flows. Note that a flow is made up of a set of inbound API requests with // similar attributes and is identified by a pair of strings: the name of the FlowSchema and a "flow distinguisher". type FlowSchemaApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go index de2aff568..74189b100 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go @@ -32,8 +32,7 @@ type FlowSchemaConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta3.FlowSchemaConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta3.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go index 910cb4c25..5b16a044a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go @@ -32,7 +32,7 @@ import ( // // PriorityLevelConfiguration represents the configuration of a priority level. type PriorityLevelConfigurationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // `metadata` is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go index bd14650a9..87013c67b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go @@ -32,8 +32,7 @@ type PriorityLevelConfigurationConditionApplyConfiguration struct { // Required. Type *flowcontrolv1beta3.PriorityLevelConfigurationConditionType `json:"type,omitempty"` // `status` is the status of the condition. - // Can be True, False, Unknown. - // Required. + // Should be specified and set to one of True, False, Unknown. Status *flowcontrolv1beta3.ConditionStatus `json:"status,omitempty"` // `lastTransitionTime` is the last time the condition transitioned from one status to another. LastTransitionTime *v1.Time `json:"lastTransitionTime,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/internal/internal.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/internal/internal.go index c0b255cc7..a8007a3d1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/internal/internal.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/internal/internal.go @@ -3188,6 +3188,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: message type: scalar: string + - name: observedGeneration + type: + scalar: numeric - name: reason type: scalar: string @@ -3517,6 +3520,26 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" +- name: io.k8s.api.batch.v1.JobSchedulingConfiguration + map: + fields: + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupDisruptionMode + - name: resourceClaims + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupResourceClaim + elementRelationship: associative + keys: + - name + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingPolicy - name: io.k8s.api.batch.v1.JobSpec map: fields: @@ -3553,6 +3576,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: podReplacementPolicy type: scalar: string + - name: scheduling + type: + namedType: io.k8s.api.batch.v1.JobSchedulingConfiguration - name: selector type: namedType: io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector @@ -3877,6 +3903,120 @@ var schemaYAML = typed.YAMLObject(`types: elementRelationship: associative keys: - type +- name: io.k8s.api.certificates.v1.ClusterTrustBundle + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.certificates.v1.ClusterTrustBundleSpec + default: {} +- name: io.k8s.api.certificates.v1.ClusterTrustBundleSpec + map: + fields: + - name: signerName + type: + scalar: string + - name: trustBundle + type: + scalar: string + default: "" +- name: io.k8s.api.certificates.v1.PodCertificateRequest + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.certificates.v1.PodCertificateRequestSpec + default: {} + - name: status + type: + namedType: io.k8s.api.certificates.v1.PodCertificateRequestStatus + default: {} +- name: io.k8s.api.certificates.v1.PodCertificateRequestSpec + map: + fields: + - name: maxExpirationSeconds + type: + scalar: numeric + default: 86400 + - name: nodeName + type: + scalar: string + default: "" + - name: nodeUID + type: + scalar: string + default: "" + - name: podName + type: + scalar: string + default: "" + - name: podUID + type: + scalar: string + default: "" + - name: serviceAccountName + type: + scalar: string + default: "" + - name: serviceAccountUID + type: + scalar: string + default: "" + - name: signerName + type: + scalar: string + default: "" + - name: stubPKCS10Request + type: + scalar: string + - name: unverifiedUserAnnotations + type: + map: + elementType: + scalar: string +- name: io.k8s.api.certificates.v1.PodCertificateRequestStatus + map: + fields: + - name: beginRefreshAt + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: certificateChain + type: + scalar: string + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: notAfter + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: notBefore + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time - name: io.k8s.api.certificates.v1alpha1.ClusterTrustBundle map: fields: @@ -4572,6 +4712,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: signerName type: scalar: string + - name: user + type: + scalar: numeric - name: io.k8s.api.core.v1.ComponentCondition map: fields: @@ -4704,6 +4847,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: defaultMode type: scalar: numeric + - name: defaultUser + type: + scalar: numeric - name: items type: list: @@ -5069,12 +5215,18 @@ var schemaYAML = typed.YAMLObject(`types: - name: resourceFieldRef type: namedType: io.k8s.api.core.v1.ResourceFieldSelector + - name: user + type: + scalar: numeric - name: io.k8s.api.core.v1.DownwardAPIVolumeSource map: fields: - name: defaultMode type: scalar: numeric + - name: defaultUser + type: + scalar: numeric - name: items type: list: @@ -5087,6 +5239,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: medium type: scalar: string + - name: mode + type: + scalar: numeric - name: sizeLimit type: namedType: io.k8s.apimachinery.pkg.api.resource.Quantity @@ -5409,6 +5564,17 @@ var schemaYAML = typed.YAMLObject(`types: - name: host type: scalar: string +- name: io.k8s.api.core.v1.EvictionResponder + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + elementRelationship: atomic - name: io.k8s.api.core.v1.ExecAction map: fields: @@ -5532,6 +5698,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.core.v1.GRPCAction map: fields: + - name: mode + type: + scalar: string - name: port type: scalar: numeric @@ -5602,6 +5771,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: port type: namedType: io.k8s.apimachinery.pkg.util.intstr.IntOrString + - name: protocol + type: + scalar: string - name: scheme type: scalar: string @@ -5761,6 +5933,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: user + type: + scalar: numeric - name: io.k8s.api.core.v1.Lifecycle map: fields: @@ -6040,6 +6215,29 @@ var schemaYAML = typed.YAMLObject(`types: - name: requiredDuringSchedulingIgnoredDuringExecution type: namedType: io.k8s.api.core.v1.NodeSelector +- name: io.k8s.api.core.v1.NodeAllocatableMappedResources + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: quantity + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.core.v1.NodeAllocatableOverheadResources + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: perContainer + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: perPod + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: io.k8s.api.core.v1.NodeAllocatableResourceClaimStatus map: fields: @@ -6049,15 +6247,26 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: associative + - name: mapping + type: + list: + elementType: + namedType: io.k8s.api.core.v1.NodeAllocatableMappedResources + elementRelationship: associative + keys: + - name + - name: overhead + type: + list: + elementType: + namedType: io.k8s.api.core.v1.NodeAllocatableOverheadResources + elementRelationship: associative + keys: + - name - name: resourceClaimName type: scalar: string default: "" - - name: resources - type: - map: - elementType: - namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: io.k8s.api.core.v1.NodeCondition map: fields: @@ -6115,6 +6324,15 @@ var schemaYAML = typed.YAMLObject(`types: - name: supplementalGroupsPolicy type: scalar: boolean +- name: io.k8s.api.core.v1.NodePodPreemptionPolicy + map: + fields: + - name: disableResizePreemption + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: io.k8s.api.core.v1.NodeRuntimeHandler map: fields: @@ -6195,6 +6413,9 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: associative + - name: podPreemptionPolicy + type: + namedType: io.k8s.api.core.v1.NodePodPreemptionPolicy - name: providerID type: scalar: string @@ -6328,6 +6549,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: runningInUserNamespace + type: + scalar: boolean - name: swap type: namedType: io.k8s.api.core.v1.NodeSwapStatus @@ -6506,6 +6730,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: currentVolumeAttributesClassName type: scalar: string + - name: healthStatus + type: + namedType: io.k8s.api.core.v1.VolumeHealthStatus - name: modifyVolumeStatus type: namedType: io.k8s.api.core.v1.ModifyVolumeStatus @@ -6766,6 +6993,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: signerName type: scalar: string + - name: user + type: + scalar: numeric - name: userAnnotations type: map: @@ -6986,6 +7216,14 @@ var schemaYAML = typed.YAMLObject(`types: elementRelationship: associative keys: - name + - name: evictionResponders + type: + list: + elementType: + namedType: io.k8s.api.core.v1.EvictionResponder + elementRelationship: associative + keys: + - name - name: hostAliases type: list: @@ -7189,7 +7427,9 @@ var schemaYAML = typed.YAMLObject(`types: list: elementType: namedType: io.k8s.api.core.v1.NodeAllocatableResourceClaimStatus - elementRelationship: atomic + elementRelationship: associative + keys: + - resourceClaimName - name: nominatedNodeName type: scalar: string @@ -7233,6 +7473,14 @@ var schemaYAML = typed.YAMLObject(`types: - name: startTime type: namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: volumeHealth + type: + list: + elementType: + namedType: io.k8s.api.core.v1.PodVolumeHealth + elementRelationship: associative + keys: + - name - name: io.k8s.api.core.v1.PodTemplate map: fields: @@ -7261,6 +7509,25 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.core.v1.PodSpec default: {} +- name: io.k8s.api.core.v1.PodVolumeHealth + map: + fields: + - name: healthConditions + type: + list: + elementType: + namedType: io.k8s.api.core.v1.VolumeHealthCondition + elementRelationship: associative + keys: + - status + - reason + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.core.v1.PortStatus map: fields: @@ -7338,6 +7605,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: defaultMode type: scalar: numeric + - name: defaultUser + type: + scalar: numeric - name: sources type: list: @@ -7864,6 +8134,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: defaultMode type: scalar: numeric + - name: defaultUser + type: + scalar: numeric - name: items type: list: @@ -7979,6 +8252,9 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" + - name: user + type: + scalar: numeric - name: io.k8s.api.core.v1.ServicePort map: fields: @@ -8401,21 +8677,56 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" -- name: io.k8s.api.core.v1.VolumeMount +- name: io.k8s.api.core.v1.VolumeHealthCondition map: fields: - - name: mountPath + - name: message type: scalar: string - default: "" - - name: mountPropagation + - name: reason type: scalar: string - - name: name + default: "" + - name: status type: scalar: string default: "" - - name: readOnly +- name: io.k8s.api.core.v1.VolumeHealthStatus + map: + fields: + - name: healthConditions + type: + list: + elementType: + namedType: io.k8s.api.core.v1.VolumeHealthCondition + elementRelationship: associative + keys: + - status + - reason + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time +- name: io.k8s.api.core.v1.VolumeMount + map: + fields: + - name: bindMountOptions + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: mountPath + type: + scalar: string + default: "" + - name: mountPropagation + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: readOnly type: scalar: boolean - name: recursiveReadOnly @@ -10862,6 +11173,214 @@ var schemaYAML = typed.YAMLObject(`types: - name: reason type: scalar: string +- name: io.k8s.api.lifecycle.v1alpha1.Eviction + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionSpec + default: {} + - name: status + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionStatus + default: {} +- name: io.k8s.api.lifecycle.v1alpha1.EvictionPodReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: uid + type: + scalar: string + default: "" +- name: io.k8s.api.lifecycle.v1alpha1.EvictionRequest + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionRequestSpec + default: {} + - name: status + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionRequestStatus + default: {} +- name: io.k8s.api.lifecycle.v1alpha1.EvictionRequestPodReference + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: uid + type: + scalar: string + default: "" +- name: io.k8s.api.lifecycle.v1alpha1.EvictionRequestSpec + map: + fields: + - name: intent + type: + scalar: string + default: "" + - name: requester + type: + scalar: string + default: "" + - name: target + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionRequestTarget + default: {} +- name: io.k8s.api.lifecycle.v1alpha1.EvictionRequestStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric +- name: io.k8s.api.lifecycle.v1alpha1.EvictionRequestTarget + map: + fields: + - name: pod + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionRequestPodReference + unions: + - fields: + - fieldName: pod + discriminatorValue: Pod +- name: io.k8s.api.lifecycle.v1alpha1.EvictionSpec + map: + fields: + - name: target + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionTarget + default: {} +- name: io.k8s.api.lifecycle.v1alpha1.EvictionStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: observedGeneration + type: + scalar: numeric + - name: requesters + type: + list: + elementType: + namedType: io.k8s.api.lifecycle.v1alpha1.Requester + elementRelationship: associative + keys: + - name + - name: responders + type: + list: + elementType: + namedType: io.k8s.api.lifecycle.v1alpha1.ResponderStatus + elementRelationship: associative + keys: + - name + - name: targetResponders + type: + list: + elementType: + namedType: io.k8s.api.lifecycle.v1alpha1.TargetResponder + elementRelationship: associative + keys: + - name +- name: io.k8s.api.lifecycle.v1alpha1.EvictionTarget + map: + fields: + - name: pod + type: + namedType: io.k8s.api.lifecycle.v1alpha1.EvictionPodReference + unions: + - fields: + - fieldName: pod + discriminatorValue: Pod +- name: io.k8s.api.lifecycle.v1alpha1.Requester + map: + fields: + - name: intent + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" + elementRelationship: atomic +- name: io.k8s.api.lifecycle.v1alpha1.ResponderStatus + map: + fields: + - name: completionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: expectedCompletionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: heartbeatTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: name + type: + scalar: string + default: "" + - name: startTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + elementRelationship: separable +- name: io.k8s.api.lifecycle.v1alpha1.TargetResponder + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: priority + type: + scalar: numeric + - name: state + type: + scalar: string + default: "" + elementRelationship: atomic - name: io.k8s.api.networking.v1.HTTPIngressPath map: fields: @@ -12476,11 +12995,11 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" - - name: nodeAllocatableResourceMappings + - name: nodeAllocatableResources type: map: elementType: - namedType: io.k8s.api.resource.v1.NodeAllocatableResourceMapping + namedType: io.k8s.api.resource.v1.NodeAllocatableResource - name: nodeName type: scalar: string @@ -12664,6 +13183,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.resource.v1.DeviceCounterConsumption map: fields: + - name: compatibilityGroups + type: + list: + elementType: + scalar: string + elementRelationship: atomic - name: counterSet type: scalar: string @@ -12673,6 +13198,17 @@ var schemaYAML = typed.YAMLObject(`types: map: elementType: namedType: io.k8s.api.resource.v1.Counter +- name: io.k8s.api.resource.v1.DeviceDerivedAttribute + map: + fields: + - name: expression + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.resource.v1.DeviceRequest map: fields: @@ -12731,6 +13267,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: shareID type: scalar: string + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: tolerations type: list: @@ -12755,6 +13297,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -12792,40 +13340,100 @@ var schemaYAML = typed.YAMLObject(`types: - name: value type: scalar: string -- name: io.k8s.api.resource.v1.DeviceToleration +- name: io.k8s.api.resource.v1.DeviceTaintRule map: fields: - - name: effect + - name: apiVersion type: scalar: string - - name: key + - name: kind type: scalar: string - - name: operator + - name: metadata type: - scalar: string - default: Equal - - name: tolerationSeconds + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec type: - scalar: numeric - - name: value + namedType: io.k8s.api.resource.v1.DeviceTaintRuleSpec + default: {} + - name: status type: - scalar: string -- name: io.k8s.api.resource.v1.ExactDeviceRequest + namedType: io.k8s.api.resource.v1.DeviceTaintRuleStatus + default: {} +- name: io.k8s.api.resource.v1.DeviceTaintRuleSpec map: fields: - - name: adminAccess - type: - scalar: boolean - - name: allocationMode + - name: deviceSelector type: - scalar: string - - name: capacity + namedType: io.k8s.api.resource.v1.DeviceTaintSelector + - name: taint type: - namedType: io.k8s.api.resource.v1.CapacityRequirements - - name: count + namedType: io.k8s.api.resource.v1.DeviceTaint + default: {} +- name: io.k8s.api.resource.v1.DeviceTaintRuleStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type +- name: io.k8s.api.resource.v1.DeviceTaintSelector + map: + fields: + - name: device + type: + scalar: string + - name: driver + type: + scalar: string + - name: pool + type: + scalar: string +- name: io.k8s.api.resource.v1.DeviceToleration + map: + fields: + - name: effect + type: + scalar: string + - name: key + type: + scalar: string + - name: operator + type: + scalar: string + default: Equal + - name: tolerationSeconds type: scalar: numeric + - name: value + type: + scalar: string +- name: io.k8s.api.resource.v1.ExactDeviceRequest + map: + fields: + - name: adminAccess + type: + scalar: boolean + - name: allocationMode + type: + scalar: string + - name: capacity + type: + namedType: io.k8s.api.resource.v1.CapacityRequirements + - name: count + type: + scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -12857,15 +13465,36 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1.NodeAllocatableResourceMapping +- name: io.k8s.api.resource.v1.NodeAllocatableMapping map: fields: - - name: allocationMultiplier - type: - namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: capacityKey type: scalar: string + - name: capacityMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: deviceMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1.NodeAllocatableOverhead + map: + fields: + - name: perContainer + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: perPod + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1.NodeAllocatableResource + map: + fields: + - name: mapping + type: + namedType: io.k8s.api.resource.v1.NodeAllocatableMapping + - name: overhead + type: + namedType: io.k8s.api.resource.v1.NodeAllocatableOverhead - name: io.k8s.api.resource.v1.OpaqueDeviceConfiguration map: fields: @@ -13029,6 +13658,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector + - name: partitionTypeAttribute + type: + scalar: string - name: perDeviceNodeSelection type: scalar: boolean @@ -13042,6 +13674,12 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1.CounterSet elementRelationship: atomic + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: io.k8s.api.resource.v1alpha3.DeviceTaint map: fields: @@ -13113,6 +13751,21 @@ var schemaYAML = typed.YAMLObject(`types: - name: pool type: scalar: string +- name: io.k8s.api.resource.v1alpha3.PartitionTypeStatus + map: + fields: + - name: allocatable + type: + scalar: numeric + - name: attribute + type: + scalar: string + - name: total + type: + scalar: numeric + - name: type + type: + scalar: string - name: io.k8s.api.resource.v1alpha3.PoolStatus map: fields: @@ -13132,12 +13785,21 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeName type: scalar: string + - name: partitionSummary + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.PartitionTypeStatus + elementRelationship: atomic - name: poolName type: scalar: string - name: resourceSliceCount type: scalar: numeric + - name: shareableSummary + type: + namedType: io.k8s.api.resource.v1alpha3.ShareableSummaryStatus - name: totalDevices type: scalar: numeric @@ -13170,6 +13832,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.resource.v1alpha3.ResourcePoolStatusRequestSpec map: fields: + - name: defaultPartitionTypeAttribute + type: + scalar: string - name: driver type: scalar: string @@ -13201,6 +13866,36 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1alpha3.PoolStatus elementRelationship: atomic +- name: io.k8s.api.resource.v1alpha3.ShareableCapacityStatus + map: + fields: + - name: available + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: consumed + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: name + type: + scalar: string + - name: total + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1alpha3.ShareableSummaryStatus + map: + fields: + - name: capacity + type: + list: + elementType: + namedType: io.k8s.api.resource.v1alpha3.ShareableCapacityStatus + elementRelationship: atomic + - name: fullyAvailableDevices + type: + scalar: numeric + - name: partiallyAvailableDevices + type: + scalar: numeric - name: io.k8s.api.resource.v1beta1.AllocatedDeviceStatus map: fields: @@ -13286,11 +13981,11 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1beta1.DeviceCounterConsumption elementRelationship: atomic - - name: nodeAllocatableResourceMappings + - name: nodeAllocatableResources type: map: elementType: - namedType: io.k8s.api.resource.v1beta1.NodeAllocatableResourceMapping + namedType: io.k8s.api.resource.v1beta1.NodeAllocatableResource - name: nodeName type: scalar: string @@ -13544,6 +14239,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.resource.v1beta1.DeviceCounterConsumption map: fields: + - name: compatibilityGroups + type: + list: + elementType: + scalar: string + elementRelationship: atomic - name: counterSet type: scalar: string @@ -13553,6 +14254,17 @@ var schemaYAML = typed.YAMLObject(`types: map: elementType: namedType: io.k8s.api.resource.v1beta1.Counter +- name: io.k8s.api.resource.v1beta1.DeviceDerivedAttribute + map: + fields: + - name: expression + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.resource.v1beta1.DeviceRequest map: fields: @@ -13568,6 +14280,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -13636,6 +14354,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: shareID type: scalar: string + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: tolerations type: list: @@ -13660,6 +14384,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta1.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -13731,15 +14461,36 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1beta1.NodeAllocatableResourceMapping +- name: io.k8s.api.resource.v1beta1.NodeAllocatableMapping map: fields: - - name: allocationMultiplier - type: - namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: capacityKey type: scalar: string + - name: capacityMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: deviceMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta1.NodeAllocatableOverhead + map: + fields: + - name: perContainer + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: perPod + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta1.NodeAllocatableResource + map: + fields: + - name: mapping + type: + namedType: io.k8s.api.resource.v1beta1.NodeAllocatableMapping + - name: overhead + type: + namedType: io.k8s.api.resource.v1beta1.NodeAllocatableOverhead - name: io.k8s.api.resource.v1beta1.OpaqueDeviceConfiguration map: fields: @@ -13903,6 +14654,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector + - name: partitionTypeAttribute + type: + scalar: string - name: perDeviceNodeSelection type: scalar: boolean @@ -13916,6 +14670,12 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1beta1.CounterSet elementRelationship: atomic + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: io.k8s.api.resource.v1beta2.AllocatedDeviceStatus map: fields: @@ -14065,11 +14825,11 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" - - name: nodeAllocatableResourceMappings + - name: nodeAllocatableResources type: map: elementType: - namedType: io.k8s.api.resource.v1beta2.NodeAllocatableResourceMapping + namedType: io.k8s.api.resource.v1beta2.NodeAllocatableResource - name: nodeName type: scalar: string @@ -14253,6 +15013,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: io.k8s.api.resource.v1beta2.DeviceCounterConsumption map: fields: + - name: compatibilityGroups + type: + list: + elementType: + scalar: string + elementRelationship: atomic - name: counterSet type: scalar: string @@ -14262,6 +15028,17 @@ var schemaYAML = typed.YAMLObject(`types: map: elementType: namedType: io.k8s.api.resource.v1beta2.Counter +- name: io.k8s.api.resource.v1beta2.DeviceDerivedAttribute + map: + fields: + - name: expression + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" - name: io.k8s.api.resource.v1beta2.DeviceRequest map: fields: @@ -14320,6 +15097,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: shareID type: scalar: string + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: tolerations type: list: @@ -14344,6 +15127,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -14469,6 +15258,12 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric + - name: derivedAttributes + type: + list: + elementType: + namedType: io.k8s.api.resource.v1beta2.DeviceDerivedAttribute + elementRelationship: atomic - name: deviceClassName type: scalar: string @@ -14500,15 +15295,36 @@ var schemaYAML = typed.YAMLObject(`types: elementType: scalar: string elementRelationship: atomic -- name: io.k8s.api.resource.v1beta2.NodeAllocatableResourceMapping +- name: io.k8s.api.resource.v1beta2.NodeAllocatableMapping map: fields: - - name: allocationMultiplier - type: - namedType: io.k8s.apimachinery.pkg.api.resource.Quantity - name: capacityKey type: scalar: string + - name: capacityMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: deviceMultiplier + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta2.NodeAllocatableOverhead + map: + fields: + - name: perContainer + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity + - name: perPod + type: + namedType: io.k8s.apimachinery.pkg.api.resource.Quantity +- name: io.k8s.api.resource.v1beta2.NodeAllocatableResource + map: + fields: + - name: mapping + type: + namedType: io.k8s.api.resource.v1beta2.NodeAllocatableMapping + - name: overhead + type: + namedType: io.k8s.api.resource.v1beta2.NodeAllocatableOverhead - name: io.k8s.api.resource.v1beta2.OpaqueDeviceConfiguration map: fields: @@ -14672,6 +15488,9 @@ var schemaYAML = typed.YAMLObject(`types: - name: nodeSelector type: namedType: io.k8s.api.core.v1.NodeSelector + - name: partitionTypeAttribute + type: + scalar: string - name: perDeviceNodeSelection type: scalar: boolean @@ -14685,6 +15504,12 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: io.k8s.api.resource.v1beta2.CounterSet elementRelationship: atomic + - name: skipNodeOperations + type: + list: + elementType: + scalar: string + elementRelationship: associative - name: io.k8s.api.scheduling.v1.PriorityClass map: fields: @@ -14711,7 +15536,7 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: numeric default: 0 -- name: io.k8s.api.scheduling.v1alpha2.BasicSchedulingPolicy +- name: io.k8s.api.scheduling.v1alpha3.AllCompositeDisruptionMode map: elementType: scalar: untyped @@ -14723,35 +15548,742 @@ var schemaYAML = typed.YAMLObject(`types: elementType: namedType: __untyped_deduced_ elementRelationship: separable -- name: io.k8s.api.scheduling.v1alpha2.GangSchedulingPolicy - map: - fields: - - name: minCount - type: - scalar: numeric - default: 0 -- name: io.k8s.api.scheduling.v1alpha2.PodGroup +- name: io.k8s.api.scheduling.v1alpha3.AllDisruptionMode map: - fields: - - name: apiVersion - type: - scalar: string - - name: kind - type: - scalar: string - - name: metadata - type: - namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta - default: {} - - name: spec - type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupSpec - default: {} - - name: status - type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupStatus - default: {} -- name: io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaim + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.BasicSchedulingPolicy + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.CompositeBasicSchedulingPolicy + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.CompositeDisruptionMode + map: + fields: + - name: all + type: + namedType: io.k8s.api.scheduling.v1alpha3.AllCompositeDisruptionMode + - name: single + type: + namedType: io.k8s.api.scheduling.v1alpha3.SingleCompositeDisruptionMode + unions: + - fields: + - fieldName: all + discriminatorValue: All + - fieldName: single + discriminatorValue: Single +- name: io.k8s.api.scheduling.v1alpha3.CompositeGangSchedulingPolicy + map: + fields: + - name: minGroupCount + type: + scalar: numeric + default: 0 +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroup + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSpec + default: {} + - name: status + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupStatus + default: {} +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingConstraints + map: + fields: + - name: topology + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.TopologyConstraint + elementRelationship: atomic +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingPolicy + map: + fields: + - name: basic + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositeBasicSchedulingPolicy + - name: gang + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositeGangSchedulingPolicy + unions: + - fields: + - fieldName: basic + discriminatorValue: Basic + - fieldName: gang + discriminatorValue: Gang +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSpec + map: + fields: + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositeDisruptionMode + default: + single: {} + - name: parentCompositePodGroupName + type: + scalar: string + - name: preemptionPolicy + type: + scalar: string + - name: priority + type: + scalar: numeric + - name: priorityClassName + type: + scalar: string + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingPolicy + default: {} + - name: workloadRef + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadReference +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroupStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type +- name: io.k8s.api.scheduling.v1alpha3.CompositePodGroupTemplate + map: + fields: + - name: compositePodGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupTemplate + elementRelationship: associative + keys: + - name + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositeDisruptionMode + - name: name + type: + scalar: string + default: "" + - name: podGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupTemplate + elementRelationship: associative + keys: + - name + - name: preemptionPolicy + type: + scalar: string + - name: priority + type: + scalar: numeric + - name: priorityClassName + type: + scalar: string + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupSchedulingPolicy + default: {} +- name: io.k8s.api.scheduling.v1alpha3.DisruptionMode + map: + fields: + - name: all + type: + namedType: io.k8s.api.scheduling.v1alpha3.AllDisruptionMode + - name: single + type: + namedType: io.k8s.api.scheduling.v1alpha3.SingleDisruptionMode + unions: + - fields: + - fieldName: all + discriminatorValue: All + - fieldName: single + discriminatorValue: Single +- name: io.k8s.api.scheduling.v1alpha3.GangSchedulingPolicy + map: + fields: + - name: minCount + type: + scalar: numeric + default: 0 +- name: io.k8s.api.scheduling.v1alpha3.PodGroup + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupSpec + default: {} + - name: status + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupStatus + default: {} +- name: io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaim + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: resourceClaimName + type: + scalar: string + - name: resourceClaimTemplateName + type: + scalar: string +- name: io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaimStatus + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: resourceClaimName + type: + scalar: string +- name: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingConstraints + map: + fields: + - name: topology + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.TopologyConstraint + elementRelationship: atomic +- name: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingPolicy + map: + fields: + - name: basic + type: + namedType: io.k8s.api.scheduling.v1alpha3.BasicSchedulingPolicy + - name: gang + type: + namedType: io.k8s.api.scheduling.v1alpha3.GangSchedulingPolicy + unions: + - fields: + - fieldName: basic + discriminatorValue: Basic + - fieldName: gang + discriminatorValue: Gang +- name: io.k8s.api.scheduling.v1alpha3.PodGroupSpec + map: + fields: + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1alpha3.DisruptionMode + default: + single: {} + - name: parentCompositePodGroupName + type: + scalar: string + - name: preemptionPolicy + type: + scalar: string + - name: priority + type: + scalar: numeric + - name: priorityClassName + type: + scalar: string + - name: resourceClaims + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaim + elementRelationship: associative + keys: + - name + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingPolicy + default: {} + - name: workloadRef + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadReference +- name: io.k8s.api.scheduling.v1alpha3.PodGroupStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: resourceClaimStatuses + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaimStatus + elementRelationship: associative + keys: + - name +- name: io.k8s.api.scheduling.v1alpha3.PodGroupTemplate + map: + fields: + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1alpha3.DisruptionMode + - name: name + type: + scalar: string + default: "" + - name: preemptionPolicy + type: + scalar: string + - name: priority + type: + scalar: numeric + - name: priorityClassName + type: + scalar: string + - name: resourceClaims + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupResourceClaim + elementRelationship: associative + keys: + - name + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupSchedulingPolicy + default: {} +- name: io.k8s.api.scheduling.v1alpha3.SingleCompositeDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.SingleDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.TopologyConstraint + map: + fields: + - name: key + type: + scalar: string + default: "" +- name: io.k8s.api.scheduling.v1alpha3.TypedLocalObjectReference + map: + fields: + - name: apiGroup + type: + scalar: string + - name: kind + type: + scalar: string + default: "" + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.scheduling.v1alpha3.Workload + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadSpec + default: {} +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupAllDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupBasicSchedulingPolicy + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupDisruptionMode + map: + fields: + - name: all + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupAllDisruptionMode + - name: single + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSingleDisruptionMode + unions: + - fields: + - fieldName: all + discriminatorValue: All + - fieldName: single + discriminatorValue: Single +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupGangSchedulingPolicy + map: + fields: + - name: minCount + type: + scalar: numeric +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupResourceClaim + map: + fields: + - name: name + type: + scalar: string + default: "" + - name: resourceClaimName + type: + scalar: string + - name: resourceClaimTemplateName + type: + scalar: string +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingConstraints + map: + fields: + - name: topology + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.TopologyConstraint + elementRelationship: atomic +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSchedulingPolicy + map: + fields: + - name: basic + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupBasicSchedulingPolicy + - name: gang + type: + namedType: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupGangSchedulingPolicy + unions: + - fields: + - fieldName: basic + discriminatorValue: Basic + - fieldName: gang + discriminatorValue: Gang +- name: io.k8s.api.scheduling.v1alpha3.WorkloadPodGroupSingleDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1alpha3.WorkloadReference + map: + fields: + - name: templateName + type: + scalar: string + default: "" + - name: workloadName + type: + scalar: string + default: "" +- name: io.k8s.api.scheduling.v1alpha3.WorkloadSpec + map: + fields: + - name: compositePodGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.CompositePodGroupTemplate + elementRelationship: associative + keys: + - name + - name: controllerRef + type: + namedType: io.k8s.api.scheduling.v1alpha3.TypedLocalObjectReference + - name: podGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1alpha3.PodGroupTemplate + elementRelationship: associative + keys: + - name +- name: io.k8s.api.scheduling.v1beta1.AllCompositeDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.AllDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.BasicSchedulingPolicy + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.CompositeBasicSchedulingPolicy + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.CompositeDisruptionMode + map: + fields: + - name: all + type: + namedType: io.k8s.api.scheduling.v1beta1.AllCompositeDisruptionMode + - name: single + type: + namedType: io.k8s.api.scheduling.v1beta1.SingleCompositeDisruptionMode + unions: + - fields: + - fieldName: all + discriminatorValue: All + - fieldName: single + discriminatorValue: Single +- name: io.k8s.api.scheduling.v1beta1.CompositeGangSchedulingPolicy + map: + fields: + - name: minGroupCount + type: + scalar: numeric + default: 0 +- name: io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingConstraints + map: + fields: + - name: topology + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1beta1.TopologyConstraint + elementRelationship: atomic +- name: io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingPolicy + map: + fields: + - name: basic + type: + namedType: io.k8s.api.scheduling.v1beta1.CompositeBasicSchedulingPolicy + - name: gang + type: + namedType: io.k8s.api.scheduling.v1beta1.CompositeGangSchedulingPolicy + unions: + - fields: + - fieldName: basic + discriminatorValue: Basic + - fieldName: gang + discriminatorValue: Gang +- name: io.k8s.api.scheduling.v1beta1.CompositePodGroupTemplate + map: + fields: + - name: compositePodGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1beta1.CompositePodGroupTemplate + elementRelationship: associative + keys: + - name + - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1beta1.CompositeDisruptionMode + - name: name + type: + scalar: string + default: "" + - name: podGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1beta1.PodGroupTemplate + elementRelationship: associative + keys: + - name + - name: preemptionPolicy + type: + scalar: string + - name: priority + type: + scalar: numeric + - name: priorityClassName + type: + scalar: string + - name: schedulingConstraints + type: + namedType: io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingConstraints + - name: schedulingPolicy + type: + namedType: io.k8s.api.scheduling.v1beta1.CompositePodGroupSchedulingPolicy + default: {} +- name: io.k8s.api.scheduling.v1beta1.DisruptionMode + map: + fields: + - name: all + type: + namedType: io.k8s.api.scheduling.v1beta1.AllDisruptionMode + - name: single + type: + namedType: io.k8s.api.scheduling.v1beta1.SingleDisruptionMode + unions: + - fields: + - fieldName: all + discriminatorValue: All + - fieldName: single + discriminatorValue: Single +- name: io.k8s.api.scheduling.v1beta1.GangSchedulingPolicy + map: + fields: + - name: minCount + type: + scalar: numeric + default: 0 +- name: io.k8s.api.scheduling.v1beta1.PodGroup + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.scheduling.v1beta1.PodGroupSpec + default: {} + - name: status + type: + namedType: io.k8s.api.scheduling.v1beta1.PodGroupStatus + default: {} +- name: io.k8s.api.scheduling.v1beta1.PodGroupResourceClaim map: fields: - name: name @@ -14764,7 +16296,7 @@ var schemaYAML = typed.YAMLObject(`types: - name: resourceClaimTemplateName type: scalar: string -- name: io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaimStatus +- name: io.k8s.api.scheduling.v1beta1.PodGroupResourceClaimStatus map: fields: - name: name @@ -14774,40 +16306,44 @@ var schemaYAML = typed.YAMLObject(`types: - name: resourceClaimName type: scalar: string -- name: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingConstraints +- name: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingConstraints map: fields: - name: topology type: list: elementType: - namedType: io.k8s.api.scheduling.v1alpha2.TopologyConstraint + namedType: io.k8s.api.scheduling.v1beta1.TopologyConstraint elementRelationship: atomic -- name: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingPolicy +- name: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingPolicy map: fields: - name: basic type: - namedType: io.k8s.api.scheduling.v1alpha2.BasicSchedulingPolicy + namedType: io.k8s.api.scheduling.v1beta1.BasicSchedulingPolicy - name: gang type: - namedType: io.k8s.api.scheduling.v1alpha2.GangSchedulingPolicy + namedType: io.k8s.api.scheduling.v1beta1.GangSchedulingPolicy unions: - fields: - fieldName: basic discriminatorValue: Basic - fieldName: gang discriminatorValue: Gang -- name: io.k8s.api.scheduling.v1alpha2.PodGroupSpec +- name: io.k8s.api.scheduling.v1beta1.PodGroupSpec map: fields: - name: disruptionMode + type: + namedType: io.k8s.api.scheduling.v1beta1.DisruptionMode + default: + single: {} + - name: parentCompositePodGroupName type: scalar: string - default: Pod - - name: podGroupTemplateRef + - name: preemptionPolicy type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupTemplateReference + scalar: string - name: priority type: scalar: numeric @@ -14818,18 +16354,21 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaim + namedType: io.k8s.api.scheduling.v1beta1.PodGroupResourceClaim elementRelationship: associative keys: - name - name: schedulingConstraints type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingConstraints + namedType: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingConstraints - name: schedulingPolicy type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingPolicy + namedType: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingPolicy default: {} -- name: io.k8s.api.scheduling.v1alpha2.PodGroupStatus + - name: workloadRef + type: + namedType: io.k8s.api.scheduling.v1beta1.WorkloadReference +- name: io.k8s.api.scheduling.v1beta1.PodGroupStatus map: fields: - name: conditions @@ -14844,20 +16383,23 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaimStatus + namedType: io.k8s.api.scheduling.v1beta1.PodGroupResourceClaimStatus elementRelationship: associative keys: - name -- name: io.k8s.api.scheduling.v1alpha2.PodGroupTemplate +- name: io.k8s.api.scheduling.v1beta1.PodGroupTemplate map: fields: - name: disruptionMode type: - scalar: string + namedType: io.k8s.api.scheduling.v1beta1.DisruptionMode - name: name type: scalar: string default: "" + - name: preemptionPolicy + type: + scalar: string - name: priority type: scalar: numeric @@ -14868,35 +16410,75 @@ var schemaYAML = typed.YAMLObject(`types: type: list: elementType: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupResourceClaim + namedType: io.k8s.api.scheduling.v1beta1.PodGroupResourceClaim elementRelationship: associative keys: - name - name: schedulingConstraints type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingConstraints + namedType: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingConstraints - name: schedulingPolicy type: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupSchedulingPolicy + namedType: io.k8s.api.scheduling.v1beta1.PodGroupSchedulingPolicy default: {} -- name: io.k8s.api.scheduling.v1alpha2.PodGroupTemplateReference +- name: io.k8s.api.scheduling.v1beta1.PriorityClass map: fields: - - name: workload + - name: apiVersion type: - namedType: io.k8s.api.scheduling.v1alpha2.WorkloadPodGroupTemplateReference - unions: - - fields: - - fieldName: workload - discriminatorValue: Workload -- name: io.k8s.api.scheduling.v1alpha2.TopologyConstraint + scalar: string + - name: description + type: + scalar: string + - name: globalDefault + type: + scalar: boolean + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: preemptionPolicy + type: + scalar: string + - name: value + type: + scalar: numeric + default: 0 +- name: io.k8s.api.scheduling.v1beta1.SingleCompositeDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.SingleDisruptionMode + map: + elementType: + scalar: untyped + list: + elementType: + namedType: __untyped_atomic_ + elementRelationship: atomic + map: + elementType: + namedType: __untyped_deduced_ + elementRelationship: separable +- name: io.k8s.api.scheduling.v1beta1.TopologyConstraint map: fields: - name: key type: scalar: string default: "" -- name: io.k8s.api.scheduling.v1alpha2.TypedLocalObjectReference +- name: io.k8s.api.scheduling.v1beta1.TypedLocalObjectReference map: fields: - name: apiGroup @@ -14910,7 +16492,7 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" -- name: io.k8s.api.scheduling.v1alpha2.Workload +- name: io.k8s.api.scheduling.v1beta1.Workload map: fields: - name: apiVersion @@ -14925,12 +16507,12 @@ var schemaYAML = typed.YAMLObject(`types: default: {} - name: spec type: - namedType: io.k8s.api.scheduling.v1alpha2.WorkloadSpec + namedType: io.k8s.api.scheduling.v1beta1.WorkloadSpec default: {} -- name: io.k8s.api.scheduling.v1alpha2.WorkloadPodGroupTemplateReference +- name: io.k8s.api.scheduling.v1beta1.WorkloadReference map: fields: - - name: podGroupTemplateName + - name: templateName type: scalar: string default: "" @@ -14938,46 +16520,28 @@ var schemaYAML = typed.YAMLObject(`types: type: scalar: string default: "" -- name: io.k8s.api.scheduling.v1alpha2.WorkloadSpec +- name: io.k8s.api.scheduling.v1beta1.WorkloadSpec map: fields: + - name: compositePodGroupTemplates + type: + list: + elementType: + namedType: io.k8s.api.scheduling.v1beta1.CompositePodGroupTemplate + elementRelationship: associative + keys: + - name - name: controllerRef type: - namedType: io.k8s.api.scheduling.v1alpha2.TypedLocalObjectReference + namedType: io.k8s.api.scheduling.v1beta1.TypedLocalObjectReference - name: podGroupTemplates type: list: elementType: - namedType: io.k8s.api.scheduling.v1alpha2.PodGroupTemplate + namedType: io.k8s.api.scheduling.v1beta1.PodGroupTemplate elementRelationship: associative keys: - name -- name: io.k8s.api.scheduling.v1beta1.PriorityClass - map: - fields: - - name: apiVersion - type: - scalar: string - - name: description - type: - scalar: string - - name: globalDefault - type: - scalar: boolean - - name: kind - type: - scalar: string - - name: metadata - type: - namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta - default: {} - - name: preemptionPolicy - type: - scalar: string - - name: value - type: - scalar: numeric - default: 0 - name: io.k8s.api.storage.v1.CSIDriver map: fields: @@ -15054,6 +16618,10 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.storage.v1.CSINodeSpec default: {} + - name: status + type: + namedType: io.k8s.api.storage.v1.CSINodeStatus + default: {} - name: io.k8s.api.storage.v1.CSINodeDriver map: fields: @@ -15085,6 +16653,17 @@ var schemaYAML = typed.YAMLObject(`types: elementRelationship: associative keys: - name +- name: io.k8s.api.storage.v1.CSINodeStatus + map: + fields: + - name: storageHealth + type: + list: + elementType: + namedType: io.k8s.api.storage.v1.StorageHealth + elementRelationship: associative + keys: + - name - name: io.k8s.api.storage.v1.CSIStorageCapacity map: fields: @@ -15154,6 +16733,42 @@ var schemaYAML = typed.YAMLObject(`types: - name: volumeBindingMode type: scalar: string +- name: io.k8s.api.storage.v1.StorageHealth + map: + fields: + - name: healthConditions + type: + list: + elementType: + namedType: io.k8s.api.storage.v1.StorageHealthCondition + elementRelationship: atomic + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.storage.v1.StorageHealthCondition + map: + fields: + - name: accessMode + type: + scalar: string + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: reason + type: + scalar: string + default: "" + - name: status + type: + scalar: string + default: "" + - name: volumeMode + type: + scalar: string - name: io.k8s.api.storage.v1.TokenRequest map: fields: @@ -15466,6 +17081,10 @@ var schemaYAML = typed.YAMLObject(`types: type: namedType: io.k8s.api.storage.v1beta1.CSINodeSpec default: {} + - name: status + type: + namedType: io.k8s.api.storage.v1beta1.CSINodeStatus + default: {} - name: io.k8s.api.storage.v1beta1.CSINodeDriver map: fields: @@ -15497,6 +17116,17 @@ var schemaYAML = typed.YAMLObject(`types: elementRelationship: associative keys: - name +- name: io.k8s.api.storage.v1beta1.CSINodeStatus + map: + fields: + - name: storageHealth + type: + list: + elementType: + namedType: io.k8s.api.storage.v1beta1.StorageHealth + elementRelationship: associative + keys: + - name - name: io.k8s.api.storage.v1beta1.CSIStorageCapacity map: fields: @@ -15566,6 +17196,42 @@ var schemaYAML = typed.YAMLObject(`types: - name: volumeBindingMode type: scalar: string +- name: io.k8s.api.storage.v1beta1.StorageHealth + map: + fields: + - name: healthConditions + type: + list: + elementType: + namedType: io.k8s.api.storage.v1beta1.StorageHealthCondition + elementRelationship: atomic + - name: name + type: + scalar: string + default: "" +- name: io.k8s.api.storage.v1beta1.StorageHealthCondition + map: + fields: + - name: accessMode + type: + scalar: string + - name: lastTransitionTime + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: message + type: + scalar: string + - name: reason + type: + scalar: string + default: "" + - name: status + type: + scalar: string + default: "" + - name: volumeMode + type: + scalar: string - name: io.k8s.api.storage.v1beta1.TokenRequest map: fields: @@ -15679,6 +17345,48 @@ var schemaYAML = typed.YAMLObject(`types: - name: count type: scalar: numeric +- name: io.k8s.api.storagemigration.v1.StorageVersionMigration + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: io.k8s.api.storagemigration.v1.StorageVersionMigrationSpec + default: {} + - name: status + type: + namedType: io.k8s.api.storagemigration.v1.StorageVersionMigrationStatus + default: {} +- name: io.k8s.api.storagemigration.v1.StorageVersionMigrationSpec + map: + fields: + - name: resource + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.GroupResource + default: {} +- name: io.k8s.api.storagemigration.v1.StorageVersionMigrationStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: resourceVersion + type: + scalar: string - name: io.k8s.api.storagemigration.v1beta1.StorageVersionMigration map: fields: diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/eviction.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/eviction.go new file mode 100644 index 000000000..afcf45120 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/eviction.go @@ -0,0 +1,327 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// EvictionApplyConfiguration represents a declarative configuration of the Eviction type for use +// with apply. +// +// Eviction initiates an eviction process, which should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. It manages the Eviction lifecycle. +// Requesters are preserved in .status.requesters even after they have withdrawn their request. +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Once all EvictionRequest corresponding to this Eviction .spec.target have been +// removed, this Eviction object will eventually be garbage collected. +// +// If the target is a pod, the .status.targetResponders is populated from Pod's +// .spec.evictionResponders. +// +// Responders should observe and communicate through the .status to help with the eviction +// of the target when they see their state == Active in .status.targetResponders. ResponderStatus +// struct should then be periodically updated to indicate the progress or completion of the eviction +// process by each responder in .status.responders. If .status.responders[].heartbeatTime is not +// updated within the heartbeat deadline defined by the Eviction API (currently 20 minutes), the +// eviction is passed over to the next responder with a lower priority. +// +// If there are no other responders and the target is a pod, the last default +// imperative-eviction.k8s.io/evictor responder with a priority of 100 will evict the pod using the +// imperative Eviction API (pods//eviction subresource). +type EvictionApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + // .metadata.name set by the evictionrequest-controller is purely informative and subject to change. + // .spec.target field should be used to identify the target precisesly. + // + // The requester and responder names will be used as label keys and added to the labels of the + // eviction in one of the following formats: + // 1. acme.io/foo: "requester" + // 2. acme.io/foo: "responder" + // 3. acme.io/foo: "requester-responder" + // + // Please see EvictionParticipantRole for available role label values. + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec defines the eviction specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Spec *EvictionSpecApplyConfiguration `json:"spec,omitempty"` + // status represents the most recently observed status of the eviction. + // Populated by responders and evictionrequest-controller. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Status *EvictionStatusApplyConfiguration `json:"status,omitempty"` +} + +// Eviction constructs a declarative configuration of the Eviction type for use with +// apply. +func Eviction(name, namespace string) *EvictionApplyConfiguration { + b := &EvictionApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("Eviction") + b.WithAPIVersion("lifecycle.k8s.io/v1alpha1") + return b +} + +// ExtractEvictionFrom extracts the applied configuration owned by fieldManager from +// eviction for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// eviction must be a unmodified Eviction API object that was retrieved from the Kubernetes API. +// ExtractEvictionFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractEvictionFrom(eviction *lifecyclev1alpha1.Eviction, fieldManager string, subresource string) (*EvictionApplyConfiguration, error) { + b := &EvictionApplyConfiguration{} + err := managedfields.ExtractInto(eviction, internal.Parser().Type("io.k8s.api.lifecycle.v1alpha1.Eviction"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(eviction.Name) + b.WithNamespace(eviction.Namespace) + + b.WithKind("Eviction") + b.WithAPIVersion("lifecycle.k8s.io/v1alpha1") + return b, nil +} + +// ExtractEviction extracts the applied configuration owned by fieldManager from +// eviction. If no managedFields are found in eviction for fieldManager, a +// EvictionApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// eviction must be a unmodified Eviction API object that was retrieved from the Kubernetes API. +// ExtractEviction provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractEviction(eviction *lifecyclev1alpha1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) { + return ExtractEvictionFrom(eviction, fieldManager, "") +} + +// ExtractEvictionStatus extracts the applied configuration owned by fieldManager from +// eviction for the status subresource. +func ExtractEvictionStatus(eviction *lifecyclev1alpha1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) { + return ExtractEvictionFrom(eviction, fieldManager, "status") +} + +func (b EvictionApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithKind(value string) *EvictionApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithAPIVersion(value string) *EvictionApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithName(value string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithGenerateName(value string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithNamespace(value string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithUID(value types.UID) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithResourceVersion(value string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithGeneration(value int64) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *EvictionApplyConfiguration) WithLabels(entries map[string]string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *EvictionApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *EvictionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *EvictionApplyConfiguration) WithFinalizers(values ...string) *EvictionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *EvictionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithSpec(value *EvictionSpecApplyConfiguration) *EvictionApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *EvictionApplyConfiguration) WithStatus(value *EvictionStatusApplyConfiguration) *EvictionApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *EvictionApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *EvictionApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *EvictionApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *EvictionApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionpodreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionpodreference.go new file mode 100644 index 000000000..bc5c6e0f2 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionpodreference.go @@ -0,0 +1,60 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + types "k8s.io/apimachinery/pkg/types" +) + +// EvictionPodReferenceApplyConfiguration represents a declarative configuration of the EvictionPodReference type for use +// with apply. +// +// EvictionPodReference contains enough information to locate the referenced pod inside the same +// namespace. +type EvictionPodReferenceApplyConfiguration struct { + // name of the target. + // This field is required. + Name *string `json:"name,omitempty"` + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + UID *types.UID `json:"uid,omitempty"` +} + +// EvictionPodReferenceApplyConfiguration constructs a declarative configuration of the EvictionPodReference type for use with +// apply. +func EvictionPodReference() *EvictionPodReferenceApplyConfiguration { + return &EvictionPodReferenceApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *EvictionPodReferenceApplyConfiguration) WithName(value string) *EvictionPodReferenceApplyConfiguration { + b.Name = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *EvictionPodReferenceApplyConfiguration) WithUID(value types.UID) *EvictionPodReferenceApplyConfiguration { + b.UID = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequest.go new file mode 100644 index 000000000..66bfeb38f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequest.go @@ -0,0 +1,310 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// EvictionRequestApplyConfiguration represents a declarative configuration of the EvictionRequest type for use +// with apply. +// +// EvictionRequest defines a request that should ideally result in a graceful eviction of a +// .spec.target (e.g. termination of a pod). +// +// The evictionrequest-controller observes intents of all EvictionRequests and transforms them into +// Evictions. +// - .spec.requester is set as a label on the Eviction for easier lookup. +// - Each target can have a set of responders assigned to it. Eviction objects are observed by +// these responders, who implement the eviction logic and update the Eviction's status with +// progress. +// +// There is many-to-many relationship between EvictionRequests and Evictions in general. +// And many-to-one if the target is a pod. +// +// If all requesters withdraw their eviction intent for a common target, the eviction will be +// canceled. Deleting an EvictionRequest also counts as a withdrawal. +// Once all EvictionRequest of a target are removed, the corresponding Evictions are eventually +// garbage collected. +type EvictionRequestApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec defines the eviction request specification. + // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Spec *EvictionRequestSpecApplyConfiguration `json:"spec,omitempty"` + // status represents the most recently observed status of the eviction request. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Status *EvictionRequestStatusApplyConfiguration `json:"status,omitempty"` +} + +// EvictionRequest constructs a declarative configuration of the EvictionRequest type for use with +// apply. +func EvictionRequest(name, namespace string) *EvictionRequestApplyConfiguration { + b := &EvictionRequestApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("EvictionRequest") + b.WithAPIVersion("lifecycle.k8s.io/v1alpha1") + return b +} + +// ExtractEvictionRequestFrom extracts the applied configuration owned by fieldManager from +// evictionRequest for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// evictionRequest must be a unmodified EvictionRequest API object that was retrieved from the Kubernetes API. +// ExtractEvictionRequestFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractEvictionRequestFrom(evictionRequest *lifecyclev1alpha1.EvictionRequest, fieldManager string, subresource string) (*EvictionRequestApplyConfiguration, error) { + b := &EvictionRequestApplyConfiguration{} + err := managedfields.ExtractInto(evictionRequest, internal.Parser().Type("io.k8s.api.lifecycle.v1alpha1.EvictionRequest"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(evictionRequest.Name) + b.WithNamespace(evictionRequest.Namespace) + + b.WithKind("EvictionRequest") + b.WithAPIVersion("lifecycle.k8s.io/v1alpha1") + return b, nil +} + +// ExtractEvictionRequest extracts the applied configuration owned by fieldManager from +// evictionRequest. If no managedFields are found in evictionRequest for fieldManager, a +// EvictionRequestApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// evictionRequest must be a unmodified EvictionRequest API object that was retrieved from the Kubernetes API. +// ExtractEvictionRequest provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractEvictionRequest(evictionRequest *lifecyclev1alpha1.EvictionRequest, fieldManager string) (*EvictionRequestApplyConfiguration, error) { + return ExtractEvictionRequestFrom(evictionRequest, fieldManager, "") +} + +// ExtractEvictionRequestStatus extracts the applied configuration owned by fieldManager from +// evictionRequest for the status subresource. +func ExtractEvictionRequestStatus(evictionRequest *lifecyclev1alpha1.EvictionRequest, fieldManager string) (*EvictionRequestApplyConfiguration, error) { + return ExtractEvictionRequestFrom(evictionRequest, fieldManager, "status") +} + +func (b EvictionRequestApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithKind(value string) *EvictionRequestApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithAPIVersion(value string) *EvictionRequestApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithName(value string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithGenerateName(value string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithNamespace(value string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithUID(value types.UID) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithResourceVersion(value string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithGeneration(value int64) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *EvictionRequestApplyConfiguration) WithLabels(entries map[string]string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *EvictionRequestApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *EvictionRequestApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *EvictionRequestApplyConfiguration) WithFinalizers(values ...string) *EvictionRequestApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *EvictionRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithSpec(value *EvictionRequestSpecApplyConfiguration) *EvictionRequestApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *EvictionRequestApplyConfiguration) WithStatus(value *EvictionRequestStatusApplyConfiguration) *EvictionRequestApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *EvictionRequestApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *EvictionRequestApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *EvictionRequestApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *EvictionRequestApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestpodreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestpodreference.go new file mode 100644 index 000000000..4e6486865 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestpodreference.go @@ -0,0 +1,60 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + types "k8s.io/apimachinery/pkg/types" +) + +// EvictionRequestPodReferenceApplyConfiguration represents a declarative configuration of the EvictionRequestPodReference type for use +// with apply. +// +// EvictionRequestPodReference contains enough information to locate the referenced pod inside the +// same namespace. +type EvictionRequestPodReferenceApplyConfiguration struct { + // name of the target. + // This field is required. + Name *string `json:"name,omitempty"` + // uid of the target. + // It can be found in .metadata.uid of the target and is a lowercase UUID in 8-4-4-4-12 format. + // This field is required. + UID *types.UID `json:"uid,omitempty"` +} + +// EvictionRequestPodReferenceApplyConfiguration constructs a declarative configuration of the EvictionRequestPodReference type for use with +// apply. +func EvictionRequestPodReference() *EvictionRequestPodReferenceApplyConfiguration { + return &EvictionRequestPodReferenceApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *EvictionRequestPodReferenceApplyConfiguration) WithName(value string) *EvictionRequestPodReferenceApplyConfiguration { + b.Name = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *EvictionRequestPodReferenceApplyConfiguration) WithUID(value types.UID) *EvictionRequestPodReferenceApplyConfiguration { + b.UID = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestspec.go new file mode 100644 index 000000000..6fc40b8c2 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequestspec.go @@ -0,0 +1,79 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" +) + +// EvictionRequestSpecApplyConfiguration represents a declarative configuration of the EvictionRequestSpec type for use +// with apply. +// +// EvictionRequestSpec is a specification of an EvictionRequest. +type EvictionRequestSpecApplyConfiguration struct { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + Target *EvictionRequestTargetApplyConfiguration `json:"target,omitempty"` + // requester allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // Domain names *.k8s.io and *.kubernetes.io are reserved. + // This field is required and immutable. + Requester *string `json:"requester,omitempty"` + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn for a common target, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + Intent *lifecyclev1alpha1.EvictionRequestIntent `json:"intent,omitempty"` +} + +// EvictionRequestSpecApplyConfiguration constructs a declarative configuration of the EvictionRequestSpec type for use with +// apply. +func EvictionRequestSpec() *EvictionRequestSpecApplyConfiguration { + return &EvictionRequestSpecApplyConfiguration{} +} + +// WithTarget sets the Target 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 Target field is set to the value of the last call. +func (b *EvictionRequestSpecApplyConfiguration) WithTarget(value *EvictionRequestTargetApplyConfiguration) *EvictionRequestSpecApplyConfiguration { + b.Target = value + return b +} + +// WithRequester sets the Requester 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 Requester field is set to the value of the last call. +func (b *EvictionRequestSpecApplyConfiguration) WithRequester(value string) *EvictionRequestSpecApplyConfiguration { + b.Requester = &value + return b +} + +// WithIntent sets the Intent 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 Intent field is set to the value of the last call. +func (b *EvictionRequestSpecApplyConfiguration) WithIntent(value lifecyclev1alpha1.EvictionRequestIntent) *EvictionRequestSpecApplyConfiguration { + b.Intent = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequeststatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequeststatus.go new file mode 100644 index 000000000..8367990f9 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequeststatus.go @@ -0,0 +1,75 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// EvictionRequestStatusApplyConfiguration represents a declarative configuration of the EvictionRequestStatus type for use +// with apply. +// +// EvictionRequestStatus represents the last observed status of the eviction request. +type EvictionRequestStatusApplyConfiguration struct { + // conditions contain information about the eviction request. + // + // EvictionRequest specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // These conditions can be reset if the eviction was unsuccessful and a new Eviction intent has + // been submitted. + // + // The maximum length of the conditions list is 100. + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + // observedGeneration is EvictionRequest's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` +} + +// EvictionRequestStatusApplyConfiguration constructs a declarative configuration of the EvictionRequestStatus type for use with +// apply. +func EvictionRequestStatus() *EvictionRequestStatusApplyConfiguration { + return &EvictionRequestStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *EvictionRequestStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *EvictionRequestStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithObservedGeneration sets the ObservedGeneration 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 ObservedGeneration field is set to the value of the last call. +func (b *EvictionRequestStatusApplyConfiguration) WithObservedGeneration(value int64) *EvictionRequestStatusApplyConfiguration { + b.ObservedGeneration = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequesttarget.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequesttarget.go new file mode 100644 index 000000000..1000dc533 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionrequesttarget.go @@ -0,0 +1,43 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +// EvictionRequestTargetApplyConfiguration represents a declarative configuration of the EvictionRequestTarget type for use +// with apply. +// +// EvictionRequestTarget contains a reference to an object that should be evicted. +type EvictionRequestTargetApplyConfiguration struct { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + Pod *EvictionRequestPodReferenceApplyConfiguration `json:"pod,omitempty"` +} + +// EvictionRequestTargetApplyConfiguration constructs a declarative configuration of the EvictionRequestTarget type for use with +// apply. +func EvictionRequestTarget() *EvictionRequestTargetApplyConfiguration { + return &EvictionRequestTargetApplyConfiguration{} +} + +// WithPod sets the Pod 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 Pod field is set to the value of the last call. +func (b *EvictionRequestTargetApplyConfiguration) WithPod(value *EvictionRequestPodReferenceApplyConfiguration) *EvictionRequestTargetApplyConfiguration { + b.Pod = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionspec.go new file mode 100644 index 000000000..4ed00a53b --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionspec.go @@ -0,0 +1,43 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +// EvictionSpecApplyConfiguration represents a declarative configuration of the EvictionSpec type for use +// with apply. +// +// EvictionSpec is a specification of an Eviction. +type EvictionSpecApplyConfiguration struct { + // target contains a reference to an object (e.g. a pod) that should be evicted. + // This field is required and immutable. + Target *EvictionTargetApplyConfiguration `json:"target,omitempty"` +} + +// EvictionSpecApplyConfiguration constructs a declarative configuration of the EvictionSpec type for use with +// apply. +func EvictionSpec() *EvictionSpecApplyConfiguration { + return &EvictionSpecApplyConfiguration{} +} + +// WithTarget sets the Target 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 Target field is set to the value of the last call. +func (b *EvictionSpecApplyConfiguration) WithTarget(value *EvictionTargetApplyConfiguration) *EvictionSpecApplyConfiguration { + b.Target = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionstatus.go new file mode 100644 index 000000000..b6d3a9658 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictionstatus.go @@ -0,0 +1,147 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// EvictionStatusApplyConfiguration represents a declarative configuration of the EvictionStatus type for use +// with apply. +// +// EvictionStatus represents the last observed status of the eviction request. +type EvictionStatusApplyConfiguration struct { + // conditions contain information about the eviction request. + // + // Eviction specific conditions are: TargetEvicted or Failed (managed by evictionrequest-controller). + // - Failed means that the eviction request is no longer being processed + // by any eviction responder. This can happen if the request is canceled or if no responder + // managed to evict the target (e.g. terminate or delete a pod). + // - TargetEvicted means that the target has been evicted (e.g. a pod has been terminated or deleted). + // + // The maximum length of the conditions list is 100. + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + // observedGeneration is Eviction's .metadata.generation observed by the evictionrequest-controller. + // The observed generation value cannot be negative and can only be incremented. + // The minimum value is 1. + // This field is managed by evictionrequest-controller. + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` + // requesters allow you to identify the entities, that requested the eviction of the target. + // If all the requesters withdraw their eviction intent, the eviction will be canceled. + // + // The maximum length of the requesters list is 100. + // If this limit is exceeded, requesters with Withdrawn intent should be dropped first. + Requesters []RequesterApplyConfiguration `json:"requesters,omitempty"` + // targetResponders reference responders that should eventually respond to this eviction + // to help with the graceful eviction of a target. These responders are selected sequentially, + // according to their specified priority by setting the Active state to the TargetResponder + // .state field. The maximum number of active responders allowed is 1. + // Eventually each responder can end up in an Interrupted, Canceled or, Completed state. + // Responders should observe these states in order to navigate their lifecycle. + // + // If the target is a pod, the field is populated from Pod's .spec.evictionResponders. Default + // responders may be added to the list according to the target. + // + // Default responders: + // - imperative-eviction.k8s.io/evictor responder with a priority of 100 is added to the list if the + // target is a pod. It will call the imperative Eviction API (pods//eviction subresource). + // This call may not succeed due to PodDisruptionBudgets, which may block the pod termination. + // It will update the responder message and try again with a backoff. + // + // The maximum length of the responders list is 11. + // The length and keys of the list cannot change once set. + // This field is managed by evictionrequest-controller. + TargetResponders []TargetResponderApplyConfiguration `json:"targetResponders,omitempty"` + // responders represents the eviction process status of each declared responder. + // + // The responder list should be the same length and have the same .name fields as + // .status.targetResponders. Only responders with .name that have Active state in + // .targetResponders[].state should be updated and can be mutated. First initialization + // of the list is allowed. + // + // Each ResponderStatus is initialized by evictionrequest-controller and then managed by + // the designated responder. + Responders []ResponderStatusApplyConfiguration `json:"responders,omitempty"` +} + +// EvictionStatusApplyConfiguration constructs a declarative configuration of the EvictionStatus type for use with +// apply. +func EvictionStatus() *EvictionStatusApplyConfiguration { + return &EvictionStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *EvictionStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *EvictionStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithObservedGeneration sets the ObservedGeneration 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 ObservedGeneration field is set to the value of the last call. +func (b *EvictionStatusApplyConfiguration) WithObservedGeneration(value int64) *EvictionStatusApplyConfiguration { + b.ObservedGeneration = &value + return b +} + +// WithRequesters adds the given value to the Requesters field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Requesters field. +func (b *EvictionStatusApplyConfiguration) WithRequesters(values ...*RequesterApplyConfiguration) *EvictionStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithRequesters") + } + b.Requesters = append(b.Requesters, *values[i]) + } + return b +} + +// WithTargetResponders adds the given value to the TargetResponders field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the TargetResponders field. +func (b *EvictionStatusApplyConfiguration) WithTargetResponders(values ...*TargetResponderApplyConfiguration) *EvictionStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTargetResponders") + } + b.TargetResponders = append(b.TargetResponders, *values[i]) + } + return b +} + +// WithResponders adds the given value to the Responders field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Responders field. +func (b *EvictionStatusApplyConfiguration) WithResponders(values ...*ResponderStatusApplyConfiguration) *EvictionStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResponders") + } + b.Responders = append(b.Responders, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictiontarget.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictiontarget.go new file mode 100644 index 000000000..ff353caeb --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/evictiontarget.go @@ -0,0 +1,43 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +// EvictionTargetApplyConfiguration represents a declarative configuration of the EvictionTarget type for use +// with apply. +// +// EvictionTarget contains a reference to an object that should be evicted. +type EvictionTargetApplyConfiguration struct { + // pod references a pod that is subject to eviction/termination. + // Pods that are part of a PodGroup (.spec.schedulingGroup is set) are not supported. + Pod *EvictionPodReferenceApplyConfiguration `json:"pod,omitempty"` +} + +// EvictionTargetApplyConfiguration constructs a declarative configuration of the EvictionTarget type for use with +// apply. +func EvictionTarget() *EvictionTargetApplyConfiguration { + return &EvictionTargetApplyConfiguration{} +} + +// WithPod sets the Pod 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 Pod field is set to the value of the last call. +func (b *EvictionTargetApplyConfiguration) WithPod(value *EvictionPodReferenceApplyConfiguration) *EvictionTargetApplyConfiguration { + b.Pod = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/requester.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/requester.go new file mode 100644 index 000000000..3991be03e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/requester.go @@ -0,0 +1,68 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" +) + +// RequesterApplyConfiguration represents a declarative configuration of the Requester type for use +// with apply. +// +// Requester allows you to identify the entity, that requested the eviction of the target. +type RequesterApplyConfiguration struct { + // name allows you to identify the entity, that requested the eviction of the target. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each requester. + // This field is required. + Name *string `json:"name,omitempty"` + // intent specifies the action that should be taken for the specified target. + // + // - Eviction means that the requester is interested in the eviction of the target. + // - Withdrawn means that the requester is no longer interested in the eviction of the target. + // If all requesters' intents are withdrawn, the eviction will be canceled. + // Cancellation consequences: + // - Inactive responders will never run. + // - Active responders are expected to cancel the eviction. + // - Completed or Interrupted responders should not take any action. + Intent *lifecyclev1alpha1.RequesterIntent `json:"intent,omitempty"` +} + +// RequesterApplyConfiguration constructs a declarative configuration of the Requester type for use with +// apply. +func Requester() *RequesterApplyConfiguration { + return &RequesterApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *RequesterApplyConfiguration) WithName(value string) *RequesterApplyConfiguration { + b.Name = &value + return b +} + +// WithIntent sets the Intent 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 Intent field is set to the value of the last call. +func (b *RequesterApplyConfiguration) WithIntent(value lifecyclev1alpha1.RequesterIntent) *RequesterApplyConfiguration { + b.Intent = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/responderstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/responderstatus.go new file mode 100644 index 000000000..e7d41d667 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/responderstatus.go @@ -0,0 +1,118 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ResponderStatusApplyConfiguration represents a declarative configuration of the ResponderStatus type for use +// with apply. +// +// ResponderStatus represents the last observed status of the eviction process of the responder. +// It should be only updated by the designated responder whose name is .name field. +type ResponderStatusApplyConfiguration struct { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field is initialized by Kubernetes and must be unique for each responder. + // This field is required. + Name *string `json:"name,omitempty"` + // startTime tracks the time at which this responder was designated as active and should start + // processing the eviction request. + // It should reflect the present time when set. + // This field is initialized by Kubernetes when this responder becomes active. + // This field becomes immutable once set. + StartTime *v1.Time `json:"startTime,omitempty"` + // heartbeatTime is the last time at which the eviction process was reported to be in progress + // by the responder. + // It should reflect the present time when set. + // Responders should avoid heartbeats more frequent than 20 seconds to avoid overloading the + // control-plane. + HeartbeatTime *v1.Time `json:"heartbeatTime,omitempty"` + // expectedCompletionTime is the time at which the eviction process step is expected to end for the + // responder. + // The time cannot be set to the past. + // May be omitted if no estimate can be made. + ExpectedCompletionTime *v1.Time `json:"expectedCompletionTime,omitempty"` + // completionTime tracks the time at which the Responder stopped processing the eviction request. + // Completion means that the responders has either fully or partially completed the + // eviction process, which may have resulted in target eviction (e.g. pod termination). + // It should reflect the present time when set. + // This field becomes immutable once set. + CompletionTime *v1.Time `json:"completionTime,omitempty"` + // message provides human-readable details about the state of the responder and the eviction + // process. + // Maximum length is 4000 characters. + Message *string `json:"message,omitempty"` +} + +// ResponderStatusApplyConfiguration constructs a declarative configuration of the ResponderStatus type for use with +// apply. +func ResponderStatus() *ResponderStatusApplyConfiguration { + return &ResponderStatusApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithName(value string) *ResponderStatusApplyConfiguration { + b.Name = &value + return b +} + +// WithStartTime sets the StartTime 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 StartTime field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithStartTime(value v1.Time) *ResponderStatusApplyConfiguration { + b.StartTime = &value + return b +} + +// WithHeartbeatTime sets the HeartbeatTime 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 HeartbeatTime field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithHeartbeatTime(value v1.Time) *ResponderStatusApplyConfiguration { + b.HeartbeatTime = &value + return b +} + +// WithExpectedCompletionTime sets the ExpectedCompletionTime 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 ExpectedCompletionTime field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithExpectedCompletionTime(value v1.Time) *ResponderStatusApplyConfiguration { + b.ExpectedCompletionTime = &value + return b +} + +// WithCompletionTime sets the CompletionTime 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 CompletionTime field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithCompletionTime(value v1.Time) *ResponderStatusApplyConfiguration { + b.CompletionTime = &value + return b +} + +// WithMessage sets the Message 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 Message field is set to the value of the last call. +func (b *ResponderStatusApplyConfiguration) WithMessage(value string) *ResponderStatusApplyConfiguration { + b.Message = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/targetresponder.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/targetresponder.go new file mode 100644 index 000000000..a04690e78 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1/targetresponder.go @@ -0,0 +1,102 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" +) + +// TargetResponderApplyConfiguration represents a declarative configuration of the TargetResponder type for use +// with apply. +// +// TargetResponder allows you to specify the responder reacting to the Eviction. +// Responders should observe and communicate through the Eviction API (see .state) to help +// with the graceful eviction of a target (e.g. termination of a pod). +type TargetResponderApplyConfiguration struct { + // name allows you to identify the responder reacting to the Eviction. + // + // It must be a valid domain-prefixed key (such as "acme.io/foo"). + // This field must be unique for each responder. + // This field is required. + Name *string `json:"name,omitempty"` + // priority for this responder. Higher priorities are selected first by the evictionrequest-controller. + // If there are responders with the same priority, the responder whose domain name comes first in the + // alphabetical higher domain order, will be picked. This means that the top domain labels are compared + // alphabetically first, followed by the lower domain labels. The key is compared last. + // + // The responder that is the managing controller of the pod should set the value of + // this field to 10000 to allow both for preemption or fallback registration by other + // responders. + // + // The minimum value is 0 and the maximum value is 100000. + // The interval 0-999 is reserved for responders with *.k8s.io suffix. + // This field is required and immutable. + Priority *int32 `json:"priority,omitempty"` + // state specifies a state that is assigned by the evictionrequest-controller. Responders should observe + // this state in order to navigate their lifecycle. + // - Inactive means that the responder should not yet process this eviction request. + // - Active means that the responder is either running or expected to start soon. + // Also, startTime has been set in the ResponderStatus by the evictionrequest-controller. + // + // An active responder should currently interact with the eviction process by updating + // .status.responders, where .name is the active responder name. ResponderStatus fields + // should be periodically updated to indicate the progress or completion of the eviction process. + // If .status.responders[].heartbeatTime field is not updated within the heartbeat deadline defined + // by the Eviction API (currently 20 minutes), the eviction is passed over to the next responder + // with a lower priority. Only one responder can be active at a time. + // - Interrupted means that the responder has failed to start or failed to update + // heartbeatTime in ResponderStatus in a timely manner. + // - Canceled means that the responder has been canceled. In other words, there is no + // EvictionRequest with the same target and Eviction intent in .spec.intent. + // - Completed means that the responder has successfully completed and set completionTime + // in ResponderStatus. + // + // Please refer to the ResponderStatus in .status.responders for more details on each responder. + State *lifecyclev1alpha1.ResponderStateType `json:"state,omitempty"` +} + +// TargetResponderApplyConfiguration constructs a declarative configuration of the TargetResponder type for use with +// apply. +func TargetResponder() *TargetResponderApplyConfiguration { + return &TargetResponderApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *TargetResponderApplyConfiguration) WithName(value string) *TargetResponderApplyConfiguration { + b.Name = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *TargetResponderApplyConfiguration) WithPriority(value int32) *TargetResponderApplyConfiguration { + b.Priority = &value + return b +} + +// WithState sets the State 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 State field is set to the value of the last call. +func (b *TargetResponderApplyConfiguration) WithState(value lifecyclev1alpha1.ResponderStateType) *TargetResponderApplyConfiguration { + b.State = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/condition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/condition.go index 6b0a44312..11e0260ab 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/condition.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/condition.go @@ -36,6 +36,9 @@ import ( // // +patchStrategy=merge // // +listType=map // // +listMapKey=type +// // +k8s:alpha(since: "1.37")=+k8s:optional +// // +k8s:alpha(since: "1.37")=+k8s:listType=map +// // +k8s:alpha(since: "1.37")=+k8s:listMapKey=type // Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // // // other fields diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go index ed4c4bfa5..0679f1c8f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go @@ -27,7 +27,7 @@ import ( // // DeleteOptions may be provided when deleting an API object. type DeleteOptionsApplyConfiguration struct { - TypeMetaApplyConfiguration `json:",inline"` + TypeMetaApplyConfiguration `json:""` // The duration in seconds before the object should be deleted. Value must be non-negative integer. // The value zero indicates delete immediately. If this value is nil, the default grace period for the // specified type will be used. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go index e6bb92050..dad98cc87 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go @@ -35,8 +35,8 @@ import ( // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. type IngressApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the Ingress. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go index 387e45728..69da66c6c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go @@ -36,8 +36,8 @@ import ( // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. type IngressClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the IngressClass. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go index e77494d86..7a8ffbf8b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go @@ -53,7 +53,7 @@ type IngressRuleApplyConfiguration struct { // just traffic matching the host to the default backend or all traffic to the // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. - IngressRuleValueApplyConfiguration `json:",inline"` + IngressRuleValueApplyConfiguration `json:""` } // IngressRuleApplyConfiguration constructs a declarative configuration of the IngressRule type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go index c1ca4853e..198899ee6 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go @@ -26,6 +26,7 @@ package v1 // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. type IngressRuleValueApplyConfiguration struct { + // http is a HTTP IngressRuleValue, which contains a list of http selectors HTTP *HTTPIngressRuleValueApplyConfiguration `json:"http,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddress.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddress.go index c0e4298aa..8f73ecac7 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddress.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddress.go @@ -38,8 +38,8 @@ import ( // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 type IPAddressApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the IPAddress. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddressspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddressspec.go index e9dce93b6..30bb1dbea 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddressspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/ipaddressspec.go @@ -23,7 +23,7 @@ package v1 // // IPAddressSpec describe the attributes in an IP Address. type IPAddressSpecApplyConfiguration struct { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. ParentRef *ParentReferenceApplyConfiguration `json:"parentRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go index f3e1e1e5e..be8b78720 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go @@ -32,8 +32,8 @@ import ( // // NetworkPolicy describes what network traffic is allowed for a set of Pods type NetworkPolicyApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec represents the specification of the desired behavior for this NetworkPolicy. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/parentreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/parentreference.go index c725e697b..34756f07e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/parentreference.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/parentreference.go @@ -23,13 +23,13 @@ package v1 // // ParentReference describes a reference to a parent object. type ParentReferenceApplyConfiguration struct { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. Group *string `json:"group,omitempty"` - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. Resource *string `json:"resource,omitempty"` - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. Namespace *string `json:"namespace,omitempty"` - // Name is the name of the object being referenced. + // name is the name of the object being referenced. Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidr.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidr.go index 8eede13e3..158ca7f92 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidr.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidr.go @@ -33,8 +33,8 @@ import ( // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. type ServiceCIDRApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the ServiceCIDR. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidrspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidrspec.go index 9372a162b..084400834 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidrspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1/servicecidrspec.go @@ -23,7 +23,7 @@ package v1 // // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. type ServiceCIDRSpecApplyConfiguration struct { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. CIDRs []string `json:"cidrs,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go index 061c29c99..d2144ed9b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go @@ -35,8 +35,8 @@ import ( // externally-reachable urls, load balance traffic, terminate SSL, offer name // based virtual hosting etc. type IngressApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the Ingress. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go index c4d6df50b..30882d4ad 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go @@ -36,8 +36,8 @@ import ( // single IngressClass resource has this annotation set to true, new Ingress // resources without a class specified will be assigned this default class. type IngressClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the IngressClass. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go index 6c8b973ed..b84026d67 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go @@ -53,7 +53,7 @@ type IngressRuleApplyConfiguration struct { // just traffic matching the host to the default backend or all traffic to the // default backend, is left to the controller fulfilling the Ingress. Http is // currently the only supported IngressRuleValue. - IngressRuleValueApplyConfiguration `json:",inline"` + IngressRuleValueApplyConfiguration `json:""` } // IngressRuleApplyConfiguration constructs a declarative configuration of the IngressRule type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go index 502384fa3..e215effaf 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go @@ -26,6 +26,7 @@ package v1beta1 // mixing different types of rules in a single Ingress is disallowed, so exactly // one of the following must be set. type IngressRuleValueApplyConfiguration struct { + // http is a HTTP IngressRuleValue, which contains a list of http selectors HTTP *HTTPIngressRuleValueApplyConfiguration `json:"http,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddress.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddress.go index 28167f1f4..10919a97a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddress.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddress.go @@ -38,8 +38,8 @@ import ( // Valid: 192.168.1.5 or 2001:db8::1 or 2001:db8:aaaa:bbbb:cccc:dddd:eeee:1 // Invalid: 10.01.2.3 or 2001:db8:0:0:0::1 type IPAddressApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the IPAddress. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddressspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddressspec.go index c0c012aaa..7218076ba 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddressspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/ipaddressspec.go @@ -23,7 +23,7 @@ package v1beta1 // // IPAddressSpec describe the attributes in an IP Address. type IPAddressSpecApplyConfiguration struct { - // ParentRef references the resource that an IPAddress is attached to. + // parentRef references the resource that an IPAddress is attached to. // An IPAddress must reference a parent object. ParentRef *ParentReferenceApplyConfiguration `json:"parentRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/parentreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/parentreference.go index edcc3b95d..9acf5f747 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/parentreference.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/parentreference.go @@ -23,13 +23,13 @@ package v1beta1 // // ParentReference describes a reference to a parent object. type ParentReferenceApplyConfiguration struct { - // Group is the group of the object being referenced. + // group is the group of the object being referenced. Group *string `json:"group,omitempty"` - // Resource is the resource of the object being referenced. + // resource is the resource of the object being referenced. Resource *string `json:"resource,omitempty"` - // Namespace is the namespace of the object being referenced. + // namespace is the namespace of the object being referenced. Namespace *string `json:"namespace,omitempty"` - // Name is the name of the object being referenced. + // name is the name of the object being referenced. Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidr.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidr.go index 07281de61..68704740c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidr.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidr.go @@ -33,8 +33,8 @@ import ( // ServiceCIDR defines a range of IP addresses using CIDR format (e.g. 192.168.0.0/24 or 2001:db2::/64). // This range is used to allocate ClusterIPs to Service objects. type ServiceCIDRApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the desired state of the ServiceCIDR. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidrspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidrspec.go index 7652700e2..890dd1410 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidrspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/networking/v1beta1/servicecidrspec.go @@ -23,7 +23,7 @@ package v1beta1 // // ServiceCIDRSpec define the CIDRs the user wants to use for allocating ClusterIPs for Services. type ServiceCIDRSpecApplyConfiguration struct { - // CIDRs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") + // cidrs defines the IP blocks in CIDR notation (e.g. "192.168.0.0/24" or "2001:db8::/64") // from which to assign service cluster IPs. Max of two CIDRs is allowed, one of each IP family. // This field is immutable. CIDRs []string `json:"cidrs,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go index 6b33701ca..3a05a9894 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go @@ -38,7 +38,8 @@ import ( // pod. For more details, see // https://kubernetes.io/docs/concepts/containers/runtime-class/ type RuntimeClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // handler specifies the underlying runtime and configuration that the CRI diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go index 5fbf9a649..da0736e76 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go @@ -38,7 +38,8 @@ import ( // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class type RuntimeClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec represents specification of the RuntimeClass diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go index fc75967fc..a7d34d2c9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go @@ -38,7 +38,8 @@ import ( // pod. For more details, see // https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class type RuntimeClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // handler specifies the underlying runtime and configuration that the CRI diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go index bd944a5e8..a22952466 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go @@ -34,10 +34,10 @@ import ( // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. type EvictionApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // ObjectMeta describes the pod that is being evicted. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata describes the pod that is being evicted. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // DeleteOptions may be provided + // deleteOptions may be provided DeleteOptions *metav1.DeleteOptionsApplyConfiguration `json:"deleteOptions,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go index c9d4fd1a6..84f01bb1c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go @@ -32,13 +32,13 @@ import ( // // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods type PodDisruptionBudgetApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. Spec *PodDisruptionBudgetSpecApplyConfiguration `json:"spec,omitempty"` - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. Status *PodDisruptionBudgetStatusApplyConfiguration `json:"status,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go index 0d2307332..acc995b33 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go @@ -29,22 +29,22 @@ import ( // // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. type PodDisruptionBudgetSpecApplyConfiguration struct { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". MinAvailable *intstr.IntOrString `json:"minAvailable,omitempty"` - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector will match no pods, while an empty ({}) selector will select // all pods within the namespace. Selector *metav1.LabelSelectorApplyConfiguration `json:"selector,omitempty"` - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go index eeadbbcb7..333b0869f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go @@ -34,10 +34,10 @@ import ( // This is a subresource of Pod. A request to cause such an eviction is // created by POSTing to .../pods//evictions. type EvictionApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // ObjectMeta describes the pod that is being evicted. + v1.TypeMetaApplyConfiguration `json:""` + // metadata describes the pod that is being evicted. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // DeleteOptions may be provided + // deleteOptions may be provided DeleteOptions *v1.DeleteOptionsApplyConfiguration `json:"deleteOptions,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go index ca2d839da..54ee76894 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go @@ -32,13 +32,13 @@ import ( // // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods type PodDisruptionBudgetApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Specification of the desired behavior of the PodDisruptionBudget. + // spec is the specification of the desired behavior of the PodDisruptionBudget. Spec *PodDisruptionBudgetSpecApplyConfiguration `json:"spec,omitempty"` - // Most recently observed status of the PodDisruptionBudget. + // status is the most recently observed status of the PodDisruptionBudget. Status *PodDisruptionBudgetStatusApplyConfiguration `json:"status,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go index 1fe247b48..28914430f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go @@ -29,23 +29,23 @@ import ( // // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. type PodDisruptionBudgetSpecApplyConfiguration struct { - // An eviction is allowed if at least "minAvailable" pods selected by + // minAvailable indicates that an eviction is allowed if at least "minAvailable" pods selected by // "selector" will still be available after the eviction, i.e. even in the // absence of the evicted pod. So for example you can prevent all voluntary // evictions by specifying "100%". MinAvailable *intstr.IntOrString `json:"minAvailable,omitempty"` - // Label query over pods whose evictions are managed by the disruption + // selector is a label query over pods whose evictions are managed by the disruption // budget. // A null selector selects no pods. // An empty selector ({}) also selects no pods, which differs from standard behavior of selecting all pods. // In policy/v1, an empty selector will select all pods in the namespace. Selector *v1.LabelSelectorApplyConfiguration `json:"selector,omitempty"` - // An eviction is allowed if at most "maxUnavailable" pods selected by + // maxUnavailable indicates that an eviction is allowed if at most "maxUnavailable" pods selected by // "selector" are unavailable after the eviction, i.e. even in absence of // the evicted pod. For example, one can prevent all voluntary evictions // by specifying 0. This is a mutually exclusive setting with "minAvailable". MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` - // UnhealthyPodEvictionPolicy defines the criteria for when unhealthy pods + // unhealthyPodEvictionPolicy defines the criteria for when unhealthy pods // should be considered for eviction. Current implementation considers healthy pods, // as pods that have status.conditions item with type="Ready",status="True". // diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go index 6f44e7979..572b47741 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go @@ -27,7 +27,7 @@ import ( // // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRuleApplyConfiguration struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added ClusterRoleSelectors []metav1.LabelSelectorApplyConfiguration `json:"clusterRoleSelectors,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go index d65387e24..2f8395cf2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go @@ -32,12 +32,12 @@ import ( // // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. type ClusterRoleApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. AggregationRule *AggregationRuleApplyConfiguration `json:"aggregationRule,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go index 13d3d0201..f4327511c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go @@ -33,12 +33,12 @@ import ( // ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, // and adds who information via Subject. type ClusterRoleBindingApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go index 03556b01c..9685f7b27 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go @@ -28,16 +28,16 @@ package v1 // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRuleApplyConfiguration struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. Verbs []string `json:"verbs,omitempty"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. APIGroups []string `json:"apiGroups,omitempty"` - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. Resources []string `json:"resources,omitempty"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. NonResourceURLs []string `json:"nonResourceURLs,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/role.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/role.go index 9e2895b1a..fee603dff 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/role.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/role.go @@ -32,10 +32,10 @@ import ( // // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. type RoleApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go index 776fb3ed3..994779c8c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go @@ -34,12 +34,12 @@ import ( // It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given // namespace only have effect in that namespace. type RoleBindingApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. // This field is immutable. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go index 231fe0dd4..1df91726d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go @@ -23,11 +23,11 @@ package v1 // // RoleRef contains information that points to the role being used type RoleRefApplyConfiguration struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced APIGroup *string `json:"apiGroup,omitempty"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced Kind *string `json:"kind,omitempty"` - // Name is the name of resource being referenced + // name is the name of resource being referenced Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go index 1914086c0..1432b410a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go @@ -24,16 +24,16 @@ package v1 // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. type SubjectApplyConfiguration struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. Kind *string `json:"kind,omitempty"` - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. APIGroup *string `json:"apiGroup,omitempty"` - // Name of the object being referenced. + // name of the object being referenced. Name *string `json:"name,omitempty"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. Namespace *string `json:"namespace,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go index 397d14a1a..169cf984d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go @@ -27,7 +27,7 @@ import ( // // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRuleApplyConfiguration struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added ClusterRoleSelectors []v1.LabelSelectorApplyConfiguration `json:"clusterRoleSelectors,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go index 678761e6a..5cc806dea 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go @@ -33,12 +33,12 @@ import ( // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. type ClusterRoleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. AggregationRule *AggregationRuleApplyConfiguration `json:"aggregationRule,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go index f4ee74f18..fcfe3709e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go @@ -34,12 +34,12 @@ import ( // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. type ClusterRoleBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go index f4a6d3fff..7c4e9cca1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go @@ -28,16 +28,16 @@ package v1alpha1 // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRuleApplyConfiguration struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. Verbs []string `json:"verbs,omitempty"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. APIGroups []string `json:"apiGroups,omitempty"` - // Resources is a list of resources this rule applies to. '*' represents all resources. + // resources is a list of resources this rule applies to. '*' represents all resources. Resources []string `json:"resources,omitempty"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. NonResourceURLs []string `json:"nonResourceURLs,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go index 19b123b2d..b2f8ca8b2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go @@ -33,10 +33,10 @@ import ( // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. type RoleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go index 116f29376..b836c08a5 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go @@ -35,12 +35,12 @@ import ( // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. type RoleBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go index a02a36be8..25aab9379 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go @@ -23,11 +23,11 @@ package v1alpha1 // // RoleRef contains information that points to the role being used type RoleRefApplyConfiguration struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced APIGroup *string `json:"apiGroup,omitempty"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced Kind *string `json:"kind,omitempty"` - // Name is the name of resource being referenced + // name is the name of resource being referenced Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go index d24f865d4..51a5b4d4b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go @@ -24,16 +24,16 @@ package v1alpha1 // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. type SubjectApplyConfiguration struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. Kind *string `json:"kind,omitempty"` - // APIVersion holds the API group and version of the referenced subject. + // apiVersion holds the API group and version of the referenced subject. // Defaults to "v1" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io/v1alpha1" for User and Group subjects. APIVersion *string `json:"apiVersion,omitempty"` - // Name of the object being referenced. + // name of the object being referenced. Name *string `json:"name,omitempty"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. Namespace *string `json:"namespace,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go index b4c6bd5ae..8064db4dd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go @@ -27,7 +27,7 @@ import ( // // AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole type AggregationRuleApplyConfiguration struct { - // ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. + // clusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. // If any of the selectors match, then the ClusterRole's permissions will be added ClusterRoleSelectors []v1.LabelSelectorApplyConfiguration `json:"clusterRoleSelectors,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go index a105df5f0..dacb3b17b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go @@ -33,12 +33,12 @@ import ( // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRole, and will no longer be served in v1.22. type ClusterRoleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this ClusterRole + // rules holds all the PolicyRules for this ClusterRole Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` - // AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. + // aggregationRule is an optional field that describes how to build the Rules for this ClusterRole. // If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be // stomped by the controller. AggregationRule *AggregationRuleApplyConfiguration `json:"aggregationRule,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go index c519c6e07..0b400e124 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go @@ -34,12 +34,12 @@ import ( // and adds who information via Subject. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 ClusterRoleBinding, and will no longer be served in v1.22. type ClusterRoleBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can only reference a ClusterRole in the global namespace. + // roleRef can only reference a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go index bf3a5a508..c5cf6a8fc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go @@ -28,17 +28,17 @@ package v1beta1 // PolicyRule holds information that describes a policy rule, but does not contain information // about who the rule applies to or which namespace the rule applies to. type PolicyRuleApplyConfiguration struct { - // Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. + // verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs. Verbs []string `json:"verbs,omitempty"` - // APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of + // apiGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of // the enumerated resources in any API group will be allowed. "" represents the core API group and "*" represents all API groups. APIGroups []string `json:"apiGroups,omitempty"` - // Resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. + // resources is a list of resources this rule applies to. '*' represents all resources in the specified apiGroups. // '*/foo' represents the subresource 'foo' for all resources in the specified apiGroups. Resources []string `json:"resources,omitempty"` - // ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. + // resourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. ResourceNames []string `json:"resourceNames,omitempty"` - // NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path + // nonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"), but not both. NonResourceURLs []string `json:"nonResourceURLs,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go index d0a4c20c6..df72d643b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go @@ -33,10 +33,10 @@ import ( // Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 Role, and will no longer be served in v1.22. type RoleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Rules holds all the PolicyRules for this Role + // rules holds all the PolicyRules for this Role Rules []PolicyRuleApplyConfiguration `json:"rules,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go index 64669c103..f851aab7b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go @@ -35,12 +35,12 @@ import ( // namespace only have effect in that namespace. // Deprecated in v1.17 in favor of rbac.authorization.k8s.io/v1 RoleBinding, and will no longer be served in v1.22. type RoleBindingApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object's metadata. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Subjects holds references to the objects the role applies to. + // subjects holds references to the objects the role applies to. Subjects []SubjectApplyConfiguration `json:"subjects,omitempty"` - // RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. + // roleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. // If the RoleRef cannot be resolved, the Authorizer must return an error. RoleRef *RoleRefApplyConfiguration `json:"roleRef,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go index 350930af7..63d1c40c1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go @@ -23,11 +23,11 @@ package v1beta1 // // RoleRef contains information that points to the role being used type RoleRefApplyConfiguration struct { - // APIGroup is the group for the resource being referenced + // apiGroup is the group for the resource being referenced APIGroup *string `json:"apiGroup,omitempty"` - // Kind is the type of resource being referenced + // kind is the type of resource being referenced Kind *string `json:"kind,omitempty"` - // Name is the name of resource being referenced + // name is the name of resource being referenced Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go index 8abbaa9fb..083c8a1a2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go @@ -24,16 +24,16 @@ package v1beta1 // Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, // or a value for non-objects such as user and group names. type SubjectApplyConfiguration struct { - // Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". + // kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". // If the Authorizer does not recognized the kind value, the Authorizer should report an error. Kind *string `json:"kind,omitempty"` - // APIGroup holds the API group of the referenced subject. + // apiGroup holds the API group of the referenced subject. // Defaults to "" for ServiceAccount subjects. // Defaults to "rbac.authorization.k8s.io" for User and Group subjects. APIGroup *string `json:"apiGroup,omitempty"` - // Name of the object being referenced. + // name of the object being referenced. Name *string `json:"name,omitempty"` - // Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty + // namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty // the Authorizer should report an error. Namespace *string `json:"namespace,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/capacityrequestpolicyrange.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/capacityrequestpolicyrange.go index b3bade611..057b1dfd1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/capacityrequestpolicyrange.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/capacityrequestpolicyrange.go @@ -27,6 +27,13 @@ import ( // // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/celdeviceselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/celdeviceselector.go index 15ec20da4..d5ca19905 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/celdeviceselector.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/celdeviceselector.go @@ -33,7 +33,7 @@ type CELDeviceSelectorApplyConfiguration struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -66,6 +66,15 @@ type CELDeviceSelectorApplyConfiguration struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/device.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/device.go index f19b9000c..4ebb005fd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/device.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/device.go @@ -114,7 +114,7 @@ type DeviceApplyConfiguration struct { // If AllowMultipleAllocations is set to true, the device can be allocated more than once, // and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not. AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -125,7 +125,7 @@ type DeviceApplyConfiguration struct { // dependencies of an accelerator device. // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. - NodeAllocatableResourceMappings map[apicorev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration `json:"nodeAllocatableResourceMappings,omitempty"` + NodeAllocatableResources map[apicorev1.ResourceName]NodeAllocatableResourceApplyConfiguration `json:"nodeAllocatableResources,omitempty"` } // DeviceApplyConfiguration constructs a declarative configuration of the Device type for use with @@ -256,16 +256,16 @@ func (b *DeviceApplyConfiguration) WithAllowMultipleAllocations(value bool) *Dev return b } -// WithNodeAllocatableResourceMappings puts the entries into the NodeAllocatableResourceMappings field in the declarative configuration +// WithNodeAllocatableResources puts the entries into the NodeAllocatableResources field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResourceMappings field, -// overwriting an existing map entries in NodeAllocatableResourceMappings field with the same key. -func (b *DeviceApplyConfiguration) WithNodeAllocatableResourceMappings(entries map[apicorev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration) *DeviceApplyConfiguration { - if b.NodeAllocatableResourceMappings == nil && len(entries) > 0 { - b.NodeAllocatableResourceMappings = make(map[apicorev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration, len(entries)) +// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResources field, +// overwriting an existing map entries in NodeAllocatableResources field with the same key. +func (b *DeviceApplyConfiguration) WithNodeAllocatableResources(entries map[apicorev1.ResourceName]NodeAllocatableResourceApplyConfiguration) *DeviceApplyConfiguration { + if b.NodeAllocatableResources == nil && len(entries) > 0 { + b.NodeAllocatableResources = make(map[apicorev1.ResourceName]NodeAllocatableResourceApplyConfiguration, len(entries)) } for k, v := range entries { - b.NodeAllocatableResourceMappings[k] = v + b.NodeAllocatableResources[k] = v } return b } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceallocationconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceallocationconfiguration.go index 29e1ba427..2cfca606d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceallocationconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceallocationconfiguration.go @@ -38,7 +38,7 @@ type DeviceAllocationConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceAllocationConfigurationApplyConfiguration constructs a declarative configuration of the DeviceAllocationConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclaimconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclaimconfiguration.go index 402cd877c..2da820760 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclaimconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclaimconfiguration.go @@ -30,7 +30,7 @@ type DeviceClaimConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClaimConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClaimConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclass.go index 478f90bb0..49d6d7258 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclass.go @@ -35,7 +35,7 @@ import ( // the device requests of a claim to apply these presets. // Cluster scoped. type DeviceClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines what can be allocated and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassconfiguration.go index c47fd9f85..062cde2ab 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassconfiguration.go @@ -23,7 +23,7 @@ package v1 // // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfigurationApplyConfiguration struct { - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClassConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClassConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassspec.go index a6a3992c9..5e7d73619 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/deviceclassspec.go @@ -40,8 +40,6 @@ type DeviceClassSpecApplyConfiguration struct { // is picked to satisfy a pod's extended resource requests. // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. - // - // This is a beta field. ExtendedResourceName *string `json:"extendedResourceName,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicecounterconsumption.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicecounterconsumption.go index 9bcd936db..939894bea 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicecounterconsumption.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicecounterconsumption.go @@ -31,6 +31,26 @@ type DeviceCounterConsumptionApplyConfiguration struct { // // The maximum number of counters is 32. Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + CompatibilityGroups []string `json:"compatibilityGroups,omitempty"` } // DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with @@ -60,3 +80,13 @@ func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[st } return b } + +// WithCompatibilityGroups adds the given value to the CompatibilityGroups field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompatibilityGroups field. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCompatibilityGroups(values ...string) *DeviceCounterConsumptionApplyConfiguration { + for i := range values { + b.CompatibilityGroups = append(b.CompatibilityGroups, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicederivedattribute.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicederivedattribute.go new file mode 100644 index 000000000..9283a257d --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicederivedattribute.go @@ -0,0 +1,95 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" +) + +// DeviceDerivedAttributeApplyConfiguration represents a declarative configuration of the DeviceDerivedAttribute type for use +// with apply. +// +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttributeApplyConfiguration struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + Name *resourcev1.FullyQualifiedName `json:"name,omitempty"` + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + Expression *string `json:"expression,omitempty"` +} + +// DeviceDerivedAttributeApplyConfiguration constructs a declarative configuration of the DeviceDerivedAttribute type for use with +// apply. +func DeviceDerivedAttribute() *DeviceDerivedAttributeApplyConfiguration { + return &DeviceDerivedAttributeApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithName(value resourcev1.FullyQualifiedName) *DeviceDerivedAttributeApplyConfiguration { + b.Name = &value + return b +} + +// WithExpression sets the Expression 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 Expression field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithExpression(value string) *DeviceDerivedAttributeApplyConfiguration { + b.Expression = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicerequestallocationresult.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicerequestallocationresult.go index 592a64175..a32440eac 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicerequestallocationresult.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicerequestallocationresult.go @@ -94,6 +94,12 @@ type DeviceRequestAllocationResultApplyConfiguration struct { // This field is populated only for devices that allow multiple allocations. // All capacity entries are included, even if the consumed amount is zero. ConsumedCapacity map[resourcev1.QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + SkipNodeOperations []resourcev1.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with @@ -196,3 +202,13 @@ func (b *DeviceRequestAllocationResultApplyConfiguration) WithConsumedCapacity(e } return b } + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithSkipNodeOperations(values ...resourcev1.SkipNodeOperation) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicesubrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicesubrequest.go index d554522fa..74a7e9612 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicesubrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicesubrequest.go @@ -109,6 +109,27 @@ type DeviceSubRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with @@ -182,3 +203,16 @@ func (b *DeviceSubRequestApplyConfiguration) WithCapacity(value *CapacityRequire b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *DeviceSubRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrule.go new file mode 100644 index 000000000..e97d4855e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrule.go @@ -0,0 +1,294 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// DeviceTaintRuleApplyConfiguration represents a declarative configuration of the DeviceTaintRule type for use +// with apply. +// +// DeviceTaintRule adds one taint to all devices which match the selector. +// This has the same effect as if the taint was specified directly +// in the ResourceSlice by the DRA driver. +type DeviceTaintRuleApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:""` + // Standard object metadata + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // Spec specifies the selector and one taint. + // + // Changing the spec automatically increments the metadata.generation number. + Spec *DeviceTaintRuleSpecApplyConfiguration `json:"spec,omitempty"` + // Status provides information about what was requested in the spec. + Status *DeviceTaintRuleStatusApplyConfiguration `json:"status,omitempty"` +} + +// DeviceTaintRule constructs a declarative configuration of the DeviceTaintRule type for use with +// apply. +func DeviceTaintRule(name string) *DeviceTaintRuleApplyConfiguration { + b := &DeviceTaintRuleApplyConfiguration{} + b.WithName(name) + b.WithKind("DeviceTaintRule") + b.WithAPIVersion("resource.k8s.io/v1") + return b +} + +// ExtractDeviceTaintRuleFrom extracts the applied configuration owned by fieldManager from +// deviceTaintRule for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// deviceTaintRule must be a unmodified DeviceTaintRule API object that was retrieved from the Kubernetes API. +// ExtractDeviceTaintRuleFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractDeviceTaintRuleFrom(deviceTaintRule *resourcev1.DeviceTaintRule, fieldManager string, subresource string) (*DeviceTaintRuleApplyConfiguration, error) { + b := &DeviceTaintRuleApplyConfiguration{} + err := managedfields.ExtractInto(deviceTaintRule, internal.Parser().Type("io.k8s.api.resource.v1.DeviceTaintRule"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(deviceTaintRule.Name) + + b.WithKind("DeviceTaintRule") + b.WithAPIVersion("resource.k8s.io/v1") + return b, nil +} + +// ExtractDeviceTaintRule extracts the applied configuration owned by fieldManager from +// deviceTaintRule. If no managedFields are found in deviceTaintRule for fieldManager, a +// DeviceTaintRuleApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// deviceTaintRule must be a unmodified DeviceTaintRule API object that was retrieved from the Kubernetes API. +// ExtractDeviceTaintRule provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractDeviceTaintRule(deviceTaintRule *resourcev1.DeviceTaintRule, fieldManager string) (*DeviceTaintRuleApplyConfiguration, error) { + return ExtractDeviceTaintRuleFrom(deviceTaintRule, fieldManager, "") +} + +// ExtractDeviceTaintRuleStatus extracts the applied configuration owned by fieldManager from +// deviceTaintRule for the status subresource. +func ExtractDeviceTaintRuleStatus(deviceTaintRule *resourcev1.DeviceTaintRule, fieldManager string) (*DeviceTaintRuleApplyConfiguration, error) { + return ExtractDeviceTaintRuleFrom(deviceTaintRule, fieldManager, "status") +} + +func (b DeviceTaintRuleApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithKind(value string) *DeviceTaintRuleApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithAPIVersion(value string) *DeviceTaintRuleApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithName(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithGenerateName(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithNamespace(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithUID(value types.UID) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithResourceVersion(value string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithGeneration(value int64) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *DeviceTaintRuleApplyConfiguration) WithLabels(entries map[string]string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *DeviceTaintRuleApplyConfiguration) WithAnnotations(entries map[string]string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *DeviceTaintRuleApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *DeviceTaintRuleApplyConfiguration) WithFinalizers(values ...string) *DeviceTaintRuleApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *DeviceTaintRuleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithSpec(value *DeviceTaintRuleSpecApplyConfiguration) *DeviceTaintRuleApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *DeviceTaintRuleApplyConfiguration) WithStatus(value *DeviceTaintRuleStatusApplyConfiguration) *DeviceTaintRuleApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *DeviceTaintRuleApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *DeviceTaintRuleApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *DeviceTaintRuleApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *DeviceTaintRuleApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulespec.go new file mode 100644 index 000000000..694a5c4b2 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulespec.go @@ -0,0 +1,55 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// DeviceTaintRuleSpecApplyConfiguration represents a declarative configuration of the DeviceTaintRuleSpec type for use +// with apply. +// +// DeviceTaintRuleSpec specifies the selector and one taint. +type DeviceTaintRuleSpecApplyConfiguration struct { + // DeviceSelector defines which device(s) the taint is applied to. + // All selector criteria must be satisfied for a device to + // match. The empty selector matches all devices. Without + // a selector, no devices are matches. + DeviceSelector *DeviceTaintSelectorApplyConfiguration `json:"deviceSelector,omitempty"` + // The taint that gets applied to matching devices. + Taint *DeviceTaintApplyConfiguration `json:"taint,omitempty"` +} + +// DeviceTaintRuleSpecApplyConfiguration constructs a declarative configuration of the DeviceTaintRuleSpec type for use with +// apply. +func DeviceTaintRuleSpec() *DeviceTaintRuleSpecApplyConfiguration { + return &DeviceTaintRuleSpecApplyConfiguration{} +} + +// WithDeviceSelector sets the DeviceSelector 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 DeviceSelector field is set to the value of the last call. +func (b *DeviceTaintRuleSpecApplyConfiguration) WithDeviceSelector(value *DeviceTaintSelectorApplyConfiguration) *DeviceTaintRuleSpecApplyConfiguration { + b.DeviceSelector = value + return b +} + +// WithTaint sets the Taint 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 Taint field is set to the value of the last call. +func (b *DeviceTaintRuleSpecApplyConfiguration) WithTaint(value *DeviceTaintApplyConfiguration) *DeviceTaintRuleSpecApplyConfiguration { + b.Taint = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulestatus.go new file mode 100644 index 000000000..568cc205a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintrulestatus.go @@ -0,0 +1,70 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// DeviceTaintRuleStatusApplyConfiguration represents a declarative configuration of the DeviceTaintRuleStatus type for use +// with apply. +// +// DeviceTaintRuleStatus provides information about an on-going pod eviction. +type DeviceTaintRuleStatusApplyConfiguration struct { + // Conditions provide information about the state of the DeviceTaintRule + // and the cluster at some point in time, + // in a machine-readable and human-readable format. + // + // The following condition is currently defined as part of this API, more may + // get added: + // - Type: EvictionInProgress + // - Status: True if there are currently pods which need to be evicted, False otherwise + // (includes the effects which don't cause eviction). + // - Reason: not specified, may change + // - Message: includes information about number of pending pods and already evicted pods + // in a human-readable format, updated periodically, may change + // + // For `effect: None`, the condition above gets set once for each change to + // the spec, with the message containing information about what would happen + // if the effect was `NoExecute`. This feedback can be used to decide whether + // changing the effect to `NoExecute` will work as intended. It only gets + // set once to avoid having to constantly update the status. + // + // Must have 8 or fewer entries. + Conditions []metav1.ConditionApplyConfiguration `json:"conditions,omitempty"` +} + +// DeviceTaintRuleStatusApplyConfiguration constructs a declarative configuration of the DeviceTaintRuleStatus type for use with +// apply. +func DeviceTaintRuleStatus() *DeviceTaintRuleStatusApplyConfiguration { + return &DeviceTaintRuleStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *DeviceTaintRuleStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *DeviceTaintRuleStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintselector.go new file mode 100644 index 000000000..6d31934be --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/devicetaintselector.go @@ -0,0 +1,76 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// DeviceTaintSelectorApplyConfiguration represents a declarative configuration of the DeviceTaintSelector type for use +// with apply. +// +// DeviceTaintSelector defines which device(s) a DeviceTaintRule applies to. +// The empty selector matches all devices. Without a selector, no devices +// are matched. +type DeviceTaintSelectorApplyConfiguration struct { + // If driver is set, only devices from that driver are selected. + // This fields corresponds to slice.spec.driver. + Driver *string `json:"driver,omitempty"` + // If pool is set, only devices in that pool are selected. + // + // Also setting the driver name may be useful to avoid + // ambiguity when different drivers use the same pool name, + // but this is not required because selecting pools from + // different drivers may also be useful, for example when + // drivers with node-local devices use the node name as + // their pool name. + Pool *string `json:"pool,omitempty"` + // If device is set, only devices with that name are selected. + // This field corresponds to slice.spec.devices[].name. + // + // Setting also driver and pool may be required to avoid ambiguity, + // but is not required. + Device *string `json:"device,omitempty"` +} + +// DeviceTaintSelectorApplyConfiguration constructs a declarative configuration of the DeviceTaintSelector type for use with +// apply. +func DeviceTaintSelector() *DeviceTaintSelectorApplyConfiguration { + return &DeviceTaintSelectorApplyConfiguration{} +} + +// WithDriver sets the Driver 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 Driver field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithDriver(value string) *DeviceTaintSelectorApplyConfiguration { + b.Driver = &value + return b +} + +// WithPool sets the Pool 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 Pool field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithPool(value string) *DeviceTaintSelectorApplyConfiguration { + b.Pool = &value + return b +} + +// WithDevice sets the Device 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 Device field is set to the value of the last call. +func (b *DeviceTaintSelectorApplyConfiguration) WithDevice(value string) *DeviceTaintSelectorApplyConfiguration { + b.Device = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/exactdevicerequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/exactdevicerequest.go index 8eb0fd352..68b3c2d40 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/exactdevicerequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/exactdevicerequest.go @@ -106,6 +106,27 @@ type ExactDeviceRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // ExactDeviceRequestApplyConfiguration constructs a declarative configuration of the ExactDeviceRequest type for use with @@ -179,3 +200,16 @@ func (b *ExactDeviceRequestApplyConfiguration) WithCapacity(value *CapacityRequi b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *ExactDeviceRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *ExactDeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatablemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatablemapping.go new file mode 100644 index 000000000..69ba07d5d --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatablemapping.go @@ -0,0 +1,90 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableMapping type for use +// with apply. +// +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMappingApplyConfiguration struct { + // CapacityKey references a capacity name defined as a key in the + // `spec.devices[*].capacity` map. When this field is set, the value associated with + // this key in the `status.allocation.devices.results[*].consumedCapacity` map + // (for a specific claim allocation) determines the base quantity for + // the node allocatable resource. `capacityMultiplier` must also be set and is + // multiplied with the base quantity. + // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", + // and this field is set to "dra.example.com/memory", then for a claim allocation + // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + CapacityKey *resourcev1.QualifiedName `json:"capacityKey,omitempty"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty"` + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty"` +} + +// NodeAllocatableMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableMapping type for use with +// apply. +func NodeAllocatableMapping() *NodeAllocatableMappingApplyConfiguration { + return &NodeAllocatableMappingApplyConfiguration{} +} + +// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityKey(value resourcev1.QualifiedName) *NodeAllocatableMappingApplyConfiguration { + b.CapacityKey = &value + return b +} + +// WithCapacityMultiplier sets the CapacityMultiplier 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 CapacityMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.CapacityMultiplier = &value + return b +} + +// WithDeviceMultiplier sets the DeviceMultiplier 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 DeviceMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithDeviceMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.DeviceMultiplier = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableoverhead.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableoverhead.go new file mode 100644 index 000000000..120fb94f2 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableoverhead.go @@ -0,0 +1,67 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableOverheadApplyConfiguration represents a declarative configuration of the NodeAllocatableOverhead type for use +// with apply. +// +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverheadApplyConfiguration struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + PerPod *resource.Quantity `json:"perPod,omitempty"` + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + PerContainer *resource.Quantity `json:"perContainer,omitempty"` +} + +// NodeAllocatableOverheadApplyConfiguration constructs a declarative configuration of the NodeAllocatableOverhead type for use with +// apply. +func NodeAllocatableOverhead() *NodeAllocatableOverheadApplyConfiguration { + return &NodeAllocatableOverheadApplyConfiguration{} +} + +// WithPerPod sets the PerPod 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 PerPod field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerPod(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerPod = &value + return b +} + +// WithPerContainer sets the PerContainer 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 PerContainer field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerContainer(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerContainer = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresource.go new file mode 100644 index 000000000..fc13ebdde --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresource.go @@ -0,0 +1,65 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// NodeAllocatableResourceApplyConfiguration represents a declarative configuration of the NodeAllocatableResource type for use +// with apply. +// +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResourceApplyConfiguration struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + Mapping *NodeAllocatableMappingApplyConfiguration `json:"mapping,omitempty"` + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + Overhead *NodeAllocatableOverheadApplyConfiguration `json:"overhead,omitempty"` +} + +// NodeAllocatableResourceApplyConfiguration constructs a declarative configuration of the NodeAllocatableResource type for use with +// apply. +func NodeAllocatableResource() *NodeAllocatableResourceApplyConfiguration { + return &NodeAllocatableResourceApplyConfiguration{} +} + +// WithMapping sets the Mapping 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 Mapping field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithMapping(value *NodeAllocatableMappingApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Mapping = value + return b +} + +// WithOverhead sets the Overhead 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 Overhead field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithOverhead(value *NodeAllocatableOverheadApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Overhead = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresourcemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresourcemapping.go deleted file mode 100644 index 600d96af8..000000000 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/nodeallocatableresourcemapping.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by applyconfiguration-gen. DO NOT EDIT. - -package v1 - -import ( - resourcev1 "k8s.io/api/resource/v1" - resource "k8s.io/apimachinery/pkg/api/resource" -) - -// NodeAllocatableResourceMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableResourceMapping type for use -// with apply. -// -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMappingApplyConfiguration struct { - // CapacityKey references a capacity name defined as a key in the - // `spec.devices[*].capacity` map. When this field is set, the value associated with - // this key in the `status.allocation.devices.results[*].consumedCapacity` map - // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is - // multiplied with the base quantity. - // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", - // and this field is set to "dra.example.com/memory", then for a claim allocation - // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". - CapacityKey *resourcev1.QualifiedName `json:"capacityKey,omitempty"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty"` -} - -// NodeAllocatableResourceMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableResourceMapping type for use with -// apply. -func NodeAllocatableResourceMapping() *NodeAllocatableResourceMappingApplyConfiguration { - return &NodeAllocatableResourceMappingApplyConfiguration{} -} - -// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithCapacityKey(value resourcev1.QualifiedName) *NodeAllocatableResourceMappingApplyConfiguration { - b.CapacityKey = &value - return b -} - -// WithAllocationMultiplier sets the AllocationMultiplier 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 AllocationMultiplier field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithAllocationMultiplier(value resource.Quantity) *NodeAllocatableResourceMappingApplyConfiguration { - b.AllocationMultiplier = &value - return b -} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaim.go index 5a87ea3cb..ec3504e62 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaim.go @@ -36,7 +36,7 @@ import ( // stanza tracks whether this claim has been satisfied and what specific // resources have been allocated. type ResourceClaimApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec describes what is being requested and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaimtemplate.go index cee18f379..2f2fa2506 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceclaimtemplate.go @@ -32,7 +32,7 @@ import ( // // ResourceClaimTemplate is used to produce ResourceClaim objects. type ResourceClaimTemplateApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Describes the ResourceClaim that is to be generated. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourcepool.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourcepool.go index 2c779f3ca..4dce50617 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourcepool.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourcepool.go @@ -25,6 +25,8 @@ package v1 type ResourcePoolApplyConfiguration struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslice.go index 7a3eec9d5..d7eb3d689 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslice.go @@ -52,7 +52,7 @@ import ( // For resources that are not local to a node, the node name is not set. Instead, // the driver may use a node selector to specify where the devices are available. type ResourceSliceApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` + metav1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Contains the information published by the driver. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslicespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslicespec.go index b268fc8d7..a7c858e0e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslicespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1/resourceslicespec.go @@ -19,6 +19,7 @@ limitations under the License. package v1 import ( + resourcev1 "k8s.io/api/resource/v1" corev1 "k8s.io/client-go/applyconfigurations/core/v1" ) @@ -82,6 +83,28 @@ type ResourceSliceSpecApplyConfiguration struct { // // The maximum number of counter sets is 8. SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + PartitionTypeAttribute *resourcev1.FullyQualifiedName `json:"partitionTypeAttribute,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + SkipNodeOperations []resourcev1.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with @@ -163,3 +186,21 @@ func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*Coun } return b } + +// WithPartitionTypeAttribute sets the PartitionTypeAttribute 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 PartitionTypeAttribute field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPartitionTypeAttribute(value resourcev1.FullyQualifiedName) *ResourceSliceSpecApplyConfiguration { + b.PartitionTypeAttribute = &value + return b +} + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *ResourceSliceSpecApplyConfiguration) WithSkipNodeOperations(values ...resourcev1.SkipNodeOperation) *ResourceSliceSpecApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/devicetaintrule.go index b28d015de..4824d6ccf 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/devicetaintrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/devicetaintrule.go @@ -34,7 +34,7 @@ import ( // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. type DeviceTaintRuleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec specifies the selector and one taint. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/partitiontypestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/partitiontypestatus.go new file mode 100644 index 000000000..f6222c71f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/partitiontypestatus.go @@ -0,0 +1,77 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// PartitionTypeStatusApplyConfiguration represents a declarative configuration of the PartitionTypeStatus type for use +// with apply. +// +// PartitionTypeStatus reports allocatability for a single partition type, +// identified by the value of a grouping attribute. +type PartitionTypeStatusApplyConfiguration struct { + // Attribute is the fully qualified name of the device attribute whose value + // groups this entry. It is the PartitionTypeAttribute declared by the + // devices' own slice, or the default named in the request when their slice + // declares none. + Attribute *string `json:"attribute,omitempty"` + // Type is the partition type value (e.g. "Full" or "Half"). + Type *string `json:"type,omitempty"` + // Total is the number of devices of this partition type in the pool. + Total *int32 `json:"total,omitempty"` + // Allocatable is the number of additional devices of this partition type + // that could still be allocated given current shared-counter consumption. + Allocatable *int32 `json:"allocatable,omitempty"` +} + +// PartitionTypeStatusApplyConfiguration constructs a declarative configuration of the PartitionTypeStatus type for use with +// apply. +func PartitionTypeStatus() *PartitionTypeStatusApplyConfiguration { + return &PartitionTypeStatusApplyConfiguration{} +} + +// WithAttribute sets the Attribute 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 Attribute field is set to the value of the last call. +func (b *PartitionTypeStatusApplyConfiguration) WithAttribute(value string) *PartitionTypeStatusApplyConfiguration { + b.Attribute = &value + return b +} + +// WithType sets the Type 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 Type field is set to the value of the last call. +func (b *PartitionTypeStatusApplyConfiguration) WithType(value string) *PartitionTypeStatusApplyConfiguration { + b.Type = &value + return b +} + +// WithTotal sets the Total 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 Total field is set to the value of the last call. +func (b *PartitionTypeStatusApplyConfiguration) WithTotal(value int32) *PartitionTypeStatusApplyConfiguration { + b.Total = &value + return b +} + +// WithAllocatable sets the Allocatable 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 Allocatable field is set to the value of the last call. +func (b *PartitionTypeStatusApplyConfiguration) WithAllocatable(value int32) *PartitionTypeStatusApplyConfiguration { + b.Allocatable = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/poolstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/poolstatus.go index 343fe8247..3daeed07d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/poolstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/poolstatus.go @@ -63,6 +63,19 @@ type PoolStatusApplyConfiguration struct { // validated (e.g., incomplete slice publication). When set, device // count fields and ResourceSliceCount may be unset. ValidationError *string `json:"validationError,omitempty"` + // PartitionSummary reports allocatability per (attribute, partition type) + // for a partitionable pool that publishes SharedCounters. Each entry names + // the grouping attribute it was resolved from: the PartitionTypeAttribute + // declared by a device's own slice, or for devices whose slice declares + // none, the default named in the request. A pool that mixes partitions + // declared under different attributes reports each independently. When no + // slice declares an attribute and the request names no default, the pool + // reports no partition summary. + PartitionSummary []PartitionTypeStatusApplyConfiguration `json:"partitionSummary,omitempty"` + // ShareableSummary reports aggregate capacity for a pool that contains + // devices with AllowMultipleAllocations. It is populated only when at + // least one device in the pool is shareable. + ShareableSummary *ShareableSummaryStatusApplyConfiguration `json:"shareableSummary,omitempty"` } // PoolStatusApplyConfiguration constructs a declarative configuration of the PoolStatus type for use with @@ -150,3 +163,24 @@ func (b *PoolStatusApplyConfiguration) WithValidationError(value string) *PoolSt b.ValidationError = &value return b } + +// WithPartitionSummary adds the given value to the PartitionSummary field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the PartitionSummary field. +func (b *PoolStatusApplyConfiguration) WithPartitionSummary(values ...*PartitionTypeStatusApplyConfiguration) *PoolStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithPartitionSummary") + } + b.PartitionSummary = append(b.PartitionSummary, *values[i]) + } + return b +} + +// WithShareableSummary sets the ShareableSummary 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 ShareableSummary field is set to the value of the last call. +func (b *PoolStatusApplyConfiguration) WithShareableSummary(value *ShareableSummaryStatusApplyConfiguration) *PoolStatusApplyConfiguration { + b.ShareableSummary = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequest.go index aee4d0ed9..e5b82c28a 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequest.go @@ -34,7 +34,7 @@ import ( // based on the provided filters. Once status is set, the request is considered complete and will not be reprocessed. // Users should delete and recreate requests to get updated information. type ResourcePoolStatusRequestApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines the filters for which pools to include in the status. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequestspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequestspec.go index bb8672732..85fd362a2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequestspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/resourcepoolstatusrequestspec.go @@ -40,6 +40,19 @@ type ResourcePoolStatusRequestSpecApplyConfiguration struct { // Minimum: 1 // Maximum: 1000 Limit *int32 `json:"limit,omitempty"` + // DefaultPartitionTypeAttribute optionally names a device attribute (by its + // fully qualified name, e.g. "gpu.example.com/profile") to use as the default + // grouping attribute for partitionable devices whose slice has not declared + // one themselves. + // + // A slice's own PartitionTypeAttribute always takes precedence. This default + // applies only to devices whose slice does not declare one, so that a request + // can still get an accurate partitionSummary from a driver that has not + // been updated to declare it. When neither the slice nor this default names + // an attribute, a partitionable pool reports no partitionSummary. + // + // Must include the domain qualifier. + DefaultPartitionTypeAttribute *string `json:"defaultPartitionTypeAttribute,omitempty"` } // ResourcePoolStatusRequestSpecApplyConfiguration constructs a declarative configuration of the ResourcePoolStatusRequestSpec type for use with @@ -71,3 +84,11 @@ func (b *ResourcePoolStatusRequestSpecApplyConfiguration) WithLimit(value int32) b.Limit = &value return b } + +// WithDefaultPartitionTypeAttribute sets the DefaultPartitionTypeAttribute 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 DefaultPartitionTypeAttribute field is set to the value of the last call. +func (b *ResourcePoolStatusRequestSpecApplyConfiguration) WithDefaultPartitionTypeAttribute(value string) *ResourcePoolStatusRequestSpecApplyConfiguration { + b.DefaultPartitionTypeAttribute = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablecapacitystatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablecapacitystatus.go new file mode 100644 index 000000000..1e9089637 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablecapacitystatus.go @@ -0,0 +1,77 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// ShareableCapacityStatusApplyConfiguration represents a declarative configuration of the ShareableCapacityStatus type for use +// with apply. +// +// ShareableCapacityStatus reports aggregate amounts for a single shareable +// capacity key. +type ShareableCapacityStatusApplyConfiguration struct { + // Name is the capacity name. + Name *string `json:"name,omitempty"` + // Total is the sum of this capacity across shareable devices in the pool. + Total *resource.Quantity `json:"total,omitempty"` + // Consumed is the amount drawn by current allocations. + Consumed *resource.Quantity `json:"consumed,omitempty"` + // Available is Total minus Consumed, never negative. + Available *resource.Quantity `json:"available,omitempty"` +} + +// ShareableCapacityStatusApplyConfiguration constructs a declarative configuration of the ShareableCapacityStatus type for use with +// apply. +func ShareableCapacityStatus() *ShareableCapacityStatusApplyConfiguration { + return &ShareableCapacityStatusApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *ShareableCapacityStatusApplyConfiguration) WithName(value string) *ShareableCapacityStatusApplyConfiguration { + b.Name = &value + return b +} + +// WithTotal sets the Total 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 Total field is set to the value of the last call. +func (b *ShareableCapacityStatusApplyConfiguration) WithTotal(value resource.Quantity) *ShareableCapacityStatusApplyConfiguration { + b.Total = &value + return b +} + +// WithConsumed sets the Consumed 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 Consumed field is set to the value of the last call. +func (b *ShareableCapacityStatusApplyConfiguration) WithConsumed(value resource.Quantity) *ShareableCapacityStatusApplyConfiguration { + b.Consumed = &value + return b +} + +// WithAvailable sets the Available 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 Available field is set to the value of the last call. +func (b *ShareableCapacityStatusApplyConfiguration) WithAvailable(value resource.Quantity) *ShareableCapacityStatusApplyConfiguration { + b.Available = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablesummarystatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablesummarystatus.go new file mode 100644 index 000000000..0a5293427 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1alpha3/shareablesummarystatus.go @@ -0,0 +1,71 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// ShareableSummaryStatusApplyConfiguration represents a declarative configuration of the ShareableSummaryStatus type for use +// with apply. +// +// ShareableSummaryStatus reports aggregate capacity for a pool that contains +// devices with AllowMultipleAllocations. +type ShareableSummaryStatusApplyConfiguration struct { + // FullyAvailableDevices is the number of shareable devices with no + // capacity consumed. + FullyAvailableDevices *int32 `json:"fullyAvailableDevices,omitempty"` + // PartiallyAvailableDevices is the number of shareable devices with some + // but not all capacity consumed. + PartiallyAvailableDevices *int32 `json:"partiallyAvailableDevices,omitempty"` + // Capacity reports aggregate total, consumed, and available amounts per + // shareable capacity key across the pool. + Capacity []ShareableCapacityStatusApplyConfiguration `json:"capacity,omitempty"` +} + +// ShareableSummaryStatusApplyConfiguration constructs a declarative configuration of the ShareableSummaryStatus type for use with +// apply. +func ShareableSummaryStatus() *ShareableSummaryStatusApplyConfiguration { + return &ShareableSummaryStatusApplyConfiguration{} +} + +// WithFullyAvailableDevices sets the FullyAvailableDevices 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 FullyAvailableDevices field is set to the value of the last call. +func (b *ShareableSummaryStatusApplyConfiguration) WithFullyAvailableDevices(value int32) *ShareableSummaryStatusApplyConfiguration { + b.FullyAvailableDevices = &value + return b +} + +// WithPartiallyAvailableDevices sets the PartiallyAvailableDevices 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 PartiallyAvailableDevices field is set to the value of the last call. +func (b *ShareableSummaryStatusApplyConfiguration) WithPartiallyAvailableDevices(value int32) *ShareableSummaryStatusApplyConfiguration { + b.PartiallyAvailableDevices = &value + return b +} + +// WithCapacity adds the given value to the Capacity field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Capacity field. +func (b *ShareableSummaryStatusApplyConfiguration) WithCapacity(values ...*ShareableCapacityStatusApplyConfiguration) *ShareableSummaryStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithCapacity") + } + b.Capacity = append(b.Capacity, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/basicdevice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/basicdevice.go index 64527b293..5d4c565e8 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/basicdevice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/basicdevice.go @@ -110,7 +110,7 @@ type BasicDeviceApplyConfiguration struct { // If AllowMultipleAllocations is set to true, the device can be allocated more than once, // and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not. AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -121,7 +121,7 @@ type BasicDeviceApplyConfiguration struct { // dependencies of an accelerator device. // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. - NodeAllocatableResourceMappings map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration `json:"nodeAllocatableResourceMappings,omitempty"` + NodeAllocatableResources map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration `json:"nodeAllocatableResources,omitempty"` } // BasicDeviceApplyConfiguration constructs a declarative configuration of the BasicDevice type for use with @@ -244,16 +244,16 @@ func (b *BasicDeviceApplyConfiguration) WithAllowMultipleAllocations(value bool) return b } -// WithNodeAllocatableResourceMappings puts the entries into the NodeAllocatableResourceMappings field in the declarative configuration +// WithNodeAllocatableResources puts the entries into the NodeAllocatableResources field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResourceMappings field, -// overwriting an existing map entries in NodeAllocatableResourceMappings field with the same key. -func (b *BasicDeviceApplyConfiguration) WithNodeAllocatableResourceMappings(entries map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration) *BasicDeviceApplyConfiguration { - if b.NodeAllocatableResourceMappings == nil && len(entries) > 0 { - b.NodeAllocatableResourceMappings = make(map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration, len(entries)) +// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResources field, +// overwriting an existing map entries in NodeAllocatableResources field with the same key. +func (b *BasicDeviceApplyConfiguration) WithNodeAllocatableResources(entries map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration) *BasicDeviceApplyConfiguration { + if b.NodeAllocatableResources == nil && len(entries) > 0 { + b.NodeAllocatableResources = make(map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration, len(entries)) } for k, v := range entries { - b.NodeAllocatableResourceMappings[k] = v + b.NodeAllocatableResources[k] = v } return b } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/capacityrequestpolicyrange.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/capacityrequestpolicyrange.go index cddfe6daf..9216d4deb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/capacityrequestpolicyrange.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/capacityrequestpolicyrange.go @@ -27,6 +27,13 @@ import ( // // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/celdeviceselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/celdeviceselector.go index ba65467ae..40663836d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/celdeviceselector.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/celdeviceselector.go @@ -33,7 +33,7 @@ type CELDeviceSelectorApplyConfiguration struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -66,6 +66,15 @@ type CELDeviceSelectorApplyConfiguration struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceallocationconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceallocationconfiguration.go index 314ff5fa7..f26f528fb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceallocationconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceallocationconfiguration.go @@ -38,7 +38,7 @@ type DeviceAllocationConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceAllocationConfigurationApplyConfiguration constructs a declarative configuration of the DeviceAllocationConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclaimconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclaimconfiguration.go index 2c7faab5b..1b094a80c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclaimconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclaimconfiguration.go @@ -30,7 +30,7 @@ type DeviceClaimConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClaimConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClaimConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclass.go index b0fcbac6f..a242986f9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclass.go @@ -38,7 +38,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type DeviceClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines what can be allocated and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassconfiguration.go index d521f01e1..b87b5407c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassconfiguration.go @@ -23,7 +23,7 @@ package v1beta1 // // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfigurationApplyConfiguration struct { - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClassConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClassConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassspec.go index c234bdd73..d01256a3e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/deviceclassspec.go @@ -40,8 +40,6 @@ type DeviceClassSpecApplyConfiguration struct { // is picked to satisfy a pod's extended resource requests. // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. - // - // This is a beta field. ExtendedResourceName *string `json:"extendedResourceName,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicecounterconsumption.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicecounterconsumption.go index 1b1956c5c..667a88bd1 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicecounterconsumption.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicecounterconsumption.go @@ -31,6 +31,26 @@ type DeviceCounterConsumptionApplyConfiguration struct { // // The maximum number of counters is 32. Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + CompatibilityGroups []string `json:"compatibilityGroups,omitempty"` } // DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with @@ -60,3 +80,13 @@ func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[st } return b } + +// WithCompatibilityGroups adds the given value to the CompatibilityGroups field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompatibilityGroups field. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCompatibilityGroups(values ...string) *DeviceCounterConsumptionApplyConfiguration { + for i := range values { + b.CompatibilityGroups = append(b.CompatibilityGroups, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicederivedattribute.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicederivedattribute.go new file mode 100644 index 000000000..0c560d70b --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicederivedattribute.go @@ -0,0 +1,95 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" +) + +// DeviceDerivedAttributeApplyConfiguration represents a declarative configuration of the DeviceDerivedAttribute type for use +// with apply. +// +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttributeApplyConfiguration struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + Name *resourcev1beta1.FullyQualifiedName `json:"name,omitempty"` + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + Expression *string `json:"expression,omitempty"` +} + +// DeviceDerivedAttributeApplyConfiguration constructs a declarative configuration of the DeviceDerivedAttribute type for use with +// apply. +func DeviceDerivedAttribute() *DeviceDerivedAttributeApplyConfiguration { + return &DeviceDerivedAttributeApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithName(value resourcev1beta1.FullyQualifiedName) *DeviceDerivedAttributeApplyConfiguration { + b.Name = &value + return b +} + +// WithExpression sets the Expression 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 Expression field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithExpression(value string) *DeviceDerivedAttributeApplyConfiguration { + b.Expression = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequest.go index fdcb928a5..caa52fcd2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequest.go @@ -149,6 +149,27 @@ type DeviceRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // DeviceRequestApplyConfiguration constructs a declarative configuration of the DeviceRequest type for use with @@ -243,3 +264,16 @@ func (b *DeviceRequestApplyConfiguration) WithCapacity(value *CapacityRequiremen b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *DeviceRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *DeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go index 3a47b9c1f..d356dd841 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicerequestallocationresult.go @@ -95,6 +95,12 @@ type DeviceRequestAllocationResultApplyConfiguration struct { // This field is populated only for devices that allow multiple allocations. // All capacity entries are included, even if the consumed amount is zero. ConsumedCapacity map[resourcev1beta1.QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + SkipNodeOperations []resourcev1beta1.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with @@ -197,3 +203,13 @@ func (b *DeviceRequestAllocationResultApplyConfiguration) WithConsumedCapacity(e } return b } + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithSkipNodeOperations(values ...resourcev1beta1.SkipNodeOperation) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicesubrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicesubrequest.go index ae7bf65a0..3810b539f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicesubrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/devicesubrequest.go @@ -110,6 +110,27 @@ type DeviceSubRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with @@ -183,3 +204,16 @@ func (b *DeviceSubRequestApplyConfiguration) WithCapacity(value *CapacityRequire b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *DeviceSubRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatablemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatablemapping.go new file mode 100644 index 000000000..a95af3ab6 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatablemapping.go @@ -0,0 +1,90 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableMapping type for use +// with apply. +// +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices or the specific capacity consumed. These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMappingApplyConfiguration struct { + // CapacityKey references a capacity name defined as a key in the + // `spec.devices[*].capacity` map. When this field is set, the value associated with + // this key in the `status.allocation.devices.results[*].consumedCapacity` map + // (for a specific claim allocation) determines the base quantity for + // the node allocatable resource. `capacityMultiplier` must also be set and is + // multiplied with the base quantity. + // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", + // and this field is set to "dra.example.com/memory", then for a claim allocation + // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + CapacityKey *resourcev1beta1.QualifiedName `json:"capacityKey,omitempty"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty"` + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty"` +} + +// NodeAllocatableMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableMapping type for use with +// apply. +func NodeAllocatableMapping() *NodeAllocatableMappingApplyConfiguration { + return &NodeAllocatableMappingApplyConfiguration{} +} + +// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityKey(value resourcev1beta1.QualifiedName) *NodeAllocatableMappingApplyConfiguration { + b.CapacityKey = &value + return b +} + +// WithCapacityMultiplier sets the CapacityMultiplier 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 CapacityMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.CapacityMultiplier = &value + return b +} + +// WithDeviceMultiplier sets the DeviceMultiplier 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 DeviceMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithDeviceMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.DeviceMultiplier = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableoverhead.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableoverhead.go new file mode 100644 index 000000000..00526a925 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableoverhead.go @@ -0,0 +1,67 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableOverheadApplyConfiguration represents a declarative configuration of the NodeAllocatableOverhead type for use +// with apply. +// +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverheadApplyConfiguration struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + PerPod *resource.Quantity `json:"perPod,omitempty"` + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + PerContainer *resource.Quantity `json:"perContainer,omitempty"` +} + +// NodeAllocatableOverheadApplyConfiguration constructs a declarative configuration of the NodeAllocatableOverhead type for use with +// apply. +func NodeAllocatableOverhead() *NodeAllocatableOverheadApplyConfiguration { + return &NodeAllocatableOverheadApplyConfiguration{} +} + +// WithPerPod sets the PerPod 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 PerPod field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerPod(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerPod = &value + return b +} + +// WithPerContainer sets the PerContainer 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 PerContainer field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerContainer(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerContainer = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresource.go new file mode 100644 index 000000000..11df524b9 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresource.go @@ -0,0 +1,65 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// NodeAllocatableResourceApplyConfiguration represents a declarative configuration of the NodeAllocatableResource type for use +// with apply. +// +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResourceApplyConfiguration struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + Mapping *NodeAllocatableMappingApplyConfiguration `json:"mapping,omitempty"` + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + Overhead *NodeAllocatableOverheadApplyConfiguration `json:"overhead,omitempty"` +} + +// NodeAllocatableResourceApplyConfiguration constructs a declarative configuration of the NodeAllocatableResource type for use with +// apply. +func NodeAllocatableResource() *NodeAllocatableResourceApplyConfiguration { + return &NodeAllocatableResourceApplyConfiguration{} +} + +// WithMapping sets the Mapping 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 Mapping field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithMapping(value *NodeAllocatableMappingApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Mapping = value + return b +} + +// WithOverhead sets the Overhead 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 Overhead field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithOverhead(value *NodeAllocatableOverheadApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Overhead = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresourcemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresourcemapping.go deleted file mode 100644 index 5cdc2c751..000000000 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/nodeallocatableresourcemapping.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by applyconfiguration-gen. DO NOT EDIT. - -package v1beta1 - -import ( - resourcev1beta1 "k8s.io/api/resource/v1beta1" - resource "k8s.io/apimachinery/pkg/api/resource" -) - -// NodeAllocatableResourceMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableResourceMapping type for use -// with apply. -// -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMappingApplyConfiguration struct { - // CapacityKey references a capacity name defined as a key in the - // `spec.devices[*].capacity` map. When this field is set, the value associated with - // this key in the `status.allocation.devices.results[*].consumedCapacity` map - // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is - // multiplied with the base quantity. - // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", - // and this field is set to "dra.example.com/memory", then for a claim allocation - // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". - CapacityKey *resourcev1beta1.QualifiedName `json:"capacityKey,omitempty"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty"` -} - -// NodeAllocatableResourceMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableResourceMapping type for use with -// apply. -func NodeAllocatableResourceMapping() *NodeAllocatableResourceMappingApplyConfiguration { - return &NodeAllocatableResourceMappingApplyConfiguration{} -} - -// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithCapacityKey(value resourcev1beta1.QualifiedName) *NodeAllocatableResourceMappingApplyConfiguration { - b.CapacityKey = &value - return b -} - -// WithAllocationMultiplier sets the AllocationMultiplier 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 AllocationMultiplier field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithAllocationMultiplier(value resource.Quantity) *NodeAllocatableResourceMappingApplyConfiguration { - b.AllocationMultiplier = &value - return b -} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaim.go index aaeaf687d..a617fecd8 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaim.go @@ -39,7 +39,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec describes what is being requested and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaimtemplate.go index fe4200326..4c1eba7cd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceclaimtemplate.go @@ -35,7 +35,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimTemplateApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Describes the ResourceClaim that is to be generated. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourcepool.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourcepool.go index eff9e042c..3452dd18b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourcepool.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourcepool.go @@ -25,6 +25,8 @@ package v1beta1 type ResourcePoolApplyConfiguration struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslice.go index c9ec6a7b7..c6b5fc59c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslice.go @@ -55,7 +55,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceSliceApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Contains the information published by the driver. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslicespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslicespec.go index 230248643..d463e7238 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslicespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta1/resourceslicespec.go @@ -19,6 +19,7 @@ limitations under the License. package v1beta1 import ( + resourcev1beta1 "k8s.io/api/resource/v1beta1" v1 "k8s.io/client-go/applyconfigurations/core/v1" ) @@ -82,6 +83,28 @@ type ResourceSliceSpecApplyConfiguration struct { // // The maximum number of counter sets is 8. SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + PartitionTypeAttribute *resourcev1beta1.FullyQualifiedName `json:"partitionTypeAttribute,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + SkipNodeOperations []resourcev1beta1.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with @@ -163,3 +186,21 @@ func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*Coun } return b } + +// WithPartitionTypeAttribute sets the PartitionTypeAttribute 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 PartitionTypeAttribute field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPartitionTypeAttribute(value resourcev1beta1.FullyQualifiedName) *ResourceSliceSpecApplyConfiguration { + b.PartitionTypeAttribute = &value + return b +} + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *ResourceSliceSpecApplyConfiguration) WithSkipNodeOperations(values ...resourcev1beta1.SkipNodeOperation) *ResourceSliceSpecApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/capacityrequestpolicyrange.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/capacityrequestpolicyrange.go index bd9a73422..60e71b904 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/capacityrequestpolicyrange.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/capacityrequestpolicyrange.go @@ -27,6 +27,13 @@ import ( // // CapacityRequestPolicyRange defines a valid range for consumable capacity values. // +// If the DRAFractionalCapacityRange feature gate is +// enabled and at least one of Min, Max, or Step is a fractional quantity (i.e. +// its value is not an integer), milli-unit arithmetic is used instead, +// supporting values with up to 3 decimal places (e.g. 100m = 0.1). +// The largest supported value then is 1000 times smaller compared to using 64-bit integers. +// Otherwise, all comparisons use 64-bit integer arithmetic via resource.Quantity.Value(). +// // - If the requested amount is less than Min, it is rounded up to the Min value. // - If Step is set and the requested amount is between Min and Max but not aligned with Step, // it will be rounded up to the next value equal to Min + (n * Step). diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/celdeviceselector.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/celdeviceselector.go index a184590eb..73485f502 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/celdeviceselector.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/celdeviceselector.go @@ -33,7 +33,7 @@ type CELDeviceSelectorApplyConfiguration struct { // - driver (string): the name of the driver which defines this device. // - attributes (map[string]object): the device's attributes, grouped by prefix // (e.g. device.attributes["dra.example.com"] evaluates to an object with all - // of the attributes which were prefixed by "dra.example.com". + // of the attributes which were prefixed by "dra.example.com"). // - capacity (map[string]object): the device's capacities, grouped by prefix. // - allowMultipleAllocations (bool): the allowMultipleAllocations property of the device // (v1.34+ with the DRAConsumableCapacity feature enabled). @@ -66,6 +66,15 @@ type CELDeviceSelectorApplyConfiguration struct { // A robust expression should check for the existence of attributes // before referencing them. // + // Common errors: + // - "no such key": Use optional chaining (.? followed by orValue()) + // or guarding the check with has() for optional fields. + // See CEL Optional Types for details: + // https://pkg.go.dev/github.com/google/cel-go@v0.17.4/cel#OptionalTypes + // + // For more CEL expression syntax and examples, see: + // https://kubernetes.io/docs/reference/using-api/cel/ + // // For ease of use, the cel.bind() function is enabled, and can be used // to simplify expressions that access multiple attributes with the // same domain. For example: diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/device.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/device.go index b3985b0ca..71e2440be 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/device.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/device.go @@ -114,7 +114,7 @@ type DeviceApplyConfiguration struct { // If AllowMultipleAllocations is set to true, the device can be allocated more than once, // and all of its capacity is consumable, regardless of whether the requestPolicy is defined or not. AllowMultipleAllocations *bool `json:"allowMultipleAllocations,omitempty"` - // NodeAllocatableResourceMappings defines the mapping of node resources + // NodeAllocatableResources defines the mapping of node resources // that are managed by the DRA driver exposing this device. This includes resources currently // reported in v1.Node `status.allocatable` that are not extended resources // (see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#extended-resources). @@ -125,7 +125,7 @@ type DeviceApplyConfiguration struct { // dependencies of an accelerator device. // The keys of this map are the node-allocatable resource names (e.g., "cpu", "memory"). // Extended resource names are not permitted as keys. - NodeAllocatableResourceMappings map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration `json:"nodeAllocatableResourceMappings,omitempty"` + NodeAllocatableResources map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration `json:"nodeAllocatableResources,omitempty"` } // DeviceApplyConfiguration constructs a declarative configuration of the Device type for use with @@ -256,16 +256,16 @@ func (b *DeviceApplyConfiguration) WithAllowMultipleAllocations(value bool) *Dev return b } -// WithNodeAllocatableResourceMappings puts the entries into the NodeAllocatableResourceMappings field in the declarative configuration +// WithNodeAllocatableResources puts the entries into the NodeAllocatableResources field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResourceMappings field, -// overwriting an existing map entries in NodeAllocatableResourceMappings field with the same key. -func (b *DeviceApplyConfiguration) WithNodeAllocatableResourceMappings(entries map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration) *DeviceApplyConfiguration { - if b.NodeAllocatableResourceMappings == nil && len(entries) > 0 { - b.NodeAllocatableResourceMappings = make(map[corev1.ResourceName]NodeAllocatableResourceMappingApplyConfiguration, len(entries)) +// If called multiple times, the entries provided by each call will be put on the NodeAllocatableResources field, +// overwriting an existing map entries in NodeAllocatableResources field with the same key. +func (b *DeviceApplyConfiguration) WithNodeAllocatableResources(entries map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration) *DeviceApplyConfiguration { + if b.NodeAllocatableResources == nil && len(entries) > 0 { + b.NodeAllocatableResources = make(map[corev1.ResourceName]NodeAllocatableResourceApplyConfiguration, len(entries)) } for k, v := range entries { - b.NodeAllocatableResourceMappings[k] = v + b.NodeAllocatableResources[k] = v } return b } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go index cbfb0c1f2..fb0c7e6be 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceallocationconfiguration.go @@ -38,7 +38,7 @@ type DeviceAllocationConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceAllocationConfigurationApplyConfiguration constructs a declarative configuration of the DeviceAllocationConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go index 59a4f50f6..34876049f 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclaimconfiguration.go @@ -30,7 +30,7 @@ type DeviceClaimConfigurationApplyConfiguration struct { // and may include the subrequest using the format
[/]. If just // the main request is given, the configuration applies to all subrequests. Requests []string `json:"requests,omitempty"` - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClaimConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClaimConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclass.go index 439e03c6d..687af4393 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclass.go @@ -38,7 +38,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type DeviceClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec defines what can be allocated and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go index f668fcf86..6b3f04366 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassconfiguration.go @@ -23,7 +23,7 @@ package v1beta2 // // DeviceClassConfiguration is used in DeviceClass. type DeviceClassConfigurationApplyConfiguration struct { - DeviceConfigurationApplyConfiguration `json:",inline"` + DeviceConfigurationApplyConfiguration `json:""` } // DeviceClassConfigurationApplyConfiguration constructs a declarative configuration of the DeviceClassConfiguration type for use with diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassspec.go index 4ae2eaa29..fc510c6ff 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/deviceclassspec.go @@ -40,8 +40,6 @@ type DeviceClassSpecApplyConfiguration struct { // is picked to satisfy a pod's extended resource requests. // If two classes are created at the same time, then the name of the class // lexicographically sorted first is picked. - // - // This is a beta field. ExtendedResourceName *string `json:"extendedResourceName,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicecounterconsumption.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicecounterconsumption.go index f636ccdbd..e94c38fc7 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicecounterconsumption.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicecounterconsumption.go @@ -31,6 +31,26 @@ type DeviceCounterConsumptionApplyConfiguration struct { // // The maximum number of counters is 32. Counters map[string]CounterApplyConfiguration `json:"counters,omitempty"` + // CompatibilityGroups is a list of opaque group names for + // this counter set consumption. + // + // Devices that consume counters from the same counter set may only be + // allocated at the same time ("co-allocated") if they all share at least + // one common group: the intersection of the CompatibilityGroups of all + // co-allocated devices on that counter set must be non-empty. Devices + // that consume from different counter sets are never compared via this + // field. + // + // An unset field, an explicit nil, and an empty list are equivalent and + // mean "no groups": such a device is only co-allocatable with sibling + // devices on the same counter set that also have no groups, and is never + // co-allocatable with a device that declares one or more groups. + // + // Group names are opaque and meaningful only within the + // publishing driver's pool. + // + // The maximum number of groups is 2, and the names must be unique. + CompatibilityGroups []string `json:"compatibilityGroups,omitempty"` } // DeviceCounterConsumptionApplyConfiguration constructs a declarative configuration of the DeviceCounterConsumption type for use with @@ -60,3 +80,13 @@ func (b *DeviceCounterConsumptionApplyConfiguration) WithCounters(entries map[st } return b } + +// WithCompatibilityGroups adds the given value to the CompatibilityGroups field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompatibilityGroups field. +func (b *DeviceCounterConsumptionApplyConfiguration) WithCompatibilityGroups(values ...string) *DeviceCounterConsumptionApplyConfiguration { + for i := range values { + b.CompatibilityGroups = append(b.CompatibilityGroups, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicederivedattribute.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicederivedattribute.go new file mode 100644 index 000000000..6b57b3f1a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicederivedattribute.go @@ -0,0 +1,95 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" +) + +// DeviceDerivedAttributeApplyConfiguration represents a declarative configuration of the DeviceDerivedAttribute type for use +// with apply. +// +// DeviceDerivedAttribute defines a derived attribute computed via CEL. +type DeviceDerivedAttributeApplyConfiguration struct { + // Name is the identifier for this derived attribute, used in constraints. + // + // It must be a DNS subdomain followed by a slash ("/") followed by a C identifier + // (e.g. "example.com/numaNode" or "derived/numaNode"). + // + // If the chosen name matches an existing physical attribute from a driver, + // the derived attribute's expression will shadow the physical attribute, + // and its evaluated value will be used in constraints instead. When the goal + // is to define a derived attribute that is only used within the ResourceClaim + // and not meant to shadow an existing attribute, use a domain prefix that + // no DRA driver should be using (e.g. "derived/myAttribute"). + // + // It is not valid to define a derived attribute that isn't used in at least + // one constraint. + Name *resourcev1beta2.FullyQualifiedName `json:"name,omitempty"` + // Expression is a CEL expression evaluated against each candidate device. + // The expression must evaluate to a primitive scalar (string, integer, + // boolean, or semver) or a list of these scalars ([]string, []int64, + // []bool, []semver) to act as a virtual grouping key. Any other return type + // is an error and causes CEL evaluation for the device to fail. + // + // The expression's input is an object named "device", which carries the + // same properties as in a CELDeviceSelector. + // + // When pod scheduling encounters CEL runtime errors (such as looking + // up an attribute that isn't defined) for some devices, it will abort + // allocation and fail scheduling for the Pod. Surfacing evaluation + // errors immediately prevents silent topology matching failures that are + // extremely hard to detect. A robust expression should, for example, check + // for the existence of attributes before referencing them to avoid + // runtime evaluation errors. + // + // The expression gets evaluated after a device has passed the other + // selector expressions for the request in which this expression is used. + // This allows writing expressions that are tailored towards the specific + // devices being requested (for example, by assuming the device is from a + // certain vendor and skipping those checks). + // + // The length of the expression must be smaller or equal to 10 Ki. The + // cost of evaluating it is also limited based on the estimated number + // of logical steps; the combined cost of all derived attributes in a + // claim is capped by a shared CEL cost budget. + Expression *string `json:"expression,omitempty"` +} + +// DeviceDerivedAttributeApplyConfiguration constructs a declarative configuration of the DeviceDerivedAttribute type for use with +// apply. +func DeviceDerivedAttribute() *DeviceDerivedAttributeApplyConfiguration { + return &DeviceDerivedAttributeApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithName(value resourcev1beta2.FullyQualifiedName) *DeviceDerivedAttributeApplyConfiguration { + b.Name = &value + return b +} + +// WithExpression sets the Expression 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 Expression field is set to the value of the last call. +func (b *DeviceDerivedAttributeApplyConfiguration) WithExpression(value string) *DeviceDerivedAttributeApplyConfiguration { + b.Expression = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go index a274e5706..e80cd933e 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicerequestallocationresult.go @@ -95,6 +95,12 @@ type DeviceRequestAllocationResultApplyConfiguration struct { // This field is populated only for devices that allow multiple allocations. // All capacity entries are included, even if the consumed amount is zero. ConsumedCapacity map[resourcev1beta2.QualifiedName]resource.Quantity `json:"consumedCapacity,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for this allocated device when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. It is a copy of + // the ResourceSlice.spec.skipNodeOperations value at the time when the device was allocated. + SkipNodeOperations []resourcev1beta2.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // DeviceRequestAllocationResultApplyConfiguration constructs a declarative configuration of the DeviceRequestAllocationResult type for use with @@ -197,3 +203,13 @@ func (b *DeviceRequestAllocationResultApplyConfiguration) WithConsumedCapacity(e } return b } + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *DeviceRequestAllocationResultApplyConfiguration) WithSkipNodeOperations(values ...resourcev1beta2.SkipNodeOperation) *DeviceRequestAllocationResultApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicesubrequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicesubrequest.go index d9f4a5cb5..f0c882185 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicesubrequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicesubrequest.go @@ -109,6 +109,27 @@ type DeviceSubRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // DeviceSubRequestApplyConfiguration constructs a declarative configuration of the DeviceSubRequest type for use with @@ -182,3 +203,16 @@ func (b *DeviceSubRequestApplyConfiguration) WithCapacity(value *CapacityRequire b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *DeviceSubRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *DeviceSubRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicetaintrule.go index 18b2aca18..5e7a5a0cb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicetaintrule.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/devicetaintrule.go @@ -34,7 +34,7 @@ import ( // This has the same effect as if the taint was specified directly // in the ResourceSlice by the DRA driver. type DeviceTaintRuleApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec specifies the selector and one taint. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/exactdevicerequest.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/exactdevicerequest.go index bda115270..b23786194 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/exactdevicerequest.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/exactdevicerequest.go @@ -107,6 +107,27 @@ type ExactDeviceRequestApplyConfiguration struct { // the request fails if there are devices that otherwise match the request, // and have this capacity, with a value >= the requested amount, but which cannot be allocated to this request. Capacity *CapacityRequirementsApplyConfiguration `json:"capacity,omitempty"` + // DerivedAttributes defines a set of virtual attributes computed via CEL expressions + // for each candidate device. These virtual attributes can be referenced in + // `.devices.constraints` to align and match different devices (e.g., co-allocating + // a GPU and a NIC on the same NUMA node) even if their drivers publish different + // attributes. Derived attributes are not available via `device.attributes` + // in the CEL environment when evaluating selector expressions. + // + // Derived attributes allow you to extract, transform, or normalize topology + // information (such as extracting a NUMA index from a complex topology string or + // renaming a vendor-specific attribute) into a common virtual attribute name at + // scheduling time. The scheduler then evaluates these virtual attributes exactly + // like static attributes when matching constraints. + // + // Every derived attribute defined in this list must be referenced by at least one + // MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list. + // + // The maximum number of derived attributes is 32. + // + // This is an alpha field and requires enabling the DRADerivedAttributes + // feature gate. + DerivedAttributes []DeviceDerivedAttributeApplyConfiguration `json:"derivedAttributes,omitempty"` } // ExactDeviceRequestApplyConfiguration constructs a declarative configuration of the ExactDeviceRequest type for use with @@ -180,3 +201,16 @@ func (b *ExactDeviceRequestApplyConfiguration) WithCapacity(value *CapacityRequi b.Capacity = value return b } + +// WithDerivedAttributes adds the given value to the DerivedAttributes field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the DerivedAttributes field. +func (b *ExactDeviceRequestApplyConfiguration) WithDerivedAttributes(values ...*DeviceDerivedAttributeApplyConfiguration) *ExactDeviceRequestApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithDerivedAttributes") + } + b.DerivedAttributes = append(b.DerivedAttributes, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatablemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatablemapping.go new file mode 100644 index 000000000..50b406973 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatablemapping.go @@ -0,0 +1,90 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableMapping type for use +// with apply. +// +// NodeAllocatableMapping defines how a DRA allocation directly translates into a node allocatable resource quantity. +// The mapping can be derived from either the count of allocated devices (via deviceMultiplier) or the specific capacity consumed (via capacityKey and capacityMultiplier). These options are mutually exclusive. +// Kubelet adds this mapped resource quantity from claim to both requests and limits at the pod-level cgroup, and to limits at the container-level cgroup for each container referencing the claim. +type NodeAllocatableMappingApplyConfiguration struct { + // CapacityKey references a capacity name defined as a key in the + // `spec.devices[*].capacity` map. When this field is set, the value associated with + // this key in the `status.allocation.devices.results[*].consumedCapacity` map + // (for a specific claim allocation) determines the base quantity for + // the node allocatable resource. `capacityMultiplier` must also be set and is + // multiplied with the base quantity. + // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", + // and this field is set to "dra.example.com/memory", then for a claim allocation + // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the + // node allocatable resource mapping will be "4Gi". + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + CapacityKey *resourcev1beta2.QualifiedName `json:"capacityKey,omitempty"` + // CapacityMultiplier is used as a multiplier for the allocated capacity consumed. + // It is only valid if `capacityKey` is set. + // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `capacityMultiplier`. + // For example, if a Device's capacity "dra.example.com/cores" is consumed, + // and each "core" provides 2 "cpu"s, the mapping would be: + // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", capacityMultiplier: "2"}. + // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. + CapacityMultiplier *resource.Quantity `json:"capacityMultiplier,omitempty"` + // DeviceMultiplier is used as a multiplier for the allocated device count in the claim. + // The final node allocatable resource amount is `deviceCount` * `deviceMultiplier`. + // For example, a DRA driver representing each cache complex (CCX) as a device would have + // {ResourceName: "cpu", deviceMultiplier: "8"} in its `nodeAllocatableResources`. + // If 2 devices (CCX) are allocated to the claim, 2 * 8 = 16 CPUs would be considered as allocated. + // It is only valid when `capacityKey` and `capacityMultiplier` are not set. + DeviceMultiplier *resource.Quantity `json:"deviceMultiplier,omitempty"` +} + +// NodeAllocatableMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableMapping type for use with +// apply. +func NodeAllocatableMapping() *NodeAllocatableMappingApplyConfiguration { + return &NodeAllocatableMappingApplyConfiguration{} +} + +// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityKey(value resourcev1beta2.QualifiedName) *NodeAllocatableMappingApplyConfiguration { + b.CapacityKey = &value + return b +} + +// WithCapacityMultiplier sets the CapacityMultiplier 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 CapacityMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithCapacityMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.CapacityMultiplier = &value + return b +} + +// WithDeviceMultiplier sets the DeviceMultiplier 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 DeviceMultiplier field is set to the value of the last call. +func (b *NodeAllocatableMappingApplyConfiguration) WithDeviceMultiplier(value resource.Quantity) *NodeAllocatableMappingApplyConfiguration { + b.DeviceMultiplier = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableoverhead.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableoverhead.go new file mode 100644 index 000000000..49205e899 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableoverhead.go @@ -0,0 +1,67 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +import ( + resource "k8s.io/apimachinery/pkg/api/resource" +) + +// NodeAllocatableOverheadApplyConfiguration represents a declarative configuration of the NodeAllocatableOverhead type for use +// with apply. +// +// NodeAllocatableOverhead defines auxiliary resource overheads incurred when allocating a device. +// Overheads can be specified as a fixed cost per pod referencing the claim, a variable cost per container reference, or both. +// Kubelet accounts for this overhead by adding it to both the pod-level and container-level cgroups of referencing containers. +type NodeAllocatableOverheadApplyConfiguration struct { + // PerPod is overhead applied once per pod referencing the claim on this node. + // This is a flat overhead incurred for every pod referencing the claim. + PerPod *resource.Quantity `json:"perPod,omitempty"` + // PerContainer is applied per container reference to the claim. + // This models overhead scaling linearly with the number of containers actively using the device. + // When both PerPod and PerContainer are specified, the total overhead allocated for each pod referencing + // the claim is computed as: + // Quantity = PerPod + (PerContainer * NumReferences) + // Kubelet accounts for this overhead in cgroups: + // - Pod-level cgroup (requests and limits): Kubelet adds PerPod + (PerContainer * NumReferences). + // - Container-level cgroup (limits only): Kubelet adds PerPod + PerContainer for each referencing container. + // This allows any single container to access the pod-level overhead, while the parent cgroup caps the total usage to account for PerPod exactly once. + PerContainer *resource.Quantity `json:"perContainer,omitempty"` +} + +// NodeAllocatableOverheadApplyConfiguration constructs a declarative configuration of the NodeAllocatableOverhead type for use with +// apply. +func NodeAllocatableOverhead() *NodeAllocatableOverheadApplyConfiguration { + return &NodeAllocatableOverheadApplyConfiguration{} +} + +// WithPerPod sets the PerPod 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 PerPod field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerPod(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerPod = &value + return b +} + +// WithPerContainer sets the PerContainer 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 PerContainer field is set to the value of the last call. +func (b *NodeAllocatableOverheadApplyConfiguration) WithPerContainer(value resource.Quantity) *NodeAllocatableOverheadApplyConfiguration { + b.PerContainer = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresource.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresource.go new file mode 100644 index 000000000..ce116f3d4 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresource.go @@ -0,0 +1,65 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta2 + +// NodeAllocatableResourceApplyConfiguration represents a declarative configuration of the NodeAllocatableResource type for use +// with apply. +// +// NodeAllocatableResource defines the translation between the DRA device/capacity +// units requested to the corresponding quantity of the node allocatable resource. +// At least one of Mapping or Overhead must be specified. Not specifying either is an invalid configuration. +type NodeAllocatableResourceApplyConfiguration struct { + // Mapping is used when the device directly models a node allocatable resource like standard CPU or memory + // (e.g., with a CPU DRA driver). The calculated quantity is accounted for exactly once per claim instance + // on the node. To prevent node cgroup isolation friction, the scheduler explicitly + // blocks sharing mapped device claims across multiple pods. + Mapping *NodeAllocatableMappingApplyConfiguration `json:"mapping,omitempty"` + // Overhead contains fields for modeling auxiliary overhead incurred on node allocatable resources + // when allocating devices that are not themselves modeling a node allocatable resource (e.g., host memory overhead for GPUs). + // Sharing overhead-mapped claims across multiple pods is allowed. The node allocatable overhead is accounted + // for individually for each pod referencing the claim. + // Overhead is always subtracted from the node's allocatable capacity for the resource, even when mapping + // is specified for the same resource. + // Eg: If a device models memory capacity per socket as a consumable capacity pool via Mapping (with CapacityKey), + // any overhead specified for the same resource will be subtracted from the node's general allocatable capacity + // and not from the per-socket capacity pool in Mapping. + Overhead *NodeAllocatableOverheadApplyConfiguration `json:"overhead,omitempty"` +} + +// NodeAllocatableResourceApplyConfiguration constructs a declarative configuration of the NodeAllocatableResource type for use with +// apply. +func NodeAllocatableResource() *NodeAllocatableResourceApplyConfiguration { + return &NodeAllocatableResourceApplyConfiguration{} +} + +// WithMapping sets the Mapping 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 Mapping field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithMapping(value *NodeAllocatableMappingApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Mapping = value + return b +} + +// WithOverhead sets the Overhead 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 Overhead field is set to the value of the last call. +func (b *NodeAllocatableResourceApplyConfiguration) WithOverhead(value *NodeAllocatableOverheadApplyConfiguration) *NodeAllocatableResourceApplyConfiguration { + b.Overhead = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresourcemapping.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresourcemapping.go deleted file mode 100644 index b1490b5e7..000000000 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/nodeallocatableresourcemapping.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by applyconfiguration-gen. DO NOT EDIT. - -package v1beta2 - -import ( - resourcev1beta2 "k8s.io/api/resource/v1beta2" - resource "k8s.io/apimachinery/pkg/api/resource" -) - -// NodeAllocatableResourceMappingApplyConfiguration represents a declarative configuration of the NodeAllocatableResourceMapping type for use -// with apply. -// -// NodeAllocatableResourceMapping defines the translation between the DRA device/capacity -// units requested to the corresponding quantity of the node allocatable resource. -type NodeAllocatableResourceMappingApplyConfiguration struct { - // CapacityKey references a capacity name defined as a key in the - // `spec.devices[*].capacity` map. When this field is set, the value associated with - // this key in the `status.allocation.devices.results[*].consumedCapacity` map - // (for a specific claim allocation) determines the base quantity for - // the node allocatable resource. If `allocationMultiplier` is also set, it is - // multiplied with the base quantity. - // For example, if `spec.devices[*].capacity` has an entry "dra.example.com/memory": "128Gi", - // and this field is set to "dra.example.com/memory", then for a claim allocation - // that consumes { "dra.example.com/memory": "4Gi" } the base quantity for the - // node allocatable resource mapping will be "4Gi", and `allocationMultiplier` should - // be omitted or set to "1". - CapacityKey *resourcev1beta2.QualifiedName `json:"capacityKey,omitempty"` - // AllocationMultiplier is used as a multiplier for the allocated device count or the allocated capacity in the claim. - // It defaults to 1 if not specified. How the field is used also depends on whether `capacityKey` is set. - // 1. If `capacityKey` is NOT set: `allocationMultiplier` multiplies the device count allocated to the claim. - // a. A DRA driver representing each CPU core as a device would have - // {ResourceName: "cpu", allocationMultiplier: "2"} in its - // `nodeAllocatableResourceMappings`. If 4 devices are allocated to the claim, - // 4 * 2 CPUs would be considered as allocated and subtracted from the node's capacity. - // b. A GPU device that needs additional node memory per GPU allocation would - // have {ResourceName: "memory", allocationMultiplier: "2Gi"}. Each allocated - // GPU device instance of this type will account for 2Gi of memory. - // - // 2. If `capacityKey` IS set: `allocationMultiplier` is multiplied by the amount of that capacity consumed. - // The final node allocatable resource amount is `consumedCapacity[capacityKey]` * `allocationMultiplier`. - // For example, if a Device's capacity "dra.example.com/cores" is consumed, - // and each "core" provides 2 "cpu"s, the mapping would be: - // {ResourceName: "cpu", capacityKey: "dra.example.com/cores", allocationMultiplier: "2"}. - // If a claim consumes 8 "dra.example.com/cores", the CPU footprint is 8 * 2 = 16. - AllocationMultiplier *resource.Quantity `json:"allocationMultiplier,omitempty"` -} - -// NodeAllocatableResourceMappingApplyConfiguration constructs a declarative configuration of the NodeAllocatableResourceMapping type for use with -// apply. -func NodeAllocatableResourceMapping() *NodeAllocatableResourceMappingApplyConfiguration { - return &NodeAllocatableResourceMappingApplyConfiguration{} -} - -// WithCapacityKey sets the CapacityKey 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 CapacityKey field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithCapacityKey(value resourcev1beta2.QualifiedName) *NodeAllocatableResourceMappingApplyConfiguration { - b.CapacityKey = &value - return b -} - -// WithAllocationMultiplier sets the AllocationMultiplier 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 AllocationMultiplier field is set to the value of the last call. -func (b *NodeAllocatableResourceMappingApplyConfiguration) WithAllocationMultiplier(value resource.Quantity) *NodeAllocatableResourceMappingApplyConfiguration { - b.AllocationMultiplier = &value - return b -} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaim.go index e35d087cd..7b8e86139 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaim.go @@ -39,7 +39,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Spec describes what is being requested and how to configure it. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go index 999521cee..35e5adbdf 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceclaimtemplate.go @@ -35,7 +35,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceClaimTemplateApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Describes the ResourceClaim that is to be generated. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourcepool.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourcepool.go index f5b0c9b61..4d631c397 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourcepool.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourcepool.go @@ -25,6 +25,8 @@ package v1beta2 type ResourcePoolApplyConfiguration struct { // Name is used to identify the pool. For node-local devices, this // is often the node name, but this is not required. + // A field selector can be used to list only ResourceSlice objects + // belonging to a certain pool. // // It must not be longer than 253 characters and must consist of one or more DNS sub-domains // separated by slashes. This field is immutable. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslice.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslice.go index dbbe7b2ea..89eae2d21 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslice.go @@ -55,7 +55,7 @@ import ( // This is an alpha type and requires enabling the DynamicResourceAllocation // feature gate. type ResourceSliceApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // Contains the information published by the driver. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslicespec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslicespec.go index 2efc7d075..cdd52c111 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslicespec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/resource/v1beta2/resourceslicespec.go @@ -19,6 +19,7 @@ limitations under the License. package v1beta2 import ( + resourcev1beta2 "k8s.io/api/resource/v1beta2" v1 "k8s.io/client-go/applyconfigurations/core/v1" ) @@ -82,6 +83,28 @@ type ResourceSliceSpecApplyConfiguration struct { // // The maximum number of counter sets is 8. SharedCounters []CounterSetApplyConfiguration `json:"sharedCounters,omitempty"` + // PartitionTypeAttribute names a string device attribute (by fully + // qualified name, e.g. "gpu.example.com/profile") whose value labels + // each device with its partition type, such as "Full" or "Half" for a + // MIG-style GPU. + // + // When set, every partitionable device in the slice must carry the attribute + // and devices sharing a value must share the same ConsumesCounters cost. + PartitionTypeAttribute *resourcev1beta2.FullyQualifiedName `json:"partitionTypeAttribute,omitempty"` + // SkipNodeOperations lists node-local resource operations (gRPC calls) + // that will be skipped for the devices in this slice when determining whether + // operations are necessary on the node. If all allocated devices for a driver in + // a claim skip an operation, that gRPC call will be skipped. Valid values are: + // + // - "NodePrepareResources": NodePrepareResources gRPC calls are skipped. This + // value cannot be specified unless "NodeUnprepareResources" is also listed + // (or "*" is specified). + // - "NodeUnprepareResources": NodeUnprepareResources gRPC calls are skipped. + // - "*": All node-local resource operations are skipped. + // + // Other values may be added in the future. The kubelet must ignore unknown + // values. + SkipNodeOperations []resourcev1beta2.SkipNodeOperation `json:"skipNodeOperations,omitempty"` } // ResourceSliceSpecApplyConfiguration constructs a declarative configuration of the ResourceSliceSpec type for use with @@ -163,3 +186,21 @@ func (b *ResourceSliceSpecApplyConfiguration) WithSharedCounters(values ...*Coun } return b } + +// WithPartitionTypeAttribute sets the PartitionTypeAttribute 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 PartitionTypeAttribute field is set to the value of the last call. +func (b *ResourceSliceSpecApplyConfiguration) WithPartitionTypeAttribute(value resourcev1beta2.FullyQualifiedName) *ResourceSliceSpecApplyConfiguration { + b.PartitionTypeAttribute = &value + return b +} + +// WithSkipNodeOperations adds the given value to the SkipNodeOperations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the SkipNodeOperations field. +func (b *ResourceSliceSpecApplyConfiguration) WithSkipNodeOperations(values ...resourcev1beta2.SkipNodeOperation) *ResourceSliceSpecApplyConfiguration { + for i := range values { + b.SkipNodeOperations = append(b.SkipNodeOperations, values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go index 4056dcdd2..b8612d6cb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go @@ -34,8 +34,8 @@ import ( // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. type PriorityClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // value represents the integer value of this priority class. This is the actual priority that pods diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplatereference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplatereference.go deleted file mode 100644 index f8b1f61ff..000000000 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplatereference.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by applyconfiguration-gen. DO NOT EDIT. - -package v1alpha2 - -// PodGroupTemplateReferenceApplyConfiguration represents a declarative configuration of the PodGroupTemplateReference type for use -// with apply. -// -// PodGroupTemplateReference references a PodGroup template defined in some object (e.g. Workload). -// Exactly one reference must be set. -type PodGroupTemplateReferenceApplyConfiguration struct { - // Workload references the PodGroupTemplate within the Workload object that was used to create - // the PodGroup. - Workload *WorkloadPodGroupTemplateReferenceApplyConfiguration `json:"workload,omitempty"` -} - -// PodGroupTemplateReferenceApplyConfiguration constructs a declarative configuration of the PodGroupTemplateReference type for use with -// apply. -func PodGroupTemplateReference() *PodGroupTemplateReferenceApplyConfiguration { - return &PodGroupTemplateReferenceApplyConfiguration{} -} - -// WithWorkload sets the Workload 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 Workload field is set to the value of the last call. -func (b *PodGroupTemplateReferenceApplyConfiguration) WithWorkload(value *WorkloadPodGroupTemplateReferenceApplyConfiguration) *PodGroupTemplateReferenceApplyConfiguration { - b.Workload = value - return b -} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadpodgrouptemplatereference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadpodgrouptemplatereference.go deleted file mode 100644 index ff3ab06c8..000000000 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadpodgrouptemplatereference.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by applyconfiguration-gen. DO NOT EDIT. - -package v1alpha2 - -// WorkloadPodGroupTemplateReferenceApplyConfiguration represents a declarative configuration of the WorkloadPodGroupTemplateReference type for use -// with apply. -// -// WorkloadPodGroupTemplateReference references the PodGroupTemplate within the Workload object. -type WorkloadPodGroupTemplateReferenceApplyConfiguration struct { - // WorkloadName defines the name of the Workload object. - WorkloadName *string `json:"workloadName,omitempty"` - // PodGroupTemplateName defines the PodGroupTemplate name within the Workload object. - PodGroupTemplateName *string `json:"podGroupTemplateName,omitempty"` -} - -// WorkloadPodGroupTemplateReferenceApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupTemplateReference type for use with -// apply. -func WorkloadPodGroupTemplateReference() *WorkloadPodGroupTemplateReferenceApplyConfiguration { - return &WorkloadPodGroupTemplateReferenceApplyConfiguration{} -} - -// WithWorkloadName sets the WorkloadName 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 WorkloadName field is set to the value of the last call. -func (b *WorkloadPodGroupTemplateReferenceApplyConfiguration) WithWorkloadName(value string) *WorkloadPodGroupTemplateReferenceApplyConfiguration { - b.WorkloadName = &value - return b -} - -// WithPodGroupTemplateName sets the PodGroupTemplateName 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 PodGroupTemplateName field is set to the value of the last call. -func (b *WorkloadPodGroupTemplateReferenceApplyConfiguration) WithPodGroupTemplateName(value string) *WorkloadPodGroupTemplateReferenceApplyConfiguration { - b.PodGroupTemplateName = &value - return b -} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositedisruptionmode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositedisruptionmode.go new file mode 100644 index 000000000..70ff0162a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositedisruptionmode.go @@ -0,0 +1,57 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// CompositeDisruptionModeApplyConfiguration represents a declarative configuration of the CompositeDisruptionMode type for use +// with apply. +// +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +type CompositeDisruptionModeApplyConfiguration struct { + // single specifies that children groups can be disrupted independently from each other. + Single *schedulingv1alpha3.SingleCompositeDisruptionMode `json:"single,omitempty"` + // all specifies that all children groups can only be disrupted together. + All *schedulingv1alpha3.AllCompositeDisruptionMode `json:"all,omitempty"` +} + +// CompositeDisruptionModeApplyConfiguration constructs a declarative configuration of the CompositeDisruptionMode type for use with +// apply. +func CompositeDisruptionMode() *CompositeDisruptionModeApplyConfiguration { + return &CompositeDisruptionModeApplyConfiguration{} +} + +// WithSingle sets the Single 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 Single field is set to the value of the last call. +func (b *CompositeDisruptionModeApplyConfiguration) WithSingle(value schedulingv1alpha3.SingleCompositeDisruptionMode) *CompositeDisruptionModeApplyConfiguration { + b.Single = &value + return b +} + +// WithAll sets the All 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 All field is set to the value of the last call. +func (b *CompositeDisruptionModeApplyConfiguration) WithAll(value schedulingv1alpha3.AllCompositeDisruptionMode) *CompositeDisruptionModeApplyConfiguration { + b.All = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositegangschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositegangschedulingpolicy.go new file mode 100644 index 000000000..c462b55a9 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositegangschedulingpolicy.go @@ -0,0 +1,45 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// CompositeGangSchedulingPolicyApplyConfiguration represents a declarative configuration of the CompositeGangSchedulingPolicy type for use +// with apply. +// +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +type CompositeGangSchedulingPolicyApplyConfiguration struct { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + MinGroupCount *int32 `json:"minGroupCount,omitempty"` +} + +// CompositeGangSchedulingPolicyApplyConfiguration constructs a declarative configuration of the CompositeGangSchedulingPolicy type for use with +// apply. +func CompositeGangSchedulingPolicy() *CompositeGangSchedulingPolicyApplyConfiguration { + return &CompositeGangSchedulingPolicyApplyConfiguration{} +} + +// WithMinGroupCount sets the MinGroupCount 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 MinGroupCount field is set to the value of the last call. +func (b *CompositeGangSchedulingPolicyApplyConfiguration) WithMinGroupCount(value int32) *CompositeGangSchedulingPolicyApplyConfiguration { + b.MinGroupCount = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroup.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroup.go new file mode 100644 index 000000000..e408c0a79 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroup.go @@ -0,0 +1,296 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// CompositePodGroupApplyConfiguration represents a declarative configuration of the CompositePodGroup type for use +// with apply. +// +// CompositePodGroup represents a runtime instance of pod groups grouped together. +// CompositePodGroups are created by workload controllers (LWS, JobSet, etc...) from +// Workload.compositePodGroupTemplates. +// CompositePodGroup API enablement is toggled by the CompositePodGroup feature gate. +type CompositePodGroupApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec defines the desired state of the CompositePodGroup. + Spec *CompositePodGroupSpecApplyConfiguration `json:"spec,omitempty"` + // status represents the current observed state of the CompositePodGroup. + Status *CompositePodGroupStatusApplyConfiguration `json:"status,omitempty"` +} + +// CompositePodGroup constructs a declarative configuration of the CompositePodGroup type for use with +// apply. +func CompositePodGroup(name, namespace string) *CompositePodGroupApplyConfiguration { + b := &CompositePodGroupApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("CompositePodGroup") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") + return b +} + +// ExtractCompositePodGroupFrom extracts the applied configuration owned by fieldManager from +// compositePodGroup for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// compositePodGroup must be a unmodified CompositePodGroup API object that was retrieved from the Kubernetes API. +// ExtractCompositePodGroupFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCompositePodGroupFrom(compositePodGroup *schedulingv1alpha3.CompositePodGroup, fieldManager string, subresource string) (*CompositePodGroupApplyConfiguration, error) { + b := &CompositePodGroupApplyConfiguration{} + err := managedfields.ExtractInto(compositePodGroup, internal.Parser().Type("io.k8s.api.scheduling.v1alpha3.CompositePodGroup"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(compositePodGroup.Name) + b.WithNamespace(compositePodGroup.Namespace) + + b.WithKind("CompositePodGroup") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") + return b, nil +} + +// ExtractCompositePodGroup extracts the applied configuration owned by fieldManager from +// compositePodGroup. If no managedFields are found in compositePodGroup for fieldManager, a +// CompositePodGroupApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// compositePodGroup must be a unmodified CompositePodGroup API object that was retrieved from the Kubernetes API. +// ExtractCompositePodGroup provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractCompositePodGroup(compositePodGroup *schedulingv1alpha3.CompositePodGroup, fieldManager string) (*CompositePodGroupApplyConfiguration, error) { + return ExtractCompositePodGroupFrom(compositePodGroup, fieldManager, "") +} + +// ExtractCompositePodGroupStatus extracts the applied configuration owned by fieldManager from +// compositePodGroup for the status subresource. +func ExtractCompositePodGroupStatus(compositePodGroup *schedulingv1alpha3.CompositePodGroup, fieldManager string) (*CompositePodGroupApplyConfiguration, error) { + return ExtractCompositePodGroupFrom(compositePodGroup, fieldManager, "status") +} + +func (b CompositePodGroupApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithKind(value string) *CompositePodGroupApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithAPIVersion(value string) *CompositePodGroupApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithName(value string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithGenerateName(value string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithNamespace(value string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithUID(value types.UID) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithResourceVersion(value string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithGeneration(value int64) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *CompositePodGroupApplyConfiguration) WithLabels(entries map[string]string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *CompositePodGroupApplyConfiguration) WithAnnotations(entries map[string]string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *CompositePodGroupApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *CompositePodGroupApplyConfiguration) WithFinalizers(values ...string) *CompositePodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *CompositePodGroupApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithSpec(value *CompositePodGroupSpecApplyConfiguration) *CompositePodGroupApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *CompositePodGroupApplyConfiguration) WithStatus(value *CompositePodGroupStatusApplyConfiguration) *CompositePodGroupApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *CompositePodGroupApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *CompositePodGroupApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *CompositePodGroupApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *CompositePodGroupApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingconstraints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingconstraints.go new file mode 100644 index 000000000..4c6fe983c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingconstraints.go @@ -0,0 +1,48 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// CompositePodGroupSchedulingConstraintsApplyConfiguration represents a declarative configuration of the CompositePodGroupSchedulingConstraints type for use +// with apply. +// +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +type CompositePodGroupSchedulingConstraintsApplyConfiguration struct { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + Topology []TopologyConstraintApplyConfiguration `json:"topology,omitempty"` +} + +// CompositePodGroupSchedulingConstraintsApplyConfiguration constructs a declarative configuration of the CompositePodGroupSchedulingConstraints type for use with +// apply. +func CompositePodGroupSchedulingConstraints() *CompositePodGroupSchedulingConstraintsApplyConfiguration { + return &CompositePodGroupSchedulingConstraintsApplyConfiguration{} +} + +// WithTopology adds the given value to the Topology field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Topology field. +func (b *CompositePodGroupSchedulingConstraintsApplyConfiguration) WithTopology(values ...*TopologyConstraintApplyConfiguration) *CompositePodGroupSchedulingConstraintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTopology") + } + b.Topology = append(b.Topology, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingpolicy.go new file mode 100644 index 000000000..c98be7fbe --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupschedulingpolicy.go @@ -0,0 +1,59 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// CompositePodGroupSchedulingPolicyApplyConfiguration represents a declarative configuration of the CompositePodGroupSchedulingPolicy type for use +// with apply. +// +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +type CompositePodGroupSchedulingPolicyApplyConfiguration struct { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + Basic *schedulingv1alpha3.CompositeBasicSchedulingPolicy `json:"basic,omitempty"` + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + Gang *CompositeGangSchedulingPolicyApplyConfiguration `json:"gang,omitempty"` +} + +// CompositePodGroupSchedulingPolicyApplyConfiguration constructs a declarative configuration of the CompositePodGroupSchedulingPolicy type for use with +// apply. +func CompositePodGroupSchedulingPolicy() *CompositePodGroupSchedulingPolicyApplyConfiguration { + return &CompositePodGroupSchedulingPolicyApplyConfiguration{} +} + +// WithBasic sets the Basic 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 Basic field is set to the value of the last call. +func (b *CompositePodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1alpha3.CompositeBasicSchedulingPolicy) *CompositePodGroupSchedulingPolicyApplyConfiguration { + b.Basic = &value + return b +} + +// WithGang sets the Gang 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 Gang field is set to the value of the last call. +func (b *CompositePodGroupSchedulingPolicyApplyConfiguration) WithGang(value *CompositeGangSchedulingPolicyApplyConfiguration) *CompositePodGroupSchedulingPolicyApplyConfiguration { + b.Gang = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupspec.go new file mode 100644 index 000000000..16bc538a5 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupspec.go @@ -0,0 +1,144 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// CompositePodGroupSpecApplyConfiguration represents a declarative configuration of the CompositePodGroupSpec type for use +// with apply. +// +// CompositePodGroupSpec defines the desired state of CompositePodGroup. +type CompositePodGroupSpecApplyConfiguration struct { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this composite pod group. It must be a DNS name. + // If it's nil, then this composite pod group is a root of a workload's hierarchy. + // This field is immutable. + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty"` + // workloadRef references an optional CompositePodGroup template within the + // Workload object that was used to create the CompositePodGroup. + // This field is required. + // This field is immutable. + WorkloadRef *WorkloadReferenceApplyConfiguration `json:"workloadRef,omitempty"` + // schedulingPolicy defines the scheduling policy for this instance of the CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + SchedulingPolicy *CompositePodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // This field is immutable. + SchedulingConstraints *CompositePodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + DisruptionMode *CompositeDisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName defines the priority that should be considered when scheduling this CompositePodGroup. + // Controllers are expected to fill this field by copying it from a CompositePodGroupTemplate. + // If left unspecified, it is validated and resolved similarly to the PriorityClassName field in Pods + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the composite pod group's priority will be zero). + // This field is immutable. + PriorityClassName *string `json:"priorityClassName,omitempty"` + // priority is the value of priority of this composite pod group. Various system components + // use this field to find the priority of the composite pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1alpha3.PreemptionPolicy `json:"preemptionPolicy,omitempty"` +} + +// CompositePodGroupSpecApplyConfiguration constructs a declarative configuration of the CompositePodGroupSpec type for use with +// apply. +func CompositePodGroupSpec() *CompositePodGroupSpecApplyConfiguration { + return &CompositePodGroupSpecApplyConfiguration{} +} + +// WithParentCompositePodGroupName sets the ParentCompositePodGroupName 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 ParentCompositePodGroupName field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithParentCompositePodGroupName(value string) *CompositePodGroupSpecApplyConfiguration { + b.ParentCompositePodGroupName = &value + return b +} + +// WithWorkloadRef sets the WorkloadRef 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 WorkloadRef field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithWorkloadRef(value *WorkloadReferenceApplyConfiguration) *CompositePodGroupSpecApplyConfiguration { + b.WorkloadRef = value + return b +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithSchedulingPolicy(value *CompositePodGroupSchedulingPolicyApplyConfiguration) *CompositePodGroupSpecApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithSchedulingConstraints(value *CompositePodGroupSchedulingConstraintsApplyConfiguration) *CompositePodGroupSpecApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithDisruptionMode(value *CompositeDisruptionModeApplyConfiguration) *CompositePodGroupSpecApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithPriorityClassName sets the PriorityClassName 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 PriorityClassName field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithPriorityClassName(value string) *CompositePodGroupSpecApplyConfiguration { + b.PriorityClassName = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithPriority(value int32) *CompositePodGroupSpecApplyConfiguration { + b.Priority = &value + return b +} + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *CompositePodGroupSpecApplyConfiguration) WithPreemptionPolicy(value schedulingv1alpha3.PreemptionPolicy) *CompositePodGroupSpecApplyConfiguration { + b.PreemptionPolicy = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupstatus.go new file mode 100644 index 000000000..7c9691652 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgroupstatus.go @@ -0,0 +1,72 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// CompositePodGroupStatusApplyConfiguration represents a declarative configuration of the CompositePodGroupStatus type for use +// with apply. +// +// CompositePodGroupStatus represents information about the status of a composite pod group. +type CompositePodGroupStatusApplyConfiguration struct { + // conditions represent the latest observations of the CompositePodGroup's state. + // + // Known condition types: + // - "CompositePodGroupInitiallyScheduled": Indicates whether the overall scheduling requirement + // for the subtree under this CompositePodGroup has been satisfied. Once this condition + // transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently deleted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the CompositePodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the CompositePodGroupInitiallyScheduled condition: + // - "Unschedulable": The CompositePodGroup's subtree could not be placed due to resource constraints, + // affinity/anti-affinity, or topological constraints. + // - "SchedulerError": The CompositePodGroup cannot be scheduled due to some internal error + // that occurred during scheduling. + // - "Invalid": Set to True when kube-scheduler detects an invalid group layout during + // runtime validation. The `message` field details the specific layout violation (such as + // a detected cycle, exceeding the maximum depth of 4, or referencing multiple distinct Workloads). + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The CompositePodGroup was targeted by the scheduler's preemption loop + // to free up capacity for higher-priority preemptors. + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` +} + +// CompositePodGroupStatusApplyConfiguration constructs a declarative configuration of the CompositePodGroupStatus type for use with +// apply. +func CompositePodGroupStatus() *CompositePodGroupStatusApplyConfiguration { + return &CompositePodGroupStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *CompositePodGroupStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *CompositePodGroupStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgrouptemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgrouptemplate.go new file mode 100644 index 000000000..fd8aadc2e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/compositepodgrouptemplate.go @@ -0,0 +1,157 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// CompositePodGroupTemplateApplyConfiguration represents a declarative configuration of the CompositePodGroupTemplate type for use +// with apply. +// +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +type CompositePodGroupTemplateApplyConfiguration struct { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + Name *string `json:"name,omitempty"` + // schedulingPolicy defines the scheduling policy for this template. + SchedulingPolicy *CompositePodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + SchedulingConstraints *CompositePodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + DisruptionMode *CompositeDisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + PriorityClassName *string `json:"priorityClassName,omitempty"` + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1alpha3.PreemptionPolicy `json:"preemptionPolicy,omitempty"` + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + PodGroupTemplates []PodGroupTemplateApplyConfiguration `json:"podGroupTemplates,omitempty"` + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + CompositePodGroupTemplates []CompositePodGroupTemplateApplyConfiguration `json:"compositePodGroupTemplates,omitempty"` +} + +// CompositePodGroupTemplateApplyConfiguration constructs a declarative configuration of the CompositePodGroupTemplate type for use with +// apply. +func CompositePodGroupTemplate() *CompositePodGroupTemplateApplyConfiguration { + return &CompositePodGroupTemplateApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithName(value string) *CompositePodGroupTemplateApplyConfiguration { + b.Name = &value + return b +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithSchedulingPolicy(value *CompositePodGroupSchedulingPolicyApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithSchedulingConstraints(value *CompositePodGroupSchedulingConstraintsApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithDisruptionMode(value *CompositeDisruptionModeApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithPriorityClassName sets the PriorityClassName 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 PriorityClassName field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPriorityClassName(value string) *CompositePodGroupTemplateApplyConfiguration { + b.PriorityClassName = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPriority(value int32) *CompositePodGroupTemplateApplyConfiguration { + b.Priority = &value + return b +} + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPreemptionPolicy(value schedulingv1alpha3.PreemptionPolicy) *CompositePodGroupTemplateApplyConfiguration { + b.PreemptionPolicy = &value + return b +} + +// WithPodGroupTemplates adds the given value to the PodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the PodGroupTemplates field. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPodGroupTemplates(values ...*PodGroupTemplateApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithPodGroupTemplates") + } + b.PodGroupTemplates = append(b.PodGroupTemplates, *values[i]) + } + return b +} + +// WithCompositePodGroupTemplates adds the given value to the CompositePodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompositePodGroupTemplates field. +func (b *CompositePodGroupTemplateApplyConfiguration) WithCompositePodGroupTemplates(values ...*CompositePodGroupTemplateApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithCompositePodGroupTemplates") + } + b.CompositePodGroupTemplates = append(b.CompositePodGroupTemplates, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/disruptionmode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/disruptionmode.go new file mode 100644 index 000000000..b500fd360 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/disruptionmode.go @@ -0,0 +1,57 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// DisruptionModeApplyConfiguration represents a declarative configuration of the DisruptionMode type for use +// with apply. +// +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +type DisruptionModeApplyConfiguration struct { + // single specifies that children can be disrupted independently from each other. + Single *schedulingv1alpha3.SingleDisruptionMode `json:"single,omitempty"` + // all specifies that all children can only be disrupted together. + All *schedulingv1alpha3.AllDisruptionMode `json:"all,omitempty"` +} + +// DisruptionModeApplyConfiguration constructs a declarative configuration of the DisruptionMode type for use with +// apply. +func DisruptionMode() *DisruptionModeApplyConfiguration { + return &DisruptionModeApplyConfiguration{} +} + +// WithSingle sets the Single 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 Single field is set to the value of the last call. +func (b *DisruptionModeApplyConfiguration) WithSingle(value schedulingv1alpha3.SingleDisruptionMode) *DisruptionModeApplyConfiguration { + b.Single = &value + return b +} + +// WithAll sets the All 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 All field is set to the value of the last call. +func (b *DisruptionModeApplyConfiguration) WithAll(value schedulingv1alpha3.AllDisruptionMode) *DisruptionModeApplyConfiguration { + b.All = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/gangschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/gangschedulingpolicy.go new file mode 100644 index 000000000..f0d3561ba --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/gangschedulingpolicy.go @@ -0,0 +1,52 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// GangSchedulingPolicyApplyConfiguration represents a declarative configuration of the GangSchedulingPolicy type for use +// with apply. +// +// GangSchedulingPolicy defines the parameters for gang scheduling. +type GangSchedulingPolicyApplyConfiguration struct { + // minCount is the minimum number of pods that must be schedulable or scheduled + // at the same time for the scheduler to admit the entire group. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. + MinCount *int32 `json:"minCount,omitempty"` +} + +// GangSchedulingPolicyApplyConfiguration constructs a declarative configuration of the GangSchedulingPolicy type for use with +// apply. +func GangSchedulingPolicy() *GangSchedulingPolicyApplyConfiguration { + return &GangSchedulingPolicyApplyConfiguration{} +} + +// WithMinCount sets the MinCount 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 MinCount field is set to the value of the last call. +func (b *GangSchedulingPolicyApplyConfiguration) WithMinCount(value int32) *GangSchedulingPolicyApplyConfiguration { + b.MinCount = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroup.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroup.go similarity index 95% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroup.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroup.go index ee2851062..4970d44cb 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroup.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroup.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" managedfields "k8s.io/apimachinery/pkg/util/managedfields" @@ -35,13 +35,13 @@ import ( // Workload.podGroupTemplates. // PodGroup API enablement is toggled by the GenericWorkload feature gate. type PodGroupApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Spec defines the desired state of the PodGroup. + // spec defines the desired state of the PodGroup. Spec *PodGroupSpecApplyConfiguration `json:"spec,omitempty"` - // Status represents the current observed state of the PodGroup. + // status represents the current observed state of the PodGroup. Status *PodGroupStatusApplyConfiguration `json:"status,omitempty"` } @@ -52,7 +52,7 @@ func PodGroup(name, namespace string) *PodGroupApplyConfiguration { b.WithName(name) b.WithNamespace(namespace) b.WithKind("PodGroup") - b.WithAPIVersion("scheduling.k8s.io/v1alpha2") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") return b } @@ -63,9 +63,9 @@ func PodGroup(name, namespace string) *PodGroupApplyConfiguration { // ExtractPodGroupFrom provides a way to perform a extract/modify-in-place/apply workflow. // Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously // applied if another fieldManager has updated or force applied any of the previously applied fields. -func ExtractPodGroupFrom(podGroup *schedulingv1alpha2.PodGroup, fieldManager string, subresource string) (*PodGroupApplyConfiguration, error) { +func ExtractPodGroupFrom(podGroup *schedulingv1alpha3.PodGroup, fieldManager string, subresource string) (*PodGroupApplyConfiguration, error) { b := &PodGroupApplyConfiguration{} - err := managedfields.ExtractInto(podGroup, internal.Parser().Type("io.k8s.api.scheduling.v1alpha2.PodGroup"), fieldManager, b, subresource) + err := managedfields.ExtractInto(podGroup, internal.Parser().Type("io.k8s.api.scheduling.v1alpha3.PodGroup"), fieldManager, b, subresource) if err != nil { return nil, err } @@ -73,7 +73,7 @@ func ExtractPodGroupFrom(podGroup *schedulingv1alpha2.PodGroup, fieldManager str b.WithNamespace(podGroup.Namespace) b.WithKind("PodGroup") - b.WithAPIVersion("scheduling.k8s.io/v1alpha2") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") return b, nil } @@ -87,13 +87,13 @@ func ExtractPodGroupFrom(podGroup *schedulingv1alpha2.PodGroup, fieldManager str // ExtractPodGroup provides a way to perform a extract/modify-in-place/apply workflow. // Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously // applied if another fieldManager has updated or force applied any of the previously applied fields. -func ExtractPodGroup(podGroup *schedulingv1alpha2.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { +func ExtractPodGroup(podGroup *schedulingv1alpha3.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { return ExtractPodGroupFrom(podGroup, fieldManager, "") } // ExtractPodGroupStatus extracts the applied configuration owned by fieldManager from // podGroup for the status subresource. -func ExtractPodGroupStatus(podGroup *schedulingv1alpha2.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { +func ExtractPodGroupStatus(podGroup *schedulingv1alpha3.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { return ExtractPodGroupFrom(podGroup, fieldManager, "status") } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaim.go similarity index 95% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaim.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaim.go index a7b21b530..cb132a07d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaim.go @@ -16,7 +16,7 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 // PodGroupResourceClaimApplyConfiguration represents a declarative configuration of the PodGroupResourceClaim type for use // with apply. @@ -30,17 +30,17 @@ package v1alpha2 // own Spec.ResourceClaims. The Pod's claim must match all fields of the // PodGroup's claim exactly. type PodGroupResourceClaimApplyConfiguration struct { - // Name uniquely identifies this resource claim inside the PodGroup. + // name uniquely identifies this resource claim inside the PodGroup. // This must be a DNS_LABEL. Name *string `json:"name,omitempty"` - // ResourceClaimName is the name of a ResourceClaim object in the same + // resourceClaimName is the name of a ResourceClaim object in the same // namespace as this PodGroup. The ResourceClaim will be reserved for the // PodGroup instead of its individual pods. // // Exactly one of ResourceClaimName and ResourceClaimTemplateName must // be set. ResourceClaimName *string `json:"resourceClaimName,omitempty"` - // ResourceClaimTemplateName is the name of a ResourceClaimTemplate + // resourceClaimTemplateName is the name of a ResourceClaimTemplate // object in the same namespace as this PodGroup. // // The template will be used to create a new ResourceClaim, which will diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaimstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaimstatus.go similarity index 94% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaimstatus.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaimstatus.go index 5f8498b13..e3250d82d 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupresourceclaimstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupresourceclaimstatus.go @@ -16,7 +16,7 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 // PodGroupResourceClaimStatusApplyConfiguration represents a declarative configuration of the PodGroupResourceClaimStatus type for use // with apply. @@ -25,11 +25,11 @@ package v1alpha2 // PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the // generated name for the corresponding ResourceClaim. type PodGroupResourceClaimStatusApplyConfiguration struct { - // Name uniquely identifies this resource claim inside the PodGroup. This + // name uniquely identifies this resource claim inside the PodGroup. This // must match the name of an entry in podgroup.spec.resourceClaims, which // implies that the string must be a DNS_LABEL. Name *string `json:"name,omitempty"` - // ResourceClaimName is the name of the ResourceClaim that was generated for + // resourceClaimName is the name of the ResourceClaim that was generated for // the PodGroup in the namespace of the PodGroup. If this is unset, then // generating a ResourceClaim was not necessary. The // podgroup.spec.resourceClaims entry can be ignored in this case. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingconstraints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingconstraints.go similarity index 96% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingconstraints.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingconstraints.go index eda72ea50..5dadef14b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingconstraints.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingconstraints.go @@ -16,14 +16,14 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 // PodGroupSchedulingConstraintsApplyConfiguration represents a declarative configuration of the PodGroupSchedulingConstraints type for use // with apply. // // PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. type PodGroupSchedulingConstraintsApplyConfiguration struct { - // Topology defines the topology constraints for the pod group. + // topology defines the topology constraints for the pod group. // Currently only a single topology constraint can be specified. This may change in the future. Topology []TopologyConstraintApplyConfiguration `json:"topology,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingpolicy.go similarity index 67% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingpolicy.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingpolicy.go index 02be5f27e..67232d192 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupschedulingpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupschedulingpolicy.go @@ -16,23 +16,28 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" ) // PodGroupSchedulingPolicyApplyConfiguration represents a declarative configuration of the PodGroupSchedulingPolicy type for use // with apply. // // PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. -// Exactly one policy must be set. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. type PodGroupSchedulingPolicyApplyConfiguration struct { - // Basic specifies that the pods in this group should be scheduled using - // standard Kubernetes scheduling behavior. - Basic *schedulingv1alpha2.BasicSchedulingPolicy `json:"basic,omitempty"` - // Gang specifies that the pods in this group should be scheduled using - // all-or-nothing semantics. + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + Basic *schedulingv1alpha3.BasicSchedulingPolicy `json:"basic,omitempty"` + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. Gang *GangSchedulingPolicyApplyConfiguration `json:"gang,omitempty"` } @@ -45,7 +50,7 @@ func PodGroupSchedulingPolicy() *PodGroupSchedulingPolicyApplyConfiguration { // WithBasic sets the Basic 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 Basic field is set to the value of the last call. -func (b *PodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1alpha2.BasicSchedulingPolicy) *PodGroupSchedulingPolicyApplyConfiguration { +func (b *PodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1alpha3.BasicSchedulingPolicy) *PodGroupSchedulingPolicyApplyConfiguration { b.Basic = &value return b } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupspec.go new file mode 100644 index 000000000..5ca2ee1ab --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupspec.go @@ -0,0 +1,168 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// PodGroupSpecApplyConfiguration represents a declarative configuration of the PodGroupSpec type for use +// with apply. +// +// PodGroupSpec defines the desired state of a PodGroup. +type PodGroupSpecApplyConfiguration struct { + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty"` + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. + // This field is immutable. + WorkloadRef *WorkloadReferenceApplyConfiguration `json:"workloadRef,omitempty"` + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + SchedulingPolicy *PodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // This field is immutable. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + SchedulingConstraints *PodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + ResourceClaims []PodGroupResourceClaimApplyConfiguration `json:"resourceClaims,omitempty"` + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // One of Single, All. Defaults to Single if unset. + // This field is immutable. + DisruptionMode *DisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName defines the priority that should be considered when scheduling this pod group. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate + // (i.e. if no priority class is specified, admission control can set this to the global default + // priority class if it exists. Otherwise, the pod group's priority will be zero). + // This field is immutable. + PriorityClassName *string `json:"priorityClassName,omitempty"` + // priority is the value of priority of this pod group. Various system components + // use this field to find the priority of the pod group. When Priority Admission + // Controller is enabled, it prevents users from setting this field. The admission + // controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1alpha3.PreemptionPolicy `json:"preemptionPolicy,omitempty"` +} + +// PodGroupSpecApplyConfiguration constructs a declarative configuration of the PodGroupSpec type for use with +// apply. +func PodGroupSpec() *PodGroupSpecApplyConfiguration { + return &PodGroupSpecApplyConfiguration{} +} + +// WithParentCompositePodGroupName sets the ParentCompositePodGroupName 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 ParentCompositePodGroupName field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithParentCompositePodGroupName(value string) *PodGroupSpecApplyConfiguration { + b.ParentCompositePodGroupName = &value + return b +} + +// WithWorkloadRef sets the WorkloadRef 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 WorkloadRef field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithWorkloadRef(value *WorkloadReferenceApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.WorkloadRef = value + return b +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithSchedulingPolicy(value *PodGroupSchedulingPolicyApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithSchedulingConstraints(value *PodGroupSchedulingConstraintsApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithResourceClaims adds the given value to the ResourceClaims field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ResourceClaims field. +func (b *PodGroupSpecApplyConfiguration) WithResourceClaims(values ...*PodGroupResourceClaimApplyConfiguration) *PodGroupSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResourceClaims") + } + b.ResourceClaims = append(b.ResourceClaims, *values[i]) + } + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithDisruptionMode(value *DisruptionModeApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithPriorityClassName sets the PriorityClassName 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 PriorityClassName field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithPriorityClassName(value string) *PodGroupSpecApplyConfiguration { + b.PriorityClassName = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithPriority(value int32) *PodGroupSpecApplyConfiguration { + b.Priority = &value + return b +} + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithPreemptionPolicy(value schedulingv1alpha3.PreemptionPolicy) *PodGroupSpecApplyConfiguration { + b.PreemptionPolicy = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupstatus.go new file mode 100644 index 000000000..af0b5d31d --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgroupstatus.go @@ -0,0 +1,83 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// PodGroupStatusApplyConfiguration represents a declarative configuration of the PodGroupStatus type for use +// with apply. +// +// PodGroupStatus represents information about the status of a pod group. +type PodGroupStatusApplyConfiguration struct { + // conditions represent the latest observations of the PodGroup's state. + // + // Known condition types: + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. + // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated + // due to disruption such as preemption. + // + // Known reasons for the PodGroupInitiallyScheduled condition: + // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, + // affinity/anti-affinity rules, or insufficient capacity for the gang. + // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error + // that happened during scheduling, for example due to nodeAffinity parsing errors. + // + // Known reasons for the DisruptionTarget condition: + // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for + // higher-priority PodGroups or Pods. + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + // resourceClaimStatuses is status of resource claims. + ResourceClaimStatuses []PodGroupResourceClaimStatusApplyConfiguration `json:"resourceClaimStatuses,omitempty"` +} + +// PodGroupStatusApplyConfiguration constructs a declarative configuration of the PodGroupStatus type for use with +// apply. +func PodGroupStatus() *PodGroupStatusApplyConfiguration { + return &PodGroupStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *PodGroupStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *PodGroupStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithResourceClaimStatuses adds the given value to the ResourceClaimStatuses field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ResourceClaimStatuses field. +func (b *PodGroupStatusApplyConfiguration) WithResourceClaimStatuses(values ...*PodGroupResourceClaimStatusApplyConfiguration) *PodGroupStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResourceClaimStatuses") + } + b.ResourceClaimStatuses = append(b.ResourceClaimStatuses, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgrouptemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgrouptemplate.go new file mode 100644 index 000000000..b004ac0b3 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/podgrouptemplate.go @@ -0,0 +1,143 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// PodGroupTemplateApplyConfiguration represents a declarative configuration of the PodGroupTemplate type for use +// with apply. +// +// PodGroupTemplate represents a template for a set of pods with a scheduling policy. +type PodGroupTemplateApplyConfiguration struct { + // name is a unique identifier for the PodGroupTemplate within the Workload. + // It must be a DNS label. This field is immutable. + Name *string `json:"name,omitempty"` + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. + SchedulingPolicy *PodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. + SchedulingConstraints *PodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // resourceClaims defines which ResourceClaims may be shared among Pods in + // the group. Pods consume the devices allocated to a PodGroup's claim by + // defining a claim in its own Spec.ResourceClaims that matches the + // PodGroup's claim exactly. The claim must have the same name and refer to + // the same ResourceClaim or ResourceClaimTemplate. + // + // This is a beta-level field and requires that the + // DRAWorkloadResourceClaims feature gate is enabled. + // + // This field is immutable. + ResourceClaims []PodGroupResourceClaimApplyConfiguration `json:"resourceClaims,omitempty"` + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + DisruptionMode *DisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. + PriorityClassName *string `json:"priorityClassName,omitempty"` + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. + // The higher the value, the higher the priority. + // This field is immutable. + Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1alpha3.PreemptionPolicy `json:"preemptionPolicy,omitempty"` +} + +// PodGroupTemplateApplyConfiguration constructs a declarative configuration of the PodGroupTemplate type for use with +// apply. +func PodGroupTemplate() *PodGroupTemplateApplyConfiguration { + return &PodGroupTemplateApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithName(value string) *PodGroupTemplateApplyConfiguration { + b.Name = &value + return b +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithSchedulingPolicy(value *PodGroupSchedulingPolicyApplyConfiguration) *PodGroupTemplateApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithSchedulingConstraints(value *PodGroupSchedulingConstraintsApplyConfiguration) *PodGroupTemplateApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithResourceClaims adds the given value to the ResourceClaims field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the ResourceClaims field. +func (b *PodGroupTemplateApplyConfiguration) WithResourceClaims(values ...*PodGroupResourceClaimApplyConfiguration) *PodGroupTemplateApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithResourceClaims") + } + b.ResourceClaims = append(b.ResourceClaims, *values[i]) + } + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithDisruptionMode(value *DisruptionModeApplyConfiguration) *PodGroupTemplateApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithPriorityClassName sets the PriorityClassName 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 PriorityClassName field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithPriorityClassName(value string) *PodGroupTemplateApplyConfiguration { + b.PriorityClassName = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithPriority(value int32) *PodGroupTemplateApplyConfiguration { + b.Priority = &value + return b +} + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithPreemptionPolicy(value schedulingv1alpha3.PreemptionPolicy) *PodGroupTemplateApplyConfiguration { + b.PreemptionPolicy = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/topologyconstraint.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/topologyconstraint.go similarity index 95% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/topologyconstraint.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/topologyconstraint.go index 92727eb2b..b1c4f2638 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/topologyconstraint.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/topologyconstraint.go @@ -16,14 +16,14 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 // TopologyConstraintApplyConfiguration represents a declarative configuration of the TopologyConstraint type for use // with apply. // // TopologyConstraint defines a topology constraint for a PodGroup. type TopologyConstraintApplyConfiguration struct { - // Key specifies the key of the node label representing the topology domain. + // key specifies the key of the node label representing the topology domain. // All pods within the PodGroup must be colocated within the same domain instance. // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. // Examples: "topology.kubernetes.io/rack" diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/typedlocalobjectreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/typedlocalobjectreference.go similarity index 94% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/typedlocalobjectreference.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/typedlocalobjectreference.go index cfbbc48e0..e8303eb66 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/typedlocalobjectreference.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/typedlocalobjectreference.go @@ -16,22 +16,22 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 // TypedLocalObjectReferenceApplyConfiguration represents a declarative configuration of the TypedLocalObjectReference type for use // with apply. // // TypedLocalObjectReference allows to reference typed object inside the same namespace. type TypedLocalObjectReferenceApplyConfiguration struct { - // APIGroup is the group for the resource being referenced. + // apiGroup is the group for the resource being referenced. // If APIGroup is empty, the specified Kind must be in the core API group. // For any other third-party types, setting APIGroup is required. // It must be a DNS subdomain. APIGroup *string `json:"apiGroup,omitempty"` - // Kind is the type of resource being referenced. + // kind is the type of resource being referenced. // It must be a path segment name. Kind *string `json:"kind,omitempty"` - // Name is the name of resource being referenced. + // name is the name of resource being referenced. // It must be a path segment name. Name *string `json:"name,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workload.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workload.go similarity index 96% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workload.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workload.go index 787095d23..6088ead03 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workload.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workload.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" managedfields "k8s.io/apimachinery/pkg/util/managedfields" @@ -35,11 +35,11 @@ import ( // including scheduling, preemption, eviction and other phases. // Workload API enablement is toggled by the GenericWorkload feature gate. type WorkloadApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Spec defines the desired behavior of a Workload. + // spec defines the desired behavior of a Workload. Spec *WorkloadSpecApplyConfiguration `json:"spec,omitempty"` } @@ -50,7 +50,7 @@ func Workload(name, namespace string) *WorkloadApplyConfiguration { b.WithName(name) b.WithNamespace(namespace) b.WithKind("Workload") - b.WithAPIVersion("scheduling.k8s.io/v1alpha2") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") return b } @@ -61,9 +61,9 @@ func Workload(name, namespace string) *WorkloadApplyConfiguration { // ExtractWorkloadFrom provides a way to perform a extract/modify-in-place/apply workflow. // Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously // applied if another fieldManager has updated or force applied any of the previously applied fields. -func ExtractWorkloadFrom(workload *schedulingv1alpha2.Workload, fieldManager string, subresource string) (*WorkloadApplyConfiguration, error) { +func ExtractWorkloadFrom(workload *schedulingv1alpha3.Workload, fieldManager string, subresource string) (*WorkloadApplyConfiguration, error) { b := &WorkloadApplyConfiguration{} - err := managedfields.ExtractInto(workload, internal.Parser().Type("io.k8s.api.scheduling.v1alpha2.Workload"), fieldManager, b, subresource) + err := managedfields.ExtractInto(workload, internal.Parser().Type("io.k8s.api.scheduling.v1alpha3.Workload"), fieldManager, b, subresource) if err != nil { return nil, err } @@ -71,7 +71,7 @@ func ExtractWorkloadFrom(workload *schedulingv1alpha2.Workload, fieldManager str b.WithNamespace(workload.Namespace) b.WithKind("Workload") - b.WithAPIVersion("scheduling.k8s.io/v1alpha2") + b.WithAPIVersion("scheduling.k8s.io/v1alpha3") return b, nil } @@ -85,7 +85,7 @@ func ExtractWorkloadFrom(workload *schedulingv1alpha2.Workload, fieldManager str // ExtractWorkload provides a way to perform a extract/modify-in-place/apply workflow. // Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously // applied if another fieldManager has updated or force applied any of the previously applied fields. -func ExtractWorkload(workload *schedulingv1alpha2.Workload, fieldManager string) (*WorkloadApplyConfiguration, error) { +func ExtractWorkload(workload *schedulingv1alpha3.Workload, fieldManager string) (*WorkloadApplyConfiguration, error) { return ExtractWorkloadFrom(workload, fieldManager, "") } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupdisruptionmode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupdisruptionmode.go new file mode 100644 index 000000000..4a524de53 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupdisruptionmode.go @@ -0,0 +1,78 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// WorkloadPodGroupDisruptionModeApplyConfiguration represents a declarative configuration of the WorkloadPodGroupDisruptionMode type for use +// with apply. +// +// WorkloadPodGroupDisruptionMode defines how individual pods within a +// group can be disrupted. Exactly one mode must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since the selected mode is immutable in the compiled +// Workload. For example, +// +// type JobSchedulingConfiguration struct { +// // DisruptionMode defines the mode in which the Job's pods can be disrupted. +// // One of Single, All. +// // This field is immutable after creation: it may not be added or removed, +// // and the selected mode may not be changed. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// DisruptionMode *schedulingv1alpha3.WorkloadPodGroupDisruptionMode `json:"disruptionMode,omitempty" protobuf:"bytes,N,opt,name=disruptionMode"` +// +// // other scheduling fields +// } +type WorkloadPodGroupDisruptionModeApplyConfiguration struct { + // single specifies that pods can be disrupted independently from each other. + Single *schedulingv1alpha3.WorkloadPodGroupSingleDisruptionMode `json:"single,omitempty"` + // all specifies that all pods in the group must be disrupted together. + All *schedulingv1alpha3.WorkloadPodGroupAllDisruptionMode `json:"all,omitempty"` +} + +// WorkloadPodGroupDisruptionModeApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupDisruptionMode type for use with +// apply. +func WorkloadPodGroupDisruptionMode() *WorkloadPodGroupDisruptionModeApplyConfiguration { + return &WorkloadPodGroupDisruptionModeApplyConfiguration{} +} + +// WithSingle sets the Single 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 Single field is set to the value of the last call. +func (b *WorkloadPodGroupDisruptionModeApplyConfiguration) WithSingle(value schedulingv1alpha3.WorkloadPodGroupSingleDisruptionMode) *WorkloadPodGroupDisruptionModeApplyConfiguration { + b.Single = &value + return b +} + +// WithAll sets the All 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 All field is set to the value of the last call. +func (b *WorkloadPodGroupDisruptionModeApplyConfiguration) WithAll(value schedulingv1alpha3.WorkloadPodGroupAllDisruptionMode) *WorkloadPodGroupDisruptionModeApplyConfiguration { + b.All = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupgangschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupgangschedulingpolicy.go new file mode 100644 index 000000000..4464dfc2a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupgangschedulingpolicy.go @@ -0,0 +1,48 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// WorkloadPodGroupGangSchedulingPolicyApplyConfiguration represents a declarative configuration of the WorkloadPodGroupGangSchedulingPolicy type for use +// with apply. +// +// WorkloadPodGroupGangSchedulingPolicy defines the parameters for gang +// (all-or-nothing) scheduling. +type WorkloadPodGroupGangSchedulingPolicyApplyConfiguration struct { + // minCount is the minimum number of pods that must be scheduled + // at the same time for the scheduler to admit the entire group. + // This field is optional. If it is not specified, the controller + // should inject a context-specific sane default (e.g., + // parallelism for a Job). + // If set, it must be a positive integer. + MinCount *int32 `json:"minCount,omitempty"` +} + +// WorkloadPodGroupGangSchedulingPolicyApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupGangSchedulingPolicy type for use with +// apply. +func WorkloadPodGroupGangSchedulingPolicy() *WorkloadPodGroupGangSchedulingPolicyApplyConfiguration { + return &WorkloadPodGroupGangSchedulingPolicyApplyConfiguration{} +} + +// WithMinCount sets the MinCount 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 MinCount field is set to the value of the last call. +func (b *WorkloadPodGroupGangSchedulingPolicyApplyConfiguration) WithMinCount(value int32) *WorkloadPodGroupGangSchedulingPolicyApplyConfiguration { + b.MinCount = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupresourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupresourceclaim.go new file mode 100644 index 000000000..a34c5a2e5 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupresourceclaim.go @@ -0,0 +1,98 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// WorkloadPodGroupResourceClaimApplyConfiguration represents a declarative configuration of the WorkloadPodGroupResourceClaim type for use +// with apply. +// +// WorkloadPodGroupResourceClaim references a dynamic resource claim +// that is shared across pods in the group. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API as a list, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the whole list after creation +// (+k8s:immutable), since the list is immutable in the compiled Workload. For +// example, +// +// type JobSchedulingConfiguration struct { +// // ResourceClaims lists the ResourceClaims shared among the group's pods. +// // At most 4 claims may be set, matching the limit on the resulting PodGroup. +// // This list is immutable after creation: entries may neither be added, +// // removed, nor modified. +// // +optional +// // +patchMergeKey=name +// // +patchStrategy=merge +// // +listType=map +// // +listMapKey=name +// // +k8s:optional +// // +k8s:listType=map +// // +k8s:listMapKey=name +// // +k8s:maxItems=4 +// // +k8s:immutable +// ResourceClaims []schedulingv1alpha3.WorkloadPodGroupResourceClaim `json:"resourceClaims,omitempty" protobuf:"bytes,N,rep,name=resourceClaims"` +// +// // other scheduling fields +// } +type WorkloadPodGroupResourceClaimApplyConfiguration struct { + // name uniquely identifies this resource claim inside the group. + // This field is required. It must be a DNS_LABEL. + Name *string `json:"name,omitempty"` + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace. + // This field is optional. If it is not specified, no resource claim + // is used. If set, it must be a DNS subdomain. + ResourceClaimName *string `json:"resourceClaimName,omitempty"` + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace. + // This field is optional. If it is not specified, no resource claim + // template is used. If set, it must be a DNS subdomain. + ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty"` +} + +// WorkloadPodGroupResourceClaimApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupResourceClaim type for use with +// apply. +func WorkloadPodGroupResourceClaim() *WorkloadPodGroupResourceClaimApplyConfiguration { + return &WorkloadPodGroupResourceClaimApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *WorkloadPodGroupResourceClaimApplyConfiguration) WithName(value string) *WorkloadPodGroupResourceClaimApplyConfiguration { + b.Name = &value + return b +} + +// WithResourceClaimName sets the ResourceClaimName 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 ResourceClaimName field is set to the value of the last call. +func (b *WorkloadPodGroupResourceClaimApplyConfiguration) WithResourceClaimName(value string) *WorkloadPodGroupResourceClaimApplyConfiguration { + b.ResourceClaimName = &value + return b +} + +// WithResourceClaimTemplateName sets the ResourceClaimTemplateName 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 ResourceClaimTemplateName field is set to the value of the last call. +func (b *WorkloadPodGroupResourceClaimApplyConfiguration) WithResourceClaimTemplateName(value string) *WorkloadPodGroupResourceClaimApplyConfiguration { + b.ResourceClaimTemplateName = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingconstraints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingconstraints.go new file mode 100644 index 000000000..1721ca6cb --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingconstraints.go @@ -0,0 +1,70 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// WorkloadPodGroupSchedulingConstraintsApplyConfiguration represents a declarative configuration of the WorkloadPodGroupSchedulingConstraints type for use +// with apply. +// +// WorkloadPodGroupSchedulingConstraints defines leaf-level scheduling +// constraints, such as topology. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to freeze the field after creation +// (+k8s:immutable), since constraints are immutable in the compiled Workload. +// For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingConstraints defines scheduling constraints (e.g. topology) +// // for the Job's pods. +// // This field is immutable after creation. +// // +optional +// // +k8s:optional +// // +k8s:immutable +// SchedulingConstraints *schedulingv1alpha3.WorkloadPodGroupSchedulingConstraints `json:"schedulingConstraints,omitempty" protobuf:"bytes,N,opt,name=schedulingConstraints"` +// +// // other scheduling fields +// } +type WorkloadPodGroupSchedulingConstraintsApplyConfiguration struct { + // topology specifies desired topological placements for all pods + // within the pod group. + // If unset, no topology placement is requested. + Topology []TopologyConstraintApplyConfiguration `json:"topology,omitempty"` +} + +// WorkloadPodGroupSchedulingConstraintsApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupSchedulingConstraints type for use with +// apply. +func WorkloadPodGroupSchedulingConstraints() *WorkloadPodGroupSchedulingConstraintsApplyConfiguration { + return &WorkloadPodGroupSchedulingConstraintsApplyConfiguration{} +} + +// WithTopology adds the given value to the Topology field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Topology field. +func (b *WorkloadPodGroupSchedulingConstraintsApplyConfiguration) WithTopology(values ...*TopologyConstraintApplyConfiguration) *WorkloadPodGroupSchedulingConstraintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTopology") + } + b.Topology = append(b.Topology, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingpolicy.go new file mode 100644 index 000000000..13a1249d8 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadpodgroupschedulingpolicy.go @@ -0,0 +1,84 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" +) + +// WorkloadPodGroupSchedulingPolicyApplyConfiguration represents a declarative configuration of the WorkloadPodGroupSchedulingPolicy type for use +// with apply. +// +// WorkloadPodGroupSchedulingPolicy defines the scheduling policy for a +// group of pods managed by a workload controller. +// Exactly one policy must be set. +// +// --- +// +// This is a reusable building block meant to be embedded in a controller's own +// API, next to its other scheduling fields (for example, in a Job's +// spec.scheduling). It's recommended to block changing the policy +// after creation, while still allowing gang.minCount to change. DV cannot +// express that only gang.minCount is mutable while the basic/gang variant is +// frozen, so the embedder must enforce variant immutability with hand-written +// validation. For example, +// +// type JobSchedulingConfiguration struct { +// // SchedulingPolicy defines the scheduling policy for this Job. +// // Exactly one of Basic or Gang must be set. +// // This field is immutable after creation: the policy may not be added or +// // removed. The policy variant (basic/gang) is frozen by the controller's +// // hand-written validation; only schedulingPolicy.gang.minCount may be changed. +// // +optional +// // +k8s:optional +// // +k8s:update=NoSet +// // +k8s:update=NoUnset +// SchedulingPolicy *schedulingv1alpha3.WorkloadPodGroupSchedulingPolicy `json:"schedulingPolicy,omitempty" protobuf:"bytes,N,opt,name=schedulingPolicy"` +// +// // other scheduling fields +// } +type WorkloadPodGroupSchedulingPolicyApplyConfiguration struct { + // basic specifies that standard, pod-by-pod Kubernetes scheduling + // behavior should be used. + Basic *schedulingv1alpha3.WorkloadPodGroupBasicSchedulingPolicy `json:"basic,omitempty"` + // gang specifies all-or-nothing scheduling semantics. + Gang *WorkloadPodGroupGangSchedulingPolicyApplyConfiguration `json:"gang,omitempty"` +} + +// WorkloadPodGroupSchedulingPolicyApplyConfiguration constructs a declarative configuration of the WorkloadPodGroupSchedulingPolicy type for use with +// apply. +func WorkloadPodGroupSchedulingPolicy() *WorkloadPodGroupSchedulingPolicyApplyConfiguration { + return &WorkloadPodGroupSchedulingPolicyApplyConfiguration{} +} + +// WithBasic sets the Basic 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 Basic field is set to the value of the last call. +func (b *WorkloadPodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1alpha3.WorkloadPodGroupBasicSchedulingPolicy) *WorkloadPodGroupSchedulingPolicyApplyConfiguration { + b.Basic = &value + return b +} + +// WithGang sets the Gang 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 Gang field is set to the value of the last call. +func (b *WorkloadPodGroupSchedulingPolicyApplyConfiguration) WithGang(value *WorkloadPodGroupGangSchedulingPolicyApplyConfiguration) *WorkloadPodGroupSchedulingPolicyApplyConfiguration { + b.Gang = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadreference.go new file mode 100644 index 000000000..e7dd7c7c5 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadreference.go @@ -0,0 +1,58 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// WorkloadReferenceApplyConfiguration represents a declarative configuration of the WorkloadReference type for use +// with apply. +// +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +type WorkloadReferenceApplyConfiguration struct { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + WorkloadName *string `json:"workloadName,omitempty"` + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + TemplateName *string `json:"templateName,omitempty"` +} + +// WorkloadReferenceApplyConfiguration constructs a declarative configuration of the WorkloadReference type for use with +// apply. +func WorkloadReference() *WorkloadReferenceApplyConfiguration { + return &WorkloadReferenceApplyConfiguration{} +} + +// WithWorkloadName sets the WorkloadName 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 WorkloadName field is set to the value of the last call. +func (b *WorkloadReferenceApplyConfiguration) WithWorkloadName(value string) *WorkloadReferenceApplyConfiguration { + b.WorkloadName = &value + return b +} + +// WithTemplateName sets the TemplateName 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 TemplateName field is set to the value of the last call. +func (b *WorkloadReferenceApplyConfiguration) WithTemplateName(value string) *WorkloadReferenceApplyConfiguration { + b.TemplateName = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadspec.go new file mode 100644 index 000000000..475b99874 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha3/workloadspec.go @@ -0,0 +1,82 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha3 + +// WorkloadSpecApplyConfiguration represents a declarative configuration of the WorkloadSpec type for use +// with apply. +// +// WorkloadSpec defines the desired state of a Workload. +type WorkloadSpecApplyConfiguration struct { + // controllerRef is an optional reference to the controlling object, such as a + // Deployment or Job. This field is intended for use by tools like CLIs + // to provide a link back to the original workload definition. + // This field is immutable. + ControllerRef *TypedLocalObjectReferenceApplyConfiguration `json:"controllerRef,omitempty"` + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + PodGroupTemplates []PodGroupTemplateApplyConfiguration `json:"podGroupTemplates,omitempty"` + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + CompositePodGroupTemplates []CompositePodGroupTemplateApplyConfiguration `json:"compositePodGroupTemplates,omitempty"` +} + +// WorkloadSpecApplyConfiguration constructs a declarative configuration of the WorkloadSpec type for use with +// apply. +func WorkloadSpec() *WorkloadSpecApplyConfiguration { + return &WorkloadSpecApplyConfiguration{} +} + +// WithControllerRef sets the ControllerRef 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 ControllerRef field is set to the value of the last call. +func (b *WorkloadSpecApplyConfiguration) WithControllerRef(value *TypedLocalObjectReferenceApplyConfiguration) *WorkloadSpecApplyConfiguration { + b.ControllerRef = value + return b +} + +// WithPodGroupTemplates adds the given value to the PodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the PodGroupTemplates field. +func (b *WorkloadSpecApplyConfiguration) WithPodGroupTemplates(values ...*PodGroupTemplateApplyConfiguration) *WorkloadSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithPodGroupTemplates") + } + b.PodGroupTemplates = append(b.PodGroupTemplates, *values[i]) + } + return b +} + +// WithCompositePodGroupTemplates adds the given value to the CompositePodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompositePodGroupTemplates field. +func (b *WorkloadSpecApplyConfiguration) WithCompositePodGroupTemplates(values ...*CompositePodGroupTemplateApplyConfiguration) *WorkloadSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithCompositePodGroupTemplates") + } + b.CompositePodGroupTemplates = append(b.CompositePodGroupTemplates, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositedisruptionmode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositedisruptionmode.go new file mode 100644 index 000000000..40f9a6298 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositedisruptionmode.go @@ -0,0 +1,57 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" +) + +// CompositeDisruptionModeApplyConfiguration represents a declarative configuration of the CompositeDisruptionMode type for use +// with apply. +// +// CompositeDisruptionMode defines how individual entities within a composite pod group can be disrupted. +// Exactly one mode must be set. +type CompositeDisruptionModeApplyConfiguration struct { + // single specifies that children groups can be disrupted independently from each other. + Single *schedulingv1beta1.SingleCompositeDisruptionMode `json:"single,omitempty"` + // all specifies that all children groups can only be disrupted together. + All *schedulingv1beta1.AllCompositeDisruptionMode `json:"all,omitempty"` +} + +// CompositeDisruptionModeApplyConfiguration constructs a declarative configuration of the CompositeDisruptionMode type for use with +// apply. +func CompositeDisruptionMode() *CompositeDisruptionModeApplyConfiguration { + return &CompositeDisruptionModeApplyConfiguration{} +} + +// WithSingle sets the Single 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 Single field is set to the value of the last call. +func (b *CompositeDisruptionModeApplyConfiguration) WithSingle(value schedulingv1beta1.SingleCompositeDisruptionMode) *CompositeDisruptionModeApplyConfiguration { + b.Single = &value + return b +} + +// WithAll sets the All 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 All field is set to the value of the last call. +func (b *CompositeDisruptionModeApplyConfiguration) WithAll(value schedulingv1beta1.AllCompositeDisruptionMode) *CompositeDisruptionModeApplyConfiguration { + b.All = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositegangschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositegangschedulingpolicy.go new file mode 100644 index 000000000..fc007af15 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositegangschedulingpolicy.go @@ -0,0 +1,45 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// CompositeGangSchedulingPolicyApplyConfiguration represents a declarative configuration of the CompositeGangSchedulingPolicy type for use +// with apply. +// +// CompositeGangSchedulingPolicy indicates that the groups belonging to the composite group +// should be scheduled using all-or-nothing semantics. +type CompositeGangSchedulingPolicyApplyConfiguration struct { + // minGroupCount is the minimum number of child groups that must be schedulable + // or scheduled at the same time for the scheduler to admit the entire group. + // It must be a positive integer. + MinGroupCount *int32 `json:"minGroupCount,omitempty"` +} + +// CompositeGangSchedulingPolicyApplyConfiguration constructs a declarative configuration of the CompositeGangSchedulingPolicy type for use with +// apply. +func CompositeGangSchedulingPolicy() *CompositeGangSchedulingPolicyApplyConfiguration { + return &CompositeGangSchedulingPolicyApplyConfiguration{} +} + +// WithMinGroupCount sets the MinGroupCount 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 MinGroupCount field is set to the value of the last call. +func (b *CompositeGangSchedulingPolicyApplyConfiguration) WithMinGroupCount(value int32) *CompositeGangSchedulingPolicyApplyConfiguration { + b.MinGroupCount = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingconstraints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingconstraints.go new file mode 100644 index 000000000..56361230c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingconstraints.go @@ -0,0 +1,48 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// CompositePodGroupSchedulingConstraintsApplyConfiguration represents a declarative configuration of the CompositePodGroupSchedulingConstraints type for use +// with apply. +// +// CompositePodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a CompositePodGroup. +type CompositePodGroupSchedulingConstraintsApplyConfiguration struct { + // topology defines the topology constraints for the composite pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + Topology []TopologyConstraintApplyConfiguration `json:"topology,omitempty"` +} + +// CompositePodGroupSchedulingConstraintsApplyConfiguration constructs a declarative configuration of the CompositePodGroupSchedulingConstraints type for use with +// apply. +func CompositePodGroupSchedulingConstraints() *CompositePodGroupSchedulingConstraintsApplyConfiguration { + return &CompositePodGroupSchedulingConstraintsApplyConfiguration{} +} + +// WithTopology adds the given value to the Topology field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Topology field. +func (b *CompositePodGroupSchedulingConstraintsApplyConfiguration) WithTopology(values ...*TopologyConstraintApplyConfiguration) *CompositePodGroupSchedulingConstraintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTopology") + } + b.Topology = append(b.Topology, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingpolicy.go new file mode 100644 index 000000000..8c8905d77 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgroupschedulingpolicy.go @@ -0,0 +1,59 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" +) + +// CompositePodGroupSchedulingPolicyApplyConfiguration represents a declarative configuration of the CompositePodGroupSchedulingPolicy type for use +// with apply. +// +// CompositePodGroupSchedulingPolicy defines the scheduling configuration for a CompositePodGroup. +// Exactly one policy must be set. +type CompositePodGroupSchedulingPolicyApplyConfiguration struct { + // basic specifies that the groups of this composite group should be scheduled independently. + // This field is immutable. + Basic *schedulingv1beta1.CompositeBasicSchedulingPolicy `json:"basic,omitempty"` + // gang specifies that the groups of this composite group should be scheduled using + // all-or-nothing semantics. + Gang *CompositeGangSchedulingPolicyApplyConfiguration `json:"gang,omitempty"` +} + +// CompositePodGroupSchedulingPolicyApplyConfiguration constructs a declarative configuration of the CompositePodGroupSchedulingPolicy type for use with +// apply. +func CompositePodGroupSchedulingPolicy() *CompositePodGroupSchedulingPolicyApplyConfiguration { + return &CompositePodGroupSchedulingPolicyApplyConfiguration{} +} + +// WithBasic sets the Basic 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 Basic field is set to the value of the last call. +func (b *CompositePodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1beta1.CompositeBasicSchedulingPolicy) *CompositePodGroupSchedulingPolicyApplyConfiguration { + b.Basic = &value + return b +} + +// WithGang sets the Gang 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 Gang field is set to the value of the last call. +func (b *CompositePodGroupSchedulingPolicyApplyConfiguration) WithGang(value *CompositeGangSchedulingPolicyApplyConfiguration) *CompositePodGroupSchedulingPolicyApplyConfiguration { + b.Gang = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgrouptemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgrouptemplate.go new file mode 100644 index 000000000..511b4cca5 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/compositepodgrouptemplate.go @@ -0,0 +1,157 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" +) + +// CompositePodGroupTemplateApplyConfiguration represents a declarative configuration of the CompositePodGroupTemplate type for use +// with apply. +// +// CompositePodGroupTemplate represents a template for a CompositePodGroup with a scheduling policy. +type CompositePodGroupTemplateApplyConfiguration struct { + // name is a unique identifier for the CompositePodGroupTemplate within the Workload. + // It must be a DNS label. This field is required. + Name *string `json:"name,omitempty"` + // schedulingPolicy defines the scheduling policy for this template. + SchedulingPolicy *CompositePodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this CompositePodGroupTemplate. + // This field is immutable. + SchedulingConstraints *CompositePodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` + // disruptionMode defines the mode in which a given CompositePodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + DisruptionMode *CompositeDisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName indicates the priority that should be considered when scheduling + // a composite pod group created from this template. If no priority class is specified, + // admission control can set this to the global default priority class if it exists. + // Otherwise, composite pod groups created from this template will have the priority set + // to zero. + // This field is immutable. + PriorityClassName *string `json:"priorityClassName,omitempty"` + // priority is the value of priority of composite pod groups created from this template. + // Various system components use this field to find the priority of the composite pod group. + // When Priority Admission Controller is enabled, it prevents users from setting this field. + // The admission controller populates this field from PriorityClassName. + // The higher the value, the higher the priority. + // This field is immutable. + Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1beta1.PreemptionPolicy `json:"preemptionPolicy,omitempty"` + // podGroupTemplates is the list of templates for children PodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + PodGroupTemplates []PodGroupTemplateApplyConfiguration `json:"podGroupTemplates,omitempty"` + // compositePodGroupTemplates is the list of templates for children CompositePodGroups. + // The maximum number of templates is 8. At least one entry in CompositePodGroupTemplates + // or PodGroupTemplates must be set. + CompositePodGroupTemplates []CompositePodGroupTemplateApplyConfiguration `json:"compositePodGroupTemplates,omitempty"` +} + +// CompositePodGroupTemplateApplyConfiguration constructs a declarative configuration of the CompositePodGroupTemplate type for use with +// apply. +func CompositePodGroupTemplate() *CompositePodGroupTemplateApplyConfiguration { + return &CompositePodGroupTemplateApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithName(value string) *CompositePodGroupTemplateApplyConfiguration { + b.Name = &value + return b +} + +// WithSchedulingPolicy sets the SchedulingPolicy 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 SchedulingPolicy field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithSchedulingPolicy(value *CompositePodGroupSchedulingPolicyApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.SchedulingPolicy = value + return b +} + +// WithSchedulingConstraints sets the SchedulingConstraints 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 SchedulingConstraints field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithSchedulingConstraints(value *CompositePodGroupSchedulingConstraintsApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.SchedulingConstraints = value + return b +} + +// WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithDisruptionMode(value *CompositeDisruptionModeApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + b.DisruptionMode = value + return b +} + +// WithPriorityClassName sets the PriorityClassName 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 PriorityClassName field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPriorityClassName(value string) *CompositePodGroupTemplateApplyConfiguration { + b.PriorityClassName = &value + return b +} + +// WithPriority sets the Priority 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 Priority field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPriority(value int32) *CompositePodGroupTemplateApplyConfiguration { + b.Priority = &value + return b +} + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPreemptionPolicy(value schedulingv1beta1.PreemptionPolicy) *CompositePodGroupTemplateApplyConfiguration { + b.PreemptionPolicy = &value + return b +} + +// WithPodGroupTemplates adds the given value to the PodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the PodGroupTemplates field. +func (b *CompositePodGroupTemplateApplyConfiguration) WithPodGroupTemplates(values ...*PodGroupTemplateApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithPodGroupTemplates") + } + b.PodGroupTemplates = append(b.PodGroupTemplates, *values[i]) + } + return b +} + +// WithCompositePodGroupTemplates adds the given value to the CompositePodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompositePodGroupTemplates field. +func (b *CompositePodGroupTemplateApplyConfiguration) WithCompositePodGroupTemplates(values ...*CompositePodGroupTemplateApplyConfiguration) *CompositePodGroupTemplateApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithCompositePodGroupTemplates") + } + b.CompositePodGroupTemplates = append(b.CompositePodGroupTemplates, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/disruptionmode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/disruptionmode.go new file mode 100644 index 000000000..de1d2c8d3 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/disruptionmode.go @@ -0,0 +1,57 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" +) + +// DisruptionModeApplyConfiguration represents a declarative configuration of the DisruptionMode type for use +// with apply. +// +// DisruptionMode defines how individual entities within a group can be disrupted. +// Exactly one mode can be set. +type DisruptionModeApplyConfiguration struct { + // single specifies that children can be disrupted independently from each other. + Single *schedulingv1beta1.SingleDisruptionMode `json:"single,omitempty"` + // all specifies that all children can only be disrupted together. + All *schedulingv1beta1.AllDisruptionMode `json:"all,omitempty"` +} + +// DisruptionModeApplyConfiguration constructs a declarative configuration of the DisruptionMode type for use with +// apply. +func DisruptionMode() *DisruptionModeApplyConfiguration { + return &DisruptionModeApplyConfiguration{} +} + +// WithSingle sets the Single 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 Single field is set to the value of the last call. +func (b *DisruptionModeApplyConfiguration) WithSingle(value schedulingv1beta1.SingleDisruptionMode) *DisruptionModeApplyConfiguration { + b.Single = &value + return b +} + +// WithAll sets the All 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 All field is set to the value of the last call. +func (b *DisruptionModeApplyConfiguration) WithAll(value schedulingv1beta1.AllDisruptionMode) *DisruptionModeApplyConfiguration { + b.All = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/gangschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/gangschedulingpolicy.go similarity index 71% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/gangschedulingpolicy.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/gangschedulingpolicy.go index 987a89013..0c6d1a4d3 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/gangschedulingpolicy.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/gangschedulingpolicy.go @@ -16,16 +16,24 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1beta1 // GangSchedulingPolicyApplyConfiguration represents a declarative configuration of the GangSchedulingPolicy type for use // with apply. // // GangSchedulingPolicy defines the parameters for gang scheduling. type GangSchedulingPolicyApplyConfiguration struct { - // MinCount is the minimum number of pods that must be schedulable or scheduled + // minCount is the minimum number of pods that must be schedulable or scheduled // at the same time for the scheduler to admit the entire group. - // It must be a positive integer. + // It must be a positive integer. This field is mutable to support workload scaling. + // + // Note that the scheduler operates on an eventually consistent model. Updates + // to minCount may not be immediately reflected in scheduling decisions due to + // propagation delays. If minCount is updated while a scheduling cycle is in + // progress for that group, the new value may not take effect until the next + // cycle. Moreover, minCount is only enforced during scheduling, meaning that + // modifications to this field do not affect already-scheduled pods, applying + // only to those evaluated in future cycles. MinCount *int32 `json:"minCount,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroup.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroup.go new file mode 100644 index 000000000..0bdbc2d4e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroup.go @@ -0,0 +1,296 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// PodGroupApplyConfiguration represents a declarative configuration of the PodGroup type for use +// with apply. +// +// PodGroup represents a runtime instance of pods grouped together. +// PodGroups are created by workload controllers (Job, LWS, JobSet, etc...) from +// Workload.podGroupTemplates. +// PodGroup API enablement is toggled by the GenericWorkload feature gate. +type PodGroupApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec defines the desired state of the PodGroup. + Spec *PodGroupSpecApplyConfiguration `json:"spec,omitempty"` + // status represents the current observed state of the PodGroup. + Status *PodGroupStatusApplyConfiguration `json:"status,omitempty"` +} + +// PodGroup constructs a declarative configuration of the PodGroup type for use with +// apply. +func PodGroup(name, namespace string) *PodGroupApplyConfiguration { + b := &PodGroupApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("PodGroup") + b.WithAPIVersion("scheduling.k8s.io/v1beta1") + return b +} + +// ExtractPodGroupFrom extracts the applied configuration owned by fieldManager from +// podGroup for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// podGroup must be a unmodified PodGroup API object that was retrieved from the Kubernetes API. +// ExtractPodGroupFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractPodGroupFrom(podGroup *schedulingv1beta1.PodGroup, fieldManager string, subresource string) (*PodGroupApplyConfiguration, error) { + b := &PodGroupApplyConfiguration{} + err := managedfields.ExtractInto(podGroup, internal.Parser().Type("io.k8s.api.scheduling.v1beta1.PodGroup"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(podGroup.Name) + b.WithNamespace(podGroup.Namespace) + + b.WithKind("PodGroup") + b.WithAPIVersion("scheduling.k8s.io/v1beta1") + return b, nil +} + +// ExtractPodGroup extracts the applied configuration owned by fieldManager from +// podGroup. If no managedFields are found in podGroup for fieldManager, a +// PodGroupApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// podGroup must be a unmodified PodGroup API object that was retrieved from the Kubernetes API. +// ExtractPodGroup provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractPodGroup(podGroup *schedulingv1beta1.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { + return ExtractPodGroupFrom(podGroup, fieldManager, "") +} + +// ExtractPodGroupStatus extracts the applied configuration owned by fieldManager from +// podGroup for the status subresource. +func ExtractPodGroupStatus(podGroup *schedulingv1beta1.PodGroup, fieldManager string) (*PodGroupApplyConfiguration, error) { + return ExtractPodGroupFrom(podGroup, fieldManager, "status") +} + +func (b PodGroupApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithKind(value string) *PodGroupApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithAPIVersion(value string) *PodGroupApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithName(value string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithGenerateName(value string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithNamespace(value string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithUID(value types.UID) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithResourceVersion(value string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithGeneration(value int64) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *PodGroupApplyConfiguration) WithLabels(entries map[string]string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *PodGroupApplyConfiguration) WithAnnotations(entries map[string]string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *PodGroupApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *PodGroupApplyConfiguration) WithFinalizers(values ...string) *PodGroupApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *PodGroupApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithSpec(value *PodGroupSpecApplyConfiguration) *PodGroupApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *PodGroupApplyConfiguration) WithStatus(value *PodGroupStatusApplyConfiguration) *PodGroupApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *PodGroupApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *PodGroupApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *PodGroupApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *PodGroupApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaim.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaim.go new file mode 100644 index 000000000..6b4de69ff --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaim.go @@ -0,0 +1,89 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// PodGroupResourceClaimApplyConfiguration represents a declarative configuration of the PodGroupResourceClaim type for use +// with apply. +// +// PodGroupResourceClaim references exactly one ResourceClaim, either directly +// or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim +// for the PodGroup. +// +// It adds a name to it that uniquely identifies the ResourceClaim inside the PodGroup. +// Pods that need access to the ResourceClaim define a matching reference in its +// own Spec.ResourceClaims. The Pod's claim must match all fields of the +// PodGroup's claim exactly. +type PodGroupResourceClaimApplyConfiguration struct { + // name uniquely identifies this resource claim inside the PodGroup. + // This must be a DNS_LABEL. + Name *string `json:"name,omitempty"` + // resourceClaimName is the name of a ResourceClaim object in the same + // namespace as this PodGroup. The ResourceClaim will be reserved for the + // PodGroup instead of its individual pods. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + ResourceClaimName *string `json:"resourceClaimName,omitempty"` + // resourceClaimTemplateName is the name of a ResourceClaimTemplate + // object in the same namespace as this PodGroup. + // + // The template will be used to create a new ResourceClaim, which will + // be bound to this PodGroup. When this PodGroup is deleted, the ResourceClaim + // will also be deleted. The PodGroup name and resource name, along with a + // generated component, will be used to form a unique name for the + // ResourceClaim, which will be recorded in podgroup.status.resourceClaimStatuses. + // + // This field is immutable and no changes will be made to the + // corresponding ResourceClaim by the control plane after creating the + // ResourceClaim. + // + // Exactly one of ResourceClaimName and ResourceClaimTemplateName must + // be set. + ResourceClaimTemplateName *string `json:"resourceClaimTemplateName,omitempty"` +} + +// PodGroupResourceClaimApplyConfiguration constructs a declarative configuration of the PodGroupResourceClaim type for use with +// apply. +func PodGroupResourceClaim() *PodGroupResourceClaimApplyConfiguration { + return &PodGroupResourceClaimApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodGroupResourceClaimApplyConfiguration) WithName(value string) *PodGroupResourceClaimApplyConfiguration { + b.Name = &value + return b +} + +// WithResourceClaimName sets the ResourceClaimName 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 ResourceClaimName field is set to the value of the last call. +func (b *PodGroupResourceClaimApplyConfiguration) WithResourceClaimName(value string) *PodGroupResourceClaimApplyConfiguration { + b.ResourceClaimName = &value + return b +} + +// WithResourceClaimTemplateName sets the ResourceClaimTemplateName 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 ResourceClaimTemplateName field is set to the value of the last call. +func (b *PodGroupResourceClaimApplyConfiguration) WithResourceClaimTemplateName(value string) *PodGroupResourceClaimApplyConfiguration { + b.ResourceClaimTemplateName = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaimstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaimstatus.go new file mode 100644 index 000000000..4b41f4e5f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupresourceclaimstatus.go @@ -0,0 +1,59 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// PodGroupResourceClaimStatusApplyConfiguration represents a declarative configuration of the PodGroupResourceClaimStatus type for use +// with apply. +// +// PodGroupResourceClaimStatus is stored in the PodGroupStatus for each +// PodGroupResourceClaim which references a ResourceClaimTemplate. It stores the +// generated name for the corresponding ResourceClaim. +type PodGroupResourceClaimStatusApplyConfiguration struct { + // name uniquely identifies this resource claim inside the PodGroup. This + // must match the name of an entry in podgroup.spec.resourceClaims, which + // implies that the string must be a DNS_LABEL. + Name *string `json:"name,omitempty"` + // resourceClaimName is the name of the ResourceClaim that was generated for + // the PodGroup in the namespace of the PodGroup. If this is unset, then + // generating a ResourceClaim was not necessary. The + // podgroup.spec.resourceClaims entry can be ignored in this case. + ResourceClaimName *string `json:"resourceClaimName,omitempty"` +} + +// PodGroupResourceClaimStatusApplyConfiguration constructs a declarative configuration of the PodGroupResourceClaimStatus type for use with +// apply. +func PodGroupResourceClaimStatus() *PodGroupResourceClaimStatusApplyConfiguration { + return &PodGroupResourceClaimStatusApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *PodGroupResourceClaimStatusApplyConfiguration) WithName(value string) *PodGroupResourceClaimStatusApplyConfiguration { + b.Name = &value + return b +} + +// WithResourceClaimName sets the ResourceClaimName 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 ResourceClaimName field is set to the value of the last call. +func (b *PodGroupResourceClaimStatusApplyConfiguration) WithResourceClaimName(value string) *PodGroupResourceClaimStatusApplyConfiguration { + b.ResourceClaimName = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingconstraints.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingconstraints.go new file mode 100644 index 000000000..11a0ec79b --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingconstraints.go @@ -0,0 +1,48 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// PodGroupSchedulingConstraintsApplyConfiguration represents a declarative configuration of the PodGroupSchedulingConstraints type for use +// with apply. +// +// PodGroupSchedulingConstraints defines scheduling constraints (e.g. topology) for a PodGroup. +type PodGroupSchedulingConstraintsApplyConfiguration struct { + // topology defines the topology constraints for the pod group. + // Currently only a single topology constraint can be specified. This may change in the future. + Topology []TopologyConstraintApplyConfiguration `json:"topology,omitempty"` +} + +// PodGroupSchedulingConstraintsApplyConfiguration constructs a declarative configuration of the PodGroupSchedulingConstraints type for use with +// apply. +func PodGroupSchedulingConstraints() *PodGroupSchedulingConstraintsApplyConfiguration { + return &PodGroupSchedulingConstraintsApplyConfiguration{} +} + +// WithTopology adds the given value to the Topology field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Topology field. +func (b *PodGroupSchedulingConstraintsApplyConfiguration) WithTopology(values ...*TopologyConstraintApplyConfiguration) *PodGroupSchedulingConstraintsApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithTopology") + } + b.Topology = append(b.Topology, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingpolicy.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingpolicy.go new file mode 100644 index 000000000..9cd2d05ab --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupschedulingpolicy.go @@ -0,0 +1,64 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" +) + +// PodGroupSchedulingPolicyApplyConfiguration represents a declarative configuration of the PodGroupSchedulingPolicy type for use +// with apply. +// +// PodGroupSchedulingPolicy defines the scheduling configuration for a PodGroup. +// Exactly one policy must be set. The policy is chosen at creation time by setting either the +// Basic or Gang field. The PodGroup may not change policy after creation. +// Fields within chosen policy may be updated after creation when their individual fields allow it. +type PodGroupSchedulingPolicyApplyConfiguration struct { + // basic specifies that the pods in this group should be scheduled using + // standard Kubernetes scheduling behavior. Setting this field at group creation time + // opts this group to basic scheduling; this field cannot be changed afterward. + Basic *schedulingv1beta1.BasicSchedulingPolicy `json:"basic,omitempty"` + // gang specifies that the pods in this group should be scheduled using + // all-or-nothing semantics. Setting this field at group creation time + // opts this group to gang scheduling; this field cannot be set or unset afterward. + // The minCount field within Gang scheduling policy remains mutable after group creation. + Gang *GangSchedulingPolicyApplyConfiguration `json:"gang,omitempty"` +} + +// PodGroupSchedulingPolicyApplyConfiguration constructs a declarative configuration of the PodGroupSchedulingPolicy type for use with +// apply. +func PodGroupSchedulingPolicy() *PodGroupSchedulingPolicyApplyConfiguration { + return &PodGroupSchedulingPolicyApplyConfiguration{} +} + +// WithBasic sets the Basic 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 Basic field is set to the value of the last call. +func (b *PodGroupSchedulingPolicyApplyConfiguration) WithBasic(value schedulingv1beta1.BasicSchedulingPolicy) *PodGroupSchedulingPolicyApplyConfiguration { + b.Basic = &value + return b +} + +// WithGang sets the Gang 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 Gang field is set to the value of the last call. +func (b *PodGroupSchedulingPolicyApplyConfiguration) WithGang(value *GangSchedulingPolicyApplyConfiguration) *PodGroupSchedulingPolicyApplyConfiguration { + b.Gang = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupspec.go similarity index 65% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupspec.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupspec.go index 76538c622..fb40a2f15 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupspec.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1beta1 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" ) // PodGroupSpecApplyConfiguration represents a declarative configuration of the PodGroupSpec type for use @@ -27,54 +27,61 @@ import ( // // PodGroupSpec defines the desired state of a PodGroup. type PodGroupSpecApplyConfiguration struct { - // PodGroupTemplateRef references an optional PodGroup template within other object - // (e.g. Workload) that was used to create the PodGroup. This field is immutable. - PodGroupTemplateRef *PodGroupTemplateReferenceApplyConfiguration `json:"podGroupTemplateRef,omitempty"` - // SchedulingPolicy defines the scheduling policy for this instance of the PodGroup. - // Controllers are expected to fill this field by copying it from a PodGroupTemplate. + // parentCompositePodGroupName contains the name of the parent composite pod group + // within the same namespace as this pod group. + // If it's nil, then this pod group is a root of a workload's hierarchy. + // This field is used only when the CompositePodGroup feature gate is enabled. + // This field is immutable. + ParentCompositePodGroupName *string `json:"parentCompositePodGroupName,omitempty"` + // workloadRef references an optional PodGroup template within the Workload + // object that was used to create the PodGroup. // This field is immutable. + WorkloadRef *WorkloadReferenceApplyConfiguration `json:"workloadRef,omitempty"` + // schedulingPolicy defines the scheduling policy for this instance of the PodGroup. + // Controllers are expected to fill this field by copying it from a PodGroupTemplate. SchedulingPolicy *PodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroup. // Controllers are expected to fill this field by copying it from a PodGroupTemplate. // This field is immutable. // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. SchedulingConstraints *PodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` - // ResourceClaims defines which ResourceClaims may be shared among Pods in + // resourceClaims defines which ResourceClaims may be shared among Pods in // the group. Pods consume the devices allocated to a PodGroup's claim by // defining a claim in its own Spec.ResourceClaims that matches the // PodGroup's claim exactly. The claim must have the same name and refer to // the same ResourceClaim or ResourceClaimTemplate. // - // This is an alpha-level field and requires that the + // This is a beta-level field and requires that the // DRAWorkloadResourceClaims feature gate is enabled. // // This field is immutable. ResourceClaims []PodGroupResourceClaimApplyConfiguration `json:"resourceClaims,omitempty"` - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. + // disruptionMode defines the mode in which a given PodGroup can be disrupted. // Controllers are expected to fill this field by copying it from a PodGroupTemplate. - // One of Pod, PodGroup. Defaults to Pod if unset. + // One of Single, All. Defaults to Single if unset. // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - DisruptionMode *schedulingv1alpha2.DisruptionMode `json:"disruptionMode,omitempty"` - // PriorityClassName defines the priority that should be considered when scheduling this pod group. + DisruptionMode *DisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName defines the priority that should be considered when scheduling this pod group. // Controllers are expected to fill this field by copying it from a PodGroupTemplate. // Otherwise, it is validated and resolved similarly to the PriorityClassName on PodGroupTemplate // (i.e. if no priority class is specified, admission control can set this to the global default // priority class if it exists. Otherwise, the pod group's priority will be zero). // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. PriorityClassName *string `json:"priorityClassName,omitempty"` - // Priority is the value of priority of this pod group. Various system components + // priority is the value of priority of this pod group. Various system components // use this field to find the priority of the pod group. When Priority Admission // Controller is enabled, it prevents users from setting this field. The admission // controller populates this field from PriorityClassName. // The higher the value, the higher the priority. // This field is immutable. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. + // When Priority Admission Controller is enabled, it populates this field from PriorityClassName, + // and defaults to PreemptLowerPriority if value is unset in PriorityClass. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1beta1.PreemptionPolicy `json:"preemptionPolicy,omitempty"` } // PodGroupSpecApplyConfiguration constructs a declarative configuration of the PodGroupSpec type for use with @@ -83,11 +90,19 @@ func PodGroupSpec() *PodGroupSpecApplyConfiguration { return &PodGroupSpecApplyConfiguration{} } -// WithPodGroupTemplateRef sets the PodGroupTemplateRef field in the declarative configuration to the given value +// WithParentCompositePodGroupName sets the ParentCompositePodGroupName 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 ParentCompositePodGroupName field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithParentCompositePodGroupName(value string) *PodGroupSpecApplyConfiguration { + b.ParentCompositePodGroupName = &value + return b +} + +// WithWorkloadRef sets the WorkloadRef 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 PodGroupTemplateRef field is set to the value of the last call. -func (b *PodGroupSpecApplyConfiguration) WithPodGroupTemplateRef(value *PodGroupTemplateReferenceApplyConfiguration) *PodGroupSpecApplyConfiguration { - b.PodGroupTemplateRef = value +// If called multiple times, the WorkloadRef field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithWorkloadRef(value *WorkloadReferenceApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.WorkloadRef = value return b } @@ -123,8 +138,8 @@ func (b *PodGroupSpecApplyConfiguration) WithResourceClaims(values ...*PodGroupR // WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. -func (b *PodGroupSpecApplyConfiguration) WithDisruptionMode(value schedulingv1alpha2.DisruptionMode) *PodGroupSpecApplyConfiguration { - b.DisruptionMode = &value +func (b *PodGroupSpecApplyConfiguration) WithDisruptionMode(value *DisruptionModeApplyConfiguration) *PodGroupSpecApplyConfiguration { + b.DisruptionMode = value return b } @@ -143,3 +158,11 @@ func (b *PodGroupSpecApplyConfiguration) WithPriority(value int32) *PodGroupSpec b.Priority = &value return b } + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *PodGroupSpecApplyConfiguration) WithPreemptionPolicy(value schedulingv1beta1.PreemptionPolicy) *PodGroupSpecApplyConfiguration { + b.PreemptionPolicy = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupstatus.go similarity index 87% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupstatus.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupstatus.go index c8c4b30da..f52dd7cd2 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgroupstatus.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgroupstatus.go @@ -16,7 +16,7 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1beta1 import ( v1 "k8s.io/client-go/applyconfigurations/meta/v1" @@ -27,14 +27,16 @@ import ( // // PodGroupStatus represents information about the status of a pod group. type PodGroupStatusApplyConfiguration struct { - // Conditions represent the latest observations of the PodGroup's state. + // conditions represent the latest observations of the PodGroup's state. // // Known condition types: - // - "PodGroupScheduled": Indicates whether the scheduling requirement has been satisfied. + // - "PodGroupInitiallyScheduled": Indicates whether the scheduling requirement has been satisfied. + // Once this condition transitions to True, it serves as a terminal state and will never revert to False, + // even if pods are subsequently evicted and group constraints are no longer met. // - "DisruptionTarget": Indicates whether the PodGroup is about to be terminated // due to disruption such as preemption. // - // Known reasons for the PodGroupScheduled condition: + // Known reasons for the PodGroupInitiallyScheduled condition: // - "Unschedulable": The PodGroup cannot be scheduled due to resource constraints, // affinity/anti-affinity rules, or insufficient capacity for the gang. // - "SchedulerError": The PodGroup cannot be scheduled due to some internal error @@ -44,7 +46,7 @@ type PodGroupStatusApplyConfiguration struct { // - "PreemptionByScheduler": The PodGroup was preempted by the scheduler to make room for // higher-priority PodGroups or Pods. Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` - // Status of resource claims. + // resourceClaimStatuses is status of resource claims. ResourceClaimStatuses []PodGroupResourceClaimStatusApplyConfiguration `json:"resourceClaimStatuses,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplate.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgrouptemplate.go similarity index 76% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplate.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgrouptemplate.go index 695caf299..e53e7d41c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/podgrouptemplate.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/podgrouptemplate.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1beta1 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" ) // PodGroupTemplateApplyConfiguration represents a declarative configuration of the PodGroupTemplate type for use @@ -27,45 +27,44 @@ import ( // // PodGroupTemplate represents a template for a set of pods with a scheduling policy. type PodGroupTemplateApplyConfiguration struct { - // Name is a unique identifier for the PodGroupTemplate within the Workload. + // name is a unique identifier for the PodGroupTemplate within the Workload. // It must be a DNS label. This field is immutable. Name *string `json:"name,omitempty"` - // SchedulingPolicy defines the scheduling policy for this PodGroupTemplate. + // schedulingPolicy defines the scheduling policy for this PodGroupTemplate. SchedulingPolicy *PodGroupSchedulingPolicyApplyConfiguration `json:"schedulingPolicy,omitempty"` - // SchedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. + // schedulingConstraints defines optional scheduling constraints (e.g. topology) for this PodGroupTemplate. // This field is only available when the TopologyAwareWorkloadScheduling feature gate is enabled. + // This field is immutable. SchedulingConstraints *PodGroupSchedulingConstraintsApplyConfiguration `json:"schedulingConstraints,omitempty"` - // ResourceClaims defines which ResourceClaims may be shared among Pods in + // resourceClaims defines which ResourceClaims may be shared among Pods in // the group. Pods consume the devices allocated to a PodGroup's claim by // defining a claim in its own Spec.ResourceClaims that matches the // PodGroup's claim exactly. The claim must have the same name and refer to // the same ResourceClaim or ResourceClaimTemplate. // - // This is an alpha-level field and requires that the + // This is a beta-level field and requires that the // DRAWorkloadResourceClaims feature gate is enabled. // // This field is immutable. ResourceClaims []PodGroupResourceClaimApplyConfiguration `json:"resourceClaims,omitempty"` - // DisruptionMode defines the mode in which a given PodGroup can be disrupted. - // One of Pod, PodGroup. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. - DisruptionMode *schedulingv1alpha2.DisruptionMode `json:"disruptionMode,omitempty"` - // PriorityClassName indicates the priority that should be considered when scheduling - // a pod group created from this template. If no priority class is specified, admission - // control can set this to the global default priority class if it exists. Otherwise, - // pod groups created from this template will have the priority set to zero. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. + // disruptionMode defines the mode in which a given PodGroup can be disrupted. + // One of Single, All. + // This field is immutable. + DisruptionMode *DisruptionModeApplyConfiguration `json:"disruptionMode,omitempty"` + // priorityClassName indicates the priority that should be considered when scheduling + // a pod group created from this template. + // This field is immutable. PriorityClassName *string `json:"priorityClassName,omitempty"` - // Priority is the value of priority of pod groups created from this template. Various - // system components use this field to find the priority of the pod group. When - // Priority Admission Controller is enabled, it prevents users from setting this field. - // The admission controller populates this field from PriorityClassName. + // priority is the value of priority of pod groups created from this template. Various + // system components use this field to find the priority of the pod group. // The higher the value, the higher the priority. - // This field is available only when the WorkloadAwarePreemption feature gate - // is enabled. + // This field is immutable. Priority *int32 `json:"priority,omitempty"` + // preemptionPolicy is the Policy for preempting pods/podgroups with lower priority. + // One of Never, PreemptLowerPriority. + // This field is immutable. + // This field is available only when the PodGroupPreemptionPolicy feature gate is enabled. + PreemptionPolicy *schedulingv1beta1.PreemptionPolicy `json:"preemptionPolicy,omitempty"` } // PodGroupTemplateApplyConfiguration constructs a declarative configuration of the PodGroupTemplate type for use with @@ -114,8 +113,8 @@ func (b *PodGroupTemplateApplyConfiguration) WithResourceClaims(values ...*PodGr // WithDisruptionMode sets the DisruptionMode 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 DisruptionMode field is set to the value of the last call. -func (b *PodGroupTemplateApplyConfiguration) WithDisruptionMode(value schedulingv1alpha2.DisruptionMode) *PodGroupTemplateApplyConfiguration { - b.DisruptionMode = &value +func (b *PodGroupTemplateApplyConfiguration) WithDisruptionMode(value *DisruptionModeApplyConfiguration) *PodGroupTemplateApplyConfiguration { + b.DisruptionMode = value return b } @@ -134,3 +133,11 @@ func (b *PodGroupTemplateApplyConfiguration) WithPriority(value int32) *PodGroup b.Priority = &value return b } + +// WithPreemptionPolicy sets the PreemptionPolicy 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 PreemptionPolicy field is set to the value of the last call. +func (b *PodGroupTemplateApplyConfiguration) WithPreemptionPolicy(value schedulingv1beta1.PreemptionPolicy) *PodGroupTemplateApplyConfiguration { + b.PreemptionPolicy = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go index 5fab5624e..3c918fe90 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go @@ -35,8 +35,8 @@ import ( // PriorityClass defines mapping from a priority class name to the priority // integer value. The value can be any valid integer. type PriorityClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // value represents the integer value of this priority class. This is the actual priority that pods diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/topologyconstraint.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/topologyconstraint.go new file mode 100644 index 000000000..52bd8a77b --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/topologyconstraint.go @@ -0,0 +1,45 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// TopologyConstraintApplyConfiguration represents a declarative configuration of the TopologyConstraint type for use +// with apply. +// +// TopologyConstraint defines a topology constraint for a PodGroup. +type TopologyConstraintApplyConfiguration struct { + // key specifies the key of the node label representing the topology domain. + // All pods within the PodGroup must be colocated within the same domain instance. + // Different PodGroups can land on different domain instances even if they derive from the same PodGroupTemplate. + // Examples: "topology.kubernetes.io/rack" + Key *string `json:"key,omitempty"` +} + +// TopologyConstraintApplyConfiguration constructs a declarative configuration of the TopologyConstraint type for use with +// apply. +func TopologyConstraint() *TopologyConstraintApplyConfiguration { + return &TopologyConstraintApplyConfiguration{} +} + +// WithKey sets the Key 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 Key field is set to the value of the last call. +func (b *TopologyConstraintApplyConfiguration) WithKey(value string) *TopologyConstraintApplyConfiguration { + b.Key = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/typedlocalobjectreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/typedlocalobjectreference.go new file mode 100644 index 000000000..4eb57815f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/typedlocalobjectreference.go @@ -0,0 +1,67 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// TypedLocalObjectReferenceApplyConfiguration represents a declarative configuration of the TypedLocalObjectReference type for use +// with apply. +// +// TypedLocalObjectReference allows to reference typed object inside the same namespace. +type TypedLocalObjectReferenceApplyConfiguration struct { + // apiGroup is the group for the resource being referenced. + // If apiGroup is empty, the specified Kind must be in the core API group. + // For any other third-party types, setting apiGroup is required. + // It must be a DNS subdomain. + APIGroup *string `json:"apiGroup,omitempty"` + // kind is the type of resource being referenced. + // It must be a path segment name. + Kind *string `json:"kind,omitempty"` + // name is the name of resource being referenced. + // It must be a path segment name. + Name *string `json:"name,omitempty"` +} + +// TypedLocalObjectReferenceApplyConfiguration constructs a declarative configuration of the TypedLocalObjectReference type for use with +// apply. +func TypedLocalObjectReference() *TypedLocalObjectReferenceApplyConfiguration { + return &TypedLocalObjectReferenceApplyConfiguration{} +} + +// WithAPIGroup sets the APIGroup 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 APIGroup field is set to the value of the last call. +func (b *TypedLocalObjectReferenceApplyConfiguration) WithAPIGroup(value string) *TypedLocalObjectReferenceApplyConfiguration { + b.APIGroup = &value + return b +} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *TypedLocalObjectReferenceApplyConfiguration) WithKind(value string) *TypedLocalObjectReferenceApplyConfiguration { + b.Kind = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *TypedLocalObjectReferenceApplyConfiguration) WithName(value string) *TypedLocalObjectReferenceApplyConfiguration { + b.Name = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workload.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workload.go new file mode 100644 index 000000000..179620a4a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workload.go @@ -0,0 +1,280 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// WorkloadApplyConfiguration represents a declarative configuration of the Workload type for use +// with apply. +// +// Workload allows for expressing scheduling constraints that should be used +// when managing the lifecycle of workloads from the scheduling perspective, +// including scheduling, preemption, eviction and other phases. +// Workload API enablement is toggled by the GenericWorkload feature gate. +type WorkloadApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // spec defines the desired behavior of a Workload. + Spec *WorkloadSpecApplyConfiguration `json:"spec,omitempty"` +} + +// Workload constructs a declarative configuration of the Workload type for use with +// apply. +func Workload(name, namespace string) *WorkloadApplyConfiguration { + b := &WorkloadApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("Workload") + b.WithAPIVersion("scheduling.k8s.io/v1beta1") + return b +} + +// ExtractWorkloadFrom extracts the applied configuration owned by fieldManager from +// workload for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// workload must be a unmodified Workload API object that was retrieved from the Kubernetes API. +// ExtractWorkloadFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractWorkloadFrom(workload *schedulingv1beta1.Workload, fieldManager string, subresource string) (*WorkloadApplyConfiguration, error) { + b := &WorkloadApplyConfiguration{} + err := managedfields.ExtractInto(workload, internal.Parser().Type("io.k8s.api.scheduling.v1beta1.Workload"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(workload.Name) + b.WithNamespace(workload.Namespace) + + b.WithKind("Workload") + b.WithAPIVersion("scheduling.k8s.io/v1beta1") + return b, nil +} + +// ExtractWorkload extracts the applied configuration owned by fieldManager from +// workload. If no managedFields are found in workload for fieldManager, a +// WorkloadApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// workload must be a unmodified Workload API object that was retrieved from the Kubernetes API. +// ExtractWorkload provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractWorkload(workload *schedulingv1beta1.Workload, fieldManager string) (*WorkloadApplyConfiguration, error) { + return ExtractWorkloadFrom(workload, fieldManager, "") +} + +func (b WorkloadApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithKind(value string) *WorkloadApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithAPIVersion(value string) *WorkloadApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithName(value string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithGenerateName(value string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithNamespace(value string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithUID(value types.UID) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithResourceVersion(value string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithGeneration(value int64) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithCreationTimestamp(value metav1.Time) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *WorkloadApplyConfiguration) WithLabels(entries map[string]string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *WorkloadApplyConfiguration) WithAnnotations(entries map[string]string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *WorkloadApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *WorkloadApplyConfiguration) WithFinalizers(values ...string) *WorkloadApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *WorkloadApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *WorkloadApplyConfiguration) WithSpec(value *WorkloadSpecApplyConfiguration) *WorkloadApplyConfiguration { + b.Spec = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *WorkloadApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *WorkloadApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *WorkloadApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *WorkloadApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadreference.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadreference.go new file mode 100644 index 000000000..ee6a1aee8 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadreference.go @@ -0,0 +1,58 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// WorkloadReferenceApplyConfiguration represents a declarative configuration of the WorkloadReference type for use +// with apply. +// +// WorkloadReference references the Workload object together with the template +// that was used to create a particular PodGroup. +type WorkloadReferenceApplyConfiguration struct { + // workloadName is the name of the Workload object that contains a template + // that was used when creating a pod group. It must + // be a DNS name. + // This field is required. + WorkloadName *string `json:"workloadName,omitempty"` + // templateName is the name of a template within the Workload object that + // was used to create a pod group. It must be a DNS label. + // This field is required. + TemplateName *string `json:"templateName,omitempty"` +} + +// WorkloadReferenceApplyConfiguration constructs a declarative configuration of the WorkloadReference type for use with +// apply. +func WorkloadReference() *WorkloadReferenceApplyConfiguration { + return &WorkloadReferenceApplyConfiguration{} +} + +// WithWorkloadName sets the WorkloadName 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 WorkloadName field is set to the value of the last call. +func (b *WorkloadReferenceApplyConfiguration) WithWorkloadName(value string) *WorkloadReferenceApplyConfiguration { + b.WorkloadName = &value + return b +} + +// WithTemplateName sets the TemplateName 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 TemplateName field is set to the value of the last call. +func (b *WorkloadReferenceApplyConfiguration) WithTemplateName(value string) *WorkloadReferenceApplyConfiguration { + b.TemplateName = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadspec.go similarity index 63% rename from constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadspec.go rename to constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadspec.go index 33eb8a5c0..36a4e37fc 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1alpha2/workloadspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/workloadspec.go @@ -16,21 +16,29 @@ limitations under the License. // Code generated by applyconfiguration-gen. DO NOT EDIT. -package v1alpha2 +package v1beta1 // WorkloadSpecApplyConfiguration represents a declarative configuration of the WorkloadSpec type for use // with apply. // // WorkloadSpec defines the desired state of a Workload. type WorkloadSpecApplyConfiguration struct { - // ControllerRef is an optional reference to the controlling object, such as a + // controllerRef is an optional reference to the controlling object, such as a // Deployment or Job. This field is intended for use by tools like CLIs // to provide a link back to the original workload definition. // This field is immutable. ControllerRef *TypedLocalObjectReferenceApplyConfiguration `json:"controllerRef,omitempty"` - // PodGroupTemplates is the list of templates that make up the Workload. - // The maximum number of templates is 8. This field is immutable. + // podGroupTemplates is the list of templates that make up the Workload. + // The maximum number of templates is 8. Templates cannot be added or removed after the workload is created. + // Existing templates may still be updated where their individual fields allow it. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. PodGroupTemplates []PodGroupTemplateApplyConfiguration `json:"podGroupTemplates,omitempty"` + // compositePodGroupTemplates is the list of CompositePodGroup templates that make up the Workload. + // The maximum number of templates is 8. This field is immutable. + // Exactly one of CompositePodGroupTemplates and PodGroupTemplates must be set. + // + // This field is used only when the CompositePodGroup feature gate is enabled. + CompositePodGroupTemplates []CompositePodGroupTemplateApplyConfiguration `json:"compositePodGroupTemplates,omitempty"` } // WorkloadSpecApplyConfiguration constructs a declarative configuration of the WorkloadSpec type for use with @@ -59,3 +67,16 @@ func (b *WorkloadSpecApplyConfiguration) WithPodGroupTemplates(values ...*PodGro } return b } + +// WithCompositePodGroupTemplates adds the given value to the CompositePodGroupTemplates field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the CompositePodGroupTemplates field. +func (b *WorkloadSpecApplyConfiguration) WithCompositePodGroupTemplates(values ...*CompositePodGroupTemplateApplyConfiguration) *WorkloadSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithCompositePodGroupTemplates") + } + b.CompositePodGroupTemplates = append(b.CompositePodGroupTemplates, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go index 39ce1eb04..a4a1bb11c 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go @@ -36,8 +36,8 @@ import ( // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. type CSIDriverApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go index 4a715c141..839b71416 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go @@ -178,7 +178,7 @@ type CSIDriverSpecApplyConfiguration struct { // // Default behavior if unset is to pass tokens in the VolumeContext field. ServiceAccountTokenInSecrets *bool `json:"serviceAccountTokenInSecrets,omitempty"` - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -193,7 +193,7 @@ type CSIDriverSpecApplyConfiguration struct { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". PreventPodSchedulingIfMissing *bool `json:"preventPodSchedulingIfMissing,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go index e0b7f349e..9a43dc622 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go @@ -40,12 +40,14 @@ import ( // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. type CSINodeApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the specification of CSINode Spec *CSINodeSpecApplyConfiguration `json:"spec,omitempty"` + // status contains health and status information for the node's storage. + Status *CSINodeStatusApplyConfiguration `json:"status,omitempty"` } // CSINode constructs a declarative configuration of the CSINode type for use with @@ -92,6 +94,12 @@ func ExtractCSINode(cSINode *storagev1.CSINode, fieldManager string) (*CSINodeAp return ExtractCSINodeFrom(cSINode, fieldManager, "") } +// ExtractCSINodeStatus extracts the applied configuration owned by fieldManager from +// cSINode for the status subresource. +func ExtractCSINodeStatus(cSINode *storagev1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) { + return ExtractCSINodeFrom(cSINode, fieldManager, "status") +} + func (b CSINodeApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value @@ -260,6 +268,14 @@ func (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguratio return b } +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *CSINodeApplyConfiguration) WithStatus(value *CSINodeStatusApplyConfiguration) *CSINodeApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *CSINodeApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinodestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinodestatus.go new file mode 100644 index 000000000..35294a3c2 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csinodestatus.go @@ -0,0 +1,47 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// CSINodeStatusApplyConfiguration represents a declarative configuration of the CSINodeStatus type for use +// with apply. +// +// CSINodeStatus contains health and status information for storage on a node. +type CSINodeStatusApplyConfiguration struct { + // storageHealth contains backend health reports for CSI drivers registered on the node. + StorageHealth []StorageHealthApplyConfiguration `json:"storageHealth,omitempty"` +} + +// CSINodeStatusApplyConfiguration constructs a declarative configuration of the CSINodeStatus type for use with +// apply. +func CSINodeStatus() *CSINodeStatusApplyConfiguration { + return &CSINodeStatusApplyConfiguration{} +} + +// WithStorageHealth adds the given value to the StorageHealth field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the StorageHealth field. +func (b *CSINodeStatusApplyConfiguration) WithStorageHealth(values ...*StorageHealthApplyConfiguration) *CSINodeStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithStorageHealth") + } + b.StorageHealth = append(b.StorageHealth, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go index 8682c4349..9ae931534 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go @@ -56,8 +56,8 @@ import ( // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacityApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // The name has no particular meaning. It must be a DNS subdomain (dots allowed, 253 characters). // To ensure that there are no conflicts with other CSI drivers on the cluster, // the recommendation is to use csisc-, a generated name, or a reverse-domain name diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go index 766b795c4..f4fdf32d0 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go @@ -38,8 +38,8 @@ import ( // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. type StorageClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // provisioner indicates the type of the provisioner. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealth.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealth.go new file mode 100644 index 000000000..9d232b2e6 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealth.go @@ -0,0 +1,58 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// StorageHealthApplyConfiguration represents a declarative configuration of the StorageHealth type for use +// with apply. +// +// StorageHealth contains storage backend health reported by a CSI driver on a node. +type StorageHealthApplyConfiguration struct { + // name is the CSI driver name, matching CSINodeDriver.name. + Name *string `json:"name,omitempty"` + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + HealthConditions []StorageHealthConditionApplyConfiguration `json:"healthConditions,omitempty"` +} + +// StorageHealthApplyConfiguration constructs a declarative configuration of the StorageHealth type for use with +// apply. +func StorageHealth() *StorageHealthApplyConfiguration { + return &StorageHealthApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *StorageHealthApplyConfiguration) WithName(value string) *StorageHealthApplyConfiguration { + b.Name = &value + return b +} + +// WithHealthConditions adds the given value to the HealthConditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the HealthConditions field. +func (b *StorageHealthApplyConfiguration) WithHealthConditions(values ...*StorageHealthConditionApplyConfiguration) *StorageHealthApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithHealthConditions") + } + b.HealthConditions = append(b.HealthConditions, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealthcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealthcondition.go new file mode 100644 index 000000000..518d00821 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/storagehealthcondition.go @@ -0,0 +1,102 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// StorageHealthConditionApplyConfiguration represents a declarative configuration of the StorageHealthCondition type for use +// with apply. +// +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +type StorageHealthConditionApplyConfiguration struct { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + Status *storagev1.StorageHealthStatusType `json:"status,omitempty"` + // reason is a brief CamelCase machine-parseable reason. + // Maximum permitted length of a reason is 256 characters. + Reason *string `json:"reason,omitempty"` + // message is a human-readable description. + // Maximum permitted length of a message is 1024 characters. + Message *string `json:"message,omitempty"` + // accessMode is the access mode affected. Nil means all access modes are affected. + AccessMode *corev1.PersistentVolumeAccessMode `json:"accessMode,omitempty"` + // volumeMode is the volume mode affected. Nil means both are affected. + VolumeMode *corev1.PersistentVolumeMode `json:"volumeMode,omitempty"` + // lastTransitionTime is when this condition first appeared at its current state. + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` +} + +// StorageHealthConditionApplyConfiguration constructs a declarative configuration of the StorageHealthCondition type for use with +// apply. +func StorageHealthCondition() *StorageHealthConditionApplyConfiguration { + return &StorageHealthConditionApplyConfiguration{} +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithStatus(value storagev1.StorageHealthStatusType) *StorageHealthConditionApplyConfiguration { + b.Status = &value + return b +} + +// WithReason sets the Reason 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 Reason field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithReason(value string) *StorageHealthConditionApplyConfiguration { + b.Reason = &value + return b +} + +// WithMessage sets the Message 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 Message field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithMessage(value string) *StorageHealthConditionApplyConfiguration { + b.Message = &value + return b +} + +// WithAccessMode sets the AccessMode 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 AccessMode field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithAccessMode(value corev1.PersistentVolumeAccessMode) *StorageHealthConditionApplyConfiguration { + b.AccessMode = &value + return b +} + +// WithVolumeMode sets the VolumeMode 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 VolumeMode field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithVolumeMode(value corev1.PersistentVolumeMode) *StorageHealthConditionApplyConfiguration { + b.VolumeMode = &value + return b +} + +// WithLastTransitionTime sets the LastTransitionTime 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 LastTransitionTime field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StorageHealthConditionApplyConfiguration { + b.LastTransitionTime = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go index 624042180..2f958f3cd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go @@ -35,8 +35,8 @@ import ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachmentApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec represents specification of the desired attach/detach volume behavior. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattributesclass.go index aee276c3d..9e2e8db13 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1/volumeattributesclass.go @@ -34,11 +34,11 @@ import ( // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClassApplyConfiguration struct { - metav1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + metav1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName *string `json:"driverName,omitempty"` // parameters hold volume attributes defined by the CSI driver. These values diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go index e52c1adf4..9885263cd 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go @@ -56,8 +56,8 @@ import ( // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacityApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. The name has no particular meaning. It must be + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go index bd214650b..839abce4b 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go @@ -35,8 +35,8 @@ import ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachmentApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec represents specification of the desired attach/detach volume behavior. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattributesclass.go index 62ff6dcbf..c384c1722 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattributesclass.go @@ -34,11 +34,11 @@ import ( // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName *string `json:"driverName,omitempty"` // parameters hold volume attributes defined by the CSI driver. These values diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go index bace6d42b..4a5077699 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go @@ -39,8 +39,8 @@ import ( // Kubelet uses this object to determine whether pod information needs to be passed on mount. // CSIDriver objects are non-namespaced. type CSIDriverApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // metadata.Name indicates the name of the CSI driver that this object // refers to; it MUST be the same name returned by the CSI GetPluginName() // call for that driver. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go index cec76d9fd..624fad712 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go @@ -178,7 +178,7 @@ type CSIDriverSpecApplyConfiguration struct { // // Default behavior if unset is to pass tokens in the VolumeContext field. ServiceAccountTokenInSecrets *bool `json:"serviceAccountTokenInSecrets,omitempty"` - // PreventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod + // preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod // scheduling if the CSI driver on the node is missing. // // Enabling this option will prevent the scheduler (or any other @@ -193,7 +193,7 @@ type CSIDriverSpecApplyConfiguration struct { // newly created node may be rejected by the scheduler because of missing CSI driver // information from the node. // - // This is an alpha feature and requires the VolumeLimitScaling feature gate to be enabled. + // This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. // Default is "false". PreventPodSchedulingIfMissing *bool `json:"preventPodSchedulingIfMissing,omitempty"` } diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go index 7f6907275..f1496eb19 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go @@ -42,11 +42,14 @@ import ( // enough that it doesn't create this object. // CSINode has an OwnerReference that points to the corresponding node object. type CSINodeApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // metadata.name must be the Kubernetes node name. *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec is the specification of CSINode Spec *CSINodeSpecApplyConfiguration `json:"spec,omitempty"` + // status contains health and status information for the node's storage. + Status *CSINodeStatusApplyConfiguration `json:"status,omitempty"` } // CSINode constructs a declarative configuration of the CSINode type for use with @@ -93,6 +96,12 @@ func ExtractCSINode(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSIN return ExtractCSINodeFrom(cSINode, fieldManager, "") } +// ExtractCSINodeStatus extracts the applied configuration owned by fieldManager from +// cSINode for the status subresource. +func ExtractCSINodeStatus(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) { + return ExtractCSINodeFrom(cSINode, fieldManager, "status") +} + func (b CSINodeApplyConfiguration) IsApplyConfiguration() {} // WithKind sets the Kind field in the declarative configuration to the given value @@ -261,6 +270,14 @@ func (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguratio return b } +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *CSINodeApplyConfiguration) WithStatus(value *CSINodeStatusApplyConfiguration) *CSINodeApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *CSINodeApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodestatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodestatus.go new file mode 100644 index 000000000..85ab83107 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodestatus.go @@ -0,0 +1,47 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// CSINodeStatusApplyConfiguration represents a declarative configuration of the CSINodeStatus type for use +// with apply. +// +// CSINodeStatus contains health and status information for storage on a node. +type CSINodeStatusApplyConfiguration struct { + // storageHealth contains backend health reports for CSI drivers registered on the node. + StorageHealth []StorageHealthApplyConfiguration `json:"storageHealth,omitempty"` +} + +// CSINodeStatusApplyConfiguration constructs a declarative configuration of the CSINodeStatus type for use with +// apply. +func CSINodeStatus() *CSINodeStatusApplyConfiguration { + return &CSINodeStatusApplyConfiguration{} +} + +// WithStorageHealth adds the given value to the StorageHealth field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the StorageHealth field. +func (b *CSINodeStatusApplyConfiguration) WithStorageHealth(values ...*StorageHealthApplyConfiguration) *CSINodeStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithStorageHealth") + } + b.StorageHealth = append(b.StorageHealth, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go index e27221e82..34f1830e9 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go @@ -56,8 +56,8 @@ import ( // the scheduler assumes that capacity is insufficient and tries some other // node. type CSIStorageCapacityApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. The name has no particular meaning. It must be + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. The name has no particular meaning. It must be // be a DNS subdomain (dots allowed, 253 characters). To ensure that // there are no conflicts with other CSI drivers on the cluster, the recommendation // is to use csisc-, a generated name, or a reverse-domain name which ends diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go index 49bf87ac5..d45801926 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go @@ -38,8 +38,8 @@ import ( // StorageClasses are non-namespaced; the name of the storage class // according to etcd is in ObjectMeta.Name. type StorageClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // provisioner indicates the type of the provisioner. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealth.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealth.go new file mode 100644 index 000000000..ccd30766e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealth.go @@ -0,0 +1,58 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +// StorageHealthApplyConfiguration represents a declarative configuration of the StorageHealth type for use +// with apply. +// +// StorageHealth contains storage backend health reported by a CSI driver on a node. +type StorageHealthApplyConfiguration struct { + // name is the CSI driver name, matching CSINodeDriver.name. + Name *string `json:"name,omitempty"` + // healthConditions are the adverse storage backend conditions reported by the CSI driver. + // At most 16 conditions may be reported. + HealthConditions []StorageHealthConditionApplyConfiguration `json:"healthConditions,omitempty"` +} + +// StorageHealthApplyConfiguration constructs a declarative configuration of the StorageHealth type for use with +// apply. +func StorageHealth() *StorageHealthApplyConfiguration { + return &StorageHealthApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *StorageHealthApplyConfiguration) WithName(value string) *StorageHealthApplyConfiguration { + b.Name = &value + return b +} + +// WithHealthConditions adds the given value to the HealthConditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the HealthConditions field. +func (b *StorageHealthApplyConfiguration) WithHealthConditions(values ...*StorageHealthConditionApplyConfiguration) *StorageHealthApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithHealthConditions") + } + b.HealthConditions = append(b.HealthConditions, *values[i]) + } + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealthcondition.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealthcondition.go new file mode 100644 index 000000000..6fd4e6bfa --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/storagehealthcondition.go @@ -0,0 +1,102 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1beta1 + +import ( + v1 "k8s.io/api/core/v1" + storagev1beta1 "k8s.io/api/storage/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// StorageHealthConditionApplyConfiguration represents a declarative configuration of the StorageHealthCondition type for use +// with apply. +// +// StorageHealthCondition represents an adverse health condition reported +// by a CSI driver for its storage backend on a node. +type StorageHealthConditionApplyConfiguration struct { + // status is the health status category. + // One of "StorageUnreachable", "StorageDegraded". + Status *storagev1beta1.StorageHealthStatusType `json:"status,omitempty"` + // reason is a brief CamelCase machine-parseable reason. + // Maximum permitted length of a reason is 256 characters. + Reason *string `json:"reason,omitempty"` + // message is a human-readable description. + // Maximum permitted length of a message is 1024 characters. + Message *string `json:"message,omitempty"` + // accessMode is the access mode affected. Nil means all access modes are affected. + AccessMode *v1.PersistentVolumeAccessMode `json:"accessMode,omitempty"` + // volumeMode is the volume mode affected. Nil means both are affected. + VolumeMode *v1.PersistentVolumeMode `json:"volumeMode,omitempty"` + // lastTransitionTime is when this condition first appeared at its current state. + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` +} + +// StorageHealthConditionApplyConfiguration constructs a declarative configuration of the StorageHealthCondition type for use with +// apply. +func StorageHealthCondition() *StorageHealthConditionApplyConfiguration { + return &StorageHealthConditionApplyConfiguration{} +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithStatus(value storagev1beta1.StorageHealthStatusType) *StorageHealthConditionApplyConfiguration { + b.Status = &value + return b +} + +// WithReason sets the Reason 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 Reason field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithReason(value string) *StorageHealthConditionApplyConfiguration { + b.Reason = &value + return b +} + +// WithMessage sets the Message 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 Message field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithMessage(value string) *StorageHealthConditionApplyConfiguration { + b.Message = &value + return b +} + +// WithAccessMode sets the AccessMode 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 AccessMode field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithAccessMode(value v1.PersistentVolumeAccessMode) *StorageHealthConditionApplyConfiguration { + b.AccessMode = &value + return b +} + +// WithVolumeMode sets the VolumeMode 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 VolumeMode field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithVolumeMode(value v1.PersistentVolumeMode) *StorageHealthConditionApplyConfiguration { + b.VolumeMode = &value + return b +} + +// WithLastTransitionTime sets the LastTransitionTime 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 LastTransitionTime field is set to the value of the last call. +func (b *StorageHealthConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StorageHealthConditionApplyConfiguration { + b.LastTransitionTime = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go index da938bd30..25ffcd140 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go @@ -35,8 +35,8 @@ import ( // // VolumeAttachment objects are non-namespaced. type VolumeAttachmentApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` // spec represents specification of the desired attach/detach volume behavior. diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattributesclass.go index 7d04a86c8..1eab6c2ca 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattributesclass.go @@ -34,11 +34,11 @@ import ( // defined by the CSI driver. The class can be specified during dynamic provisioning // of PersistentVolumeClaims, and changed in the PersistentVolumeClaim spec after provisioning. type VolumeAttributesClassApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` - // Standard object's metadata. + v1.TypeMetaApplyConfiguration `json:""` + // metadata is the standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - // Name of the CSI driver + // driverName is the name of the CSI driver // This field is immutable. DriverName *string `json:"driverName,omitempty"` // parameters hold volume attributes defined by the CSI driver. These values diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigration.go new file mode 100644 index 000000000..b42000e71 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigration.go @@ -0,0 +1,292 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + storagemigrationv1 "k8s.io/api/storagemigration/v1" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + internal "k8s.io/client-go/applyconfigurations/internal" + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// StorageVersionMigrationApplyConfiguration represents a declarative configuration of the StorageVersionMigration type for use +// with apply. +// +// StorageVersionMigration represents a migration of stored data to the latest +// storage version. +type StorageVersionMigrationApplyConfiguration struct { + metav1.TypeMetaApplyConfiguration `json:""` + // Standard object metadata. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata + *metav1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + // Specification of the migration. + Spec *StorageVersionMigrationSpecApplyConfiguration `json:"spec,omitempty"` + // Status of the migration. + Status *StorageVersionMigrationStatusApplyConfiguration `json:"status,omitempty"` +} + +// StorageVersionMigration constructs a declarative configuration of the StorageVersionMigration type for use with +// apply. +func StorageVersionMigration(name string) *StorageVersionMigrationApplyConfiguration { + b := &StorageVersionMigrationApplyConfiguration{} + b.WithName(name) + b.WithKind("StorageVersionMigration") + b.WithAPIVersion("storagemigration.k8s.io/v1") + return b +} + +// ExtractStorageVersionMigrationFrom extracts the applied configuration owned by fieldManager from +// storageVersionMigration for the specified subresource. Pass an empty string for subresource to extract +// the main resource. Common subresources include "status", "scale", etc. +// storageVersionMigration must be a unmodified StorageVersionMigration API object that was retrieved from the Kubernetes API. +// ExtractStorageVersionMigrationFrom provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractStorageVersionMigrationFrom(storageVersionMigration *storagemigrationv1.StorageVersionMigration, fieldManager string, subresource string) (*StorageVersionMigrationApplyConfiguration, error) { + b := &StorageVersionMigrationApplyConfiguration{} + err := managedfields.ExtractInto(storageVersionMigration, internal.Parser().Type("io.k8s.api.storagemigration.v1.StorageVersionMigration"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(storageVersionMigration.Name) + + b.WithKind("StorageVersionMigration") + b.WithAPIVersion("storagemigration.k8s.io/v1") + return b, nil +} + +// ExtractStorageVersionMigration extracts the applied configuration owned by fieldManager from +// storageVersionMigration. If no managedFields are found in storageVersionMigration for fieldManager, a +// StorageVersionMigrationApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// storageVersionMigration must be a unmodified StorageVersionMigration API object that was retrieved from the Kubernetes API. +// ExtractStorageVersionMigration provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +func ExtractStorageVersionMigration(storageVersionMigration *storagemigrationv1.StorageVersionMigration, fieldManager string) (*StorageVersionMigrationApplyConfiguration, error) { + return ExtractStorageVersionMigrationFrom(storageVersionMigration, fieldManager, "") +} + +// ExtractStorageVersionMigrationStatus extracts the applied configuration owned by fieldManager from +// storageVersionMigration for the status subresource. +func ExtractStorageVersionMigrationStatus(storageVersionMigration *storagemigrationv1.StorageVersionMigration, fieldManager string) (*StorageVersionMigrationApplyConfiguration, error) { + return ExtractStorageVersionMigrationFrom(storageVersionMigration, fieldManager, "status") +} + +func (b StorageVersionMigrationApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithKind(value string) *StorageVersionMigrationApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithAPIVersion(value string) *StorageVersionMigrationApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithName(value string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithGenerateName(value string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithNamespace(value string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithUID(value types.UID) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithResourceVersion(value string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithGeneration(value int64) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithCreationTimestamp(value apismetav1.Time) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithDeletionTimestamp(value apismetav1.Time) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *StorageVersionMigrationApplyConfiguration) WithLabels(entries map[string]string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *StorageVersionMigrationApplyConfiguration) WithAnnotations(entries map[string]string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *StorageVersionMigrationApplyConfiguration) WithOwnerReferences(values ...*metav1.OwnerReferenceApplyConfiguration) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *StorageVersionMigrationApplyConfiguration) WithFinalizers(values ...string) *StorageVersionMigrationApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *StorageVersionMigrationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &metav1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithSpec(value *StorageVersionMigrationSpecApplyConfiguration) *StorageVersionMigrationApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status 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 Status field is set to the value of the last call. +func (b *StorageVersionMigrationApplyConfiguration) WithStatus(value *StorageVersionMigrationStatusApplyConfiguration) *StorageVersionMigrationApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *StorageVersionMigrationApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *StorageVersionMigrationApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *StorageVersionMigrationApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *StorageVersionMigrationApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationspec.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationspec.go new file mode 100644 index 000000000..2c8603560 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationspec.go @@ -0,0 +1,48 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// StorageVersionMigrationSpecApplyConfiguration represents a declarative configuration of the StorageVersionMigrationSpec type for use +// with apply. +// +// Spec of the storage version migration. +type StorageVersionMigrationSpecApplyConfiguration struct { + // The resource that is being migrated. The migrator sends requests to + // the endpoint serving the resource. + // Immutable. + Resource *metav1.GroupResourceApplyConfiguration `json:"resource,omitempty"` +} + +// StorageVersionMigrationSpecApplyConfiguration constructs a declarative configuration of the StorageVersionMigrationSpec type for use with +// apply. +func StorageVersionMigrationSpec() *StorageVersionMigrationSpecApplyConfiguration { + return &StorageVersionMigrationSpecApplyConfiguration{} +} + +// WithResource sets the Resource 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 Resource field is set to the value of the last call. +func (b *StorageVersionMigrationSpecApplyConfiguration) WithResource(value *metav1.GroupResourceApplyConfiguration) *StorageVersionMigrationSpecApplyConfiguration { + b.Resource = value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationstatus.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationstatus.go new file mode 100644 index 000000000..14bc86973 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1/storageversionmigrationstatus.go @@ -0,0 +1,63 @@ +/* +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 applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + metav1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// StorageVersionMigrationStatusApplyConfiguration represents a declarative configuration of the StorageVersionMigrationStatus type for use +// with apply. +// +// Status of the storage version migration. +type StorageVersionMigrationStatusApplyConfiguration struct { + // The latest available observations of the migration's current state. + Conditions []metav1.ConditionApplyConfiguration `json:"conditions,omitempty"` + // ResourceVersion to compare with the GC cache for performing the migration. + // This is the current resource version of given group, version and resource when + // kube-controller-manager first observes this StorageVersionMigration resource. + ResourceVersion *string `json:"resourceVersion,omitempty"` +} + +// StorageVersionMigrationStatusApplyConfiguration constructs a declarative configuration of the StorageVersionMigrationStatus type for use with +// apply. +func StorageVersionMigrationStatus() *StorageVersionMigrationStatusApplyConfiguration { + return &StorageVersionMigrationStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *StorageVersionMigrationStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *StorageVersionMigrationStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *StorageVersionMigrationStatusApplyConfiguration) WithResourceVersion(value string) *StorageVersionMigrationStatusApplyConfiguration { + b.ResourceVersion = &value + return b +} diff --git a/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1beta1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1beta1/storageversionmigration.go index e52fa5d81..f82428997 100644 --- a/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1beta1/storageversionmigration.go +++ b/constraint/vendor/k8s.io/client-go/applyconfigurations/storagemigration/v1beta1/storageversionmigration.go @@ -33,7 +33,7 @@ import ( // StorageVersionMigration represents a migration of stored data to the latest // storage version. type StorageVersionMigrationApplyConfiguration struct { - v1.TypeMetaApplyConfiguration `json:",inline"` + v1.TypeMetaApplyConfiguration `json:""` // Standard object metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/discovery/aggregated_discovery.go b/constraint/vendor/k8s.io/client-go/discovery/aggregated_discovery.go index 82d46b489..2111b2645 100644 --- a/constraint/vendor/k8s.io/client-go/discovery/aggregated_discovery.go +++ b/constraint/vendor/k8s.io/client-go/discovery/aggregated_discovery.go @@ -20,7 +20,6 @@ import ( "fmt" apidiscovery "k8s.io/api/apidiscovery/v2" - apidiscoveryv2beta1 "k8s.io/api/apidiscovery/v2beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) @@ -155,124 +154,3 @@ func convertAPISubresource(parent metav1.APIResource, in apidiscovery.APISubreso result.Verbs = in.Verbs return result, nil } - -// Please note the functions below will be removed in v1.35. They facilitate conversion -// between the deprecated type apidiscoveryv2beta1.APIGroupDiscoveryList. - -// SplitGroupsAndResourcesV2Beta1 transforms "aggregated" discovery top-level structure into -// the previous "unaggregated" discovery groups and resources. -// Deprecated: Please use SplitGroupsAndResources -func SplitGroupsAndResourcesV2Beta1(aggregatedGroups apidiscoveryv2beta1.APIGroupDiscoveryList) ( - *metav1.APIGroupList, - map[schema.GroupVersion]*metav1.APIResourceList, - map[schema.GroupVersion]error) { - // Aggregated group list will contain the entirety of discovery, including - // groups, versions, and resources. GroupVersions marked "stale" are failed. - groups := []*metav1.APIGroup{} - failedGVs := map[schema.GroupVersion]error{} - resourcesByGV := map[schema.GroupVersion]*metav1.APIResourceList{} - for _, aggGroup := range aggregatedGroups.Items { - group, resources, failed := convertAPIGroupv2beta1(aggGroup) - groups = append(groups, group) - for gv, resourceList := range resources { - resourcesByGV[gv] = resourceList - } - for gv, err := range failed { - failedGVs[gv] = err - } - } - // Transform slice of groups to group list before returning. - groupList := &metav1.APIGroupList{} - groupList.Groups = make([]metav1.APIGroup, 0, len(groups)) - for _, group := range groups { - groupList.Groups = append(groupList.Groups, *group) - } - return groupList, resourcesByGV, failedGVs -} - -// convertAPIGroupv2beta1 tranforms an "aggregated" APIGroupDiscovery to an "legacy" APIGroup, -// also returning the map of APIResourceList for resources within GroupVersions. -func convertAPIGroupv2beta1(g apidiscoveryv2beta1.APIGroupDiscovery) ( - *metav1.APIGroup, - map[schema.GroupVersion]*metav1.APIResourceList, - map[schema.GroupVersion]error) { - // Iterate through versions to convert to group and resources. - group := &metav1.APIGroup{} - gvResources := map[schema.GroupVersion]*metav1.APIResourceList{} - failedGVs := map[schema.GroupVersion]error{} - group.Name = g.ObjectMeta.Name - for _, v := range g.Versions { - gv := schema.GroupVersion{Group: g.Name, Version: v.Version} - if v.Freshness == apidiscoveryv2beta1.DiscoveryFreshnessStale { - failedGVs[gv] = StaleGroupVersionError{gv: gv} - continue - } - version := metav1.GroupVersionForDiscovery{} - version.GroupVersion = gv.String() - version.Version = v.Version - group.Versions = append(group.Versions, version) - // PreferredVersion is first non-stale Version - if group.PreferredVersion == (metav1.GroupVersionForDiscovery{}) { - group.PreferredVersion = version - } - resourceList := &metav1.APIResourceList{} - resourceList.GroupVersion = gv.String() - for _, r := range v.Resources { - resource, err := convertAPIResourcev2beta1(r) - if err == nil { - resourceList.APIResources = append(resourceList.APIResources, resource) - } - // Subresources field in new format get transformed into full APIResources. - // It is possible a partial result with an error was returned to be used - // as the parent resource for the subresource. - for _, subresource := range r.Subresources { - sr, err := convertAPISubresourcev2beta1(resource, subresource) - if err == nil { - resourceList.APIResources = append(resourceList.APIResources, sr) - } - } - } - gvResources[gv] = resourceList - } - return group, gvResources, failedGVs -} - -// convertAPIResource tranforms a APIResourceDiscovery to an APIResource. We are -// resilient to missing GVK, since this resource might be the parent resource -// for a subresource. If the parent is missing a GVK, it is not returned in -// discovery, and the subresource MUST have the GVK. -func convertAPIResourcev2beta1(in apidiscoveryv2beta1.APIResourceDiscovery) (metav1.APIResource, error) { - result := metav1.APIResource{ - Name: in.Resource, - SingularName: in.SingularResource, - Namespaced: in.Scope == apidiscoveryv2beta1.ScopeNamespace, - Verbs: in.Verbs, - ShortNames: in.ShortNames, - Categories: in.Categories, - } - // Can return partial result with error, which can be the parent for a - // subresource. Do not add this result to the returned discovery resources. - if in.ResponseKind == nil || (*in.ResponseKind) == emptyKind { - return result, fmt.Errorf("discovery resource %s missing GVK", in.Resource) - } - result.Group = in.ResponseKind.Group - result.Version = in.ResponseKind.Version - result.Kind = in.ResponseKind.Kind - return result, nil -} - -// convertAPISubresource tranforms a APISubresourceDiscovery to an APIResource. -func convertAPISubresourcev2beta1(parent metav1.APIResource, in apidiscoveryv2beta1.APISubresourceDiscovery) (metav1.APIResource, error) { - result := metav1.APIResource{} - if in.ResponseKind == nil || (*in.ResponseKind) == emptyKind { - return result, fmt.Errorf("subresource %s/%s missing GVK", parent.Name, in.Subresource) - } - result.Name = fmt.Sprintf("%s/%s", parent.Name, in.Subresource) - result.SingularName = parent.SingularName - result.Namespaced = parent.Namespaced - result.Group = in.ResponseKind.Group - result.Version = in.ResponseKind.Version - result.Kind = in.ResponseKind.Kind - result.Verbs = in.Verbs - return result, nil -} diff --git a/constraint/vendor/k8s.io/client-go/discovery/discovery_client.go b/constraint/vendor/k8s.io/client-go/discovery/discovery_client.go index aae94f9b8..355c70193 100644 --- a/constraint/vendor/k8s.io/client-go/discovery/discovery_client.go +++ b/constraint/vendor/k8s.io/client-go/discovery/discovery_client.go @@ -33,7 +33,6 @@ import ( "google.golang.org/protobuf/proto" apidiscoveryv2 "k8s.io/api/apidiscovery/v2" - apidiscoveryv2beta1 "k8s.io/api/apidiscovery/v2beta1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -60,22 +59,24 @@ const ( defaultBurst = 300 AcceptV1 = runtime.ContentTypeJSON - // Aggregated discovery content-type (v2beta1). NOTE: content-type parameters + // Aggregated discovery content-type. NOTE: content-type parameters // MUST be ordered (g, v, as) for server in "Accept" header (BUT we are resilient // to ordering when comparing returned values in "Content-Type" header). - AcceptV2Beta1 = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList" AcceptV2 = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList" AcceptV2NoPeer = runtime.ContentTypeJSON + ";" + "g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList;profile=nopeer" // Prioritize aggregated discovery by placing first in the order of discovery accept types. - acceptDiscoveryFormats = AcceptV2 + "," + AcceptV2Beta1 + "," + AcceptV1 + acceptDiscoveryFormats = AcceptV2 + "," + AcceptV1 ) // Aggregated discovery content-type GVK. -var v2Beta1GVK = schema.GroupVersionKind{Group: "apidiscovery.k8s.io", Version: "v2beta1", Kind: "APIGroupDiscoveryList"} var v2GVK = schema.GroupVersionKind{Group: "apidiscovery.k8s.io", Version: "v2", Kind: "APIGroupDiscoveryList"} // DiscoveryInterface holds the methods that discover server-supported API groups, // versions and resources. +// +// DiscoveryInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use DiscoveryInterfaceWithContext instead. type DiscoveryInterface interface { RESTClient() restclient.Interface ServerGroupsInterface @@ -86,22 +87,123 @@ type DiscoveryInterface interface { // Returns copy of current discovery client that will only // receive the legacy discovery format, or pointer to current // discovery client if it does not support legacy-only discovery. + // + // DiscoveryInterfaceWithContext.WithLegacyWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use DiscoveryInterfaceWithContext.WithLegacyWithContext instead. WithLegacy() DiscoveryInterface } +// DiscoveryInterfaceWithContext holds the methods that discover server-supported API groups, +// versions and resources. +type DiscoveryInterfaceWithContext interface { + RESTClient() restclient.Interface + ServerGroupsInterfaceWithContext + ServerResourcesInterfaceWithContext + ServerVersionInterfaceWithContext + OpenAPISchemaInterfaceWithContext + OpenAPIV3SchemaInterfaceWithContext + // Returns copy of current discovery client that will only + // receive the legacy discovery format, or pointer to current + // discovery client if it does not support legacy-only discovery. + WithLegacyWithContext(ctx context.Context) DiscoveryInterfaceWithContext +} + +// DiscoveryInterfaces combines both interface variants. +type DiscoveryInterfaces interface { + DiscoveryInterface + DiscoveryInterfaceWithContext +} + +func ToDiscoveryInterfaceWithContext(i DiscoveryInterface) DiscoveryInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(DiscoveryInterfaceWithContext); ok { + return i + } + return &discoveryInterfaceWrapper{ + ServerGroupsInterfaceWithContext: ToServerGroupsInterfaceWithContext(i), + ServerResourcesInterfaceWithContext: ToServerResourcesInterfaceWithContext(i), + ServerVersionInterfaceWithContext: ToServerVersionInterfaceWithContext(i), + OpenAPISchemaInterfaceWithContext: ToOpenAPISchemaInterfaceWithContext(i), + OpenAPIV3SchemaInterfaceWithContext: OpenAPIV3ToSchemaInterfaceWithContext(i), + delegate: i, + } +} + +type discoveryInterfaceWrapper struct { + ServerGroupsInterfaceWithContext + ServerResourcesInterfaceWithContext + ServerVersionInterfaceWithContext + OpenAPISchemaInterfaceWithContext + OpenAPIV3SchemaInterfaceWithContext + delegate DiscoveryInterface +} + +func (i *discoveryInterfaceWrapper) RESTClient() restclient.Interface { + return i.delegate.RESTClient() +} + +func (i *discoveryInterfaceWrapper) WithLegacyWithContext(ctx context.Context) DiscoveryInterfaceWithContext { + return ToDiscoveryInterfaceWithContext(i.delegate.WithLegacy()) +} + // AggregatedDiscoveryInterface extends DiscoveryInterface to include a method to possibly // return discovery resources along with the discovery groups, which is what the newer // aggregated discovery format does (APIGroupDiscoveryList). +// +// AggregatedDiscoveryInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use AggregatedDiscoveryInterfaceWithContext instead. type AggregatedDiscoveryInterface interface { DiscoveryInterface + // AggregatedDiscoveryInterfaceWithContext.GroupsAndMaybeResourcesWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use AggregatedDiscoveryInterfaceWithContext.GroupsAndMaybeResourcesWithContext instead. GroupsAndMaybeResources() (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) } +// AggregatedDiscoveryInterfaceWithContext extends DiscoveryInterface to include a method to possibly +// return discovery resources along with the discovery groups, which is what the newer +// aggregated discovery format does (APIGroupDiscoveryList). +type AggregatedDiscoveryInterfaceWithContext interface { + DiscoveryInterfaceWithContext + + GroupsAndMaybeResourcesWithContext(ctx context.Context) (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) +} + +func ToAggregatedDiscoveryInterfaceWithContext(i AggregatedDiscoveryInterface) AggregatedDiscoveryInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(AggregatedDiscoveryInterfaceWithContext); ok { + return i + } + return &aggregatedDiscoveryInterfaceWrapper{ + DiscoveryInterfaceWithContext: ToDiscoveryInterfaceWithContext(i), + delegate: i, + } +} + +type aggregatedDiscoveryInterfaceWrapper struct { + DiscoveryInterfaceWithContext + delegate AggregatedDiscoveryInterface +} + +func (i *aggregatedDiscoveryInterfaceWrapper) GroupsAndMaybeResourcesWithContext(ctx context.Context) (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) { + return i.delegate.GroupsAndMaybeResources() +} + // CachedDiscoveryInterface is a DiscoveryInterface with cache invalidation and freshness. // Note that If the ServerResourcesForGroupVersion method returns a cache miss // error, the user needs to explicitly call Invalidate to clear the cache, // otherwise the same cache miss error will be returned next time. +// +// CachedDiscoveryInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use CachedDiscoveryInterfaceWithContext instead. type CachedDiscoveryInterface interface { DiscoveryInterface // Fresh is supposed to tell the caller whether or not to retry if the cache @@ -109,58 +211,343 @@ type CachedDiscoveryInterface interface { // // TODO: this needs to be revisited, this interface can't be locked properly // and doesn't make a lot of sense. + // + // CachedDiscoveryInterfaceWithContext.FreshWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use CachedDiscoveryInterfaceWithContext.FreshWithContext instead. Fresh() bool // Invalidate enforces that no cached data that is older than the current time // is used. + // + // CachedDiscoveryInterfaceWithContext.InvalidateWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use CachedDiscoveryInterfaceWithContext.InvalidateWithContext instead. Invalidate() } +// CachedDiscoveryInterfaceWithContext is a DiscoveryInterfaceWithContext with cache invalidation and freshness. +// Note that If the ServerResourcesForGroupVersion method returns a cache miss +// error, the user needs to explicitly call Invalidate to clear the cache, +// otherwise the same cache miss error will be returned next time. +type CachedDiscoveryInterfaceWithContext interface { + DiscoveryInterfaceWithContext + // Fresh is supposed to tell the caller whether or not to retry if the cache + // fails to find something (false = retry, true = no need to retry). + // + // TODO: this needs to be revisited, this interface can't be locked properly + // and doesn't make a lot of sense. + FreshWithContext(ctx context.Context) bool + // Invalidate enforces that no cached data that is older than the current time + // is used. + InvalidateWithContext(ctx context.Context) +} + +func ToCachedDiscoveryInterfaceWithContext(i CachedDiscoveryInterface) CachedDiscoveryInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(CachedDiscoveryInterfaceWithContext); ok { + return i + } + return &cachedDiscoveryInterfaceWrapper{ + DiscoveryInterfaceWithContext: ToDiscoveryInterfaceWithContext(i), + delegate: i, + } +} + +type cachedDiscoveryInterfaceWrapper struct { + DiscoveryInterfaceWithContext + delegate CachedDiscoveryInterface +} + +func (i *cachedDiscoveryInterfaceWrapper) FreshWithContext(ctx context.Context) bool { + return i.delegate.Fresh() +} + +func (i *cachedDiscoveryInterfaceWrapper) InvalidateWithContext(ctx context.Context) { + i.delegate.Invalidate() +} + // ServerGroupsInterface has methods for obtaining supported groups on the API server +// +// ServerGroupsInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerGroupsInterfaceWithContext instead. type ServerGroupsInterface interface { // ServerGroups returns the supported groups, with information like supported versions and the // preferred version. + // + // ServerGroupsInterfaceWithContext.ServerGroups is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerGroupsInterfaceWithContext.ServerGroups instead. ServerGroups() (*metav1.APIGroupList, error) } +// ServerGroupsInterfaceWithContext has methods for obtaining supported groups on the API server +type ServerGroupsInterfaceWithContext interface { + // ServerGroups returns the supported groups, with information like supported versions and the + // preferred version. + ServerGroupsWithContext(ctx context.Context) (*metav1.APIGroupList, error) +} + +func ToServerGroupsInterfaceWithContext(i ServerGroupsInterface) ServerGroupsInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(ServerGroupsInterfaceWithContext); ok { + return i + } + return &serverGroupsInterfaceWrapper{ + delegate: i, + } +} + +type serverGroupsInterfaceWrapper struct { + delegate ServerGroupsInterface +} + +func (i *serverGroupsInterfaceWrapper) ServerGroupsWithContext(ctx context.Context) (*metav1.APIGroupList, error) { + return i.delegate.ServerGroups() +} + // ServerResourcesInterface has methods for obtaining supported resources on the API server +// +// ServerGroupsAndResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerGroupsAndResourcesWithContext instead. type ServerResourcesInterface interface { // ServerResourcesForGroupVersion returns the supported resources for a group and version. + // + // ServerGroupsAndResourcesWithContext.ServerResourcesForGroupVersionWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerGroupsAndResourcesWithContext.ServerResourcesForGroupVersionWithContext instead. ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) // ServerGroupsAndResources returns the supported groups and resources for all groups and versions. // // The returned group and resource lists might be non-nil with partial results even in the // case of non-nil error. + // + // ServerGroupsAndResourcesWithContext.ServerGroupsAndResourcesWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerGroupsAndResourcesWithContext.ServerGroupsAndResourcesWithContext instead. ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) // ServerPreferredResources returns the supported resources with the version preferred by the // server. // // The returned group and resource lists might be non-nil with partial results even in the // case of non-nil error. + // + // ServerResourcesInterfaceWithContext.ServerPreferredResourcesWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerResourcesInterfaceWithContext.ServerPreferredResourcesWithContext instead. ServerPreferredResources() ([]*metav1.APIResourceList, error) // ServerPreferredNamespacedResources returns the supported namespaced resources with the // version preferred by the server. // // The returned resource list might be non-nil with partial results even in the case of // non-nil error. + // + // ServerResourcesInterfaceWithContext.ServerPreferredNamespacedResourcesWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerResourcesInterfaceWithContext.ServerPreferredNamespacedResourcesWithContext instead. ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) } +// ServerResourcesInterfaceWithContext has methods for obtaining supported resources on the API server +type ServerResourcesInterfaceWithContext interface { + // ServerResourcesForGroupVersionWithContext returns the supported resources for a group and version. + ServerResourcesForGroupVersionWithContext(ctx context.Context, groupVersion string) (*metav1.APIResourceList, error) + // ServerGroupsAndResourcesWithContext returns the supported groups and resources for all groups and versions. + // + // The returned group and resource lists might be non-nil with partial results even in the + // case of non-nil error. + ServerGroupsAndResourcesWithContext(ctx context.Context) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) + // ServerPreferredResourcesWithContext returns the supported resources with the version preferred by the + // server. + // + // The returned group and resource lists might be non-nil with partial results even in the + // case of non-nil error. + ServerPreferredResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) + // ServerPreferredNamespacedResourcesWithContext returns the supported namespaced resources with the + // version preferred by the server. + // + // The returned resource list might be non-nil with partial results even in the case of + // non-nil error. + ServerPreferredNamespacedResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) +} + +func ToServerResourcesInterfaceWithContext(i ServerResourcesInterface) ServerResourcesInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(ServerResourcesInterfaceWithContext); ok { + return i + } + return &serverResourcesInterfaceWrapper{ + delegate: i, + } +} + +type serverResourcesInterfaceWrapper struct { + delegate ServerResourcesInterface +} + +func (i *serverResourcesInterfaceWrapper) ServerResourcesForGroupVersionWithContext(ctx context.Context, groupVersion string) (*metav1.APIResourceList, error) { + return i.delegate.ServerResourcesForGroupVersion(groupVersion) +} + +func (i *serverResourcesInterfaceWrapper) ServerGroupsAndResourcesWithContext(ctx context.Context) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + return i.delegate.ServerGroupsAndResources() +} + +func (i *serverResourcesInterfaceWrapper) ServerPreferredResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) { + return i.delegate.ServerPreferredResources() +} + +func (i *serverResourcesInterfaceWrapper) ServerPreferredNamespacedResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) { + return i.delegate.ServerPreferredNamespacedResources() +} + // ServerVersionInterface has a method for retrieving the server's version. +// +// ServerVersionInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerVersionInterfaceWithContext instead. type ServerVersionInterface interface { // ServerVersion retrieves and parses the server's version (git version). + // + // ServerVersionInterfaceWithContext.ServerVersionWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use ServerVersionInterfaceWithContext.ServerVersionWithContext instead. ServerVersion() (*version.Info, error) } +// ServerVersionInterface has a method for retrieving the server's version. +type ServerVersionInterfaceWithContext interface { + // ServerVersion retrieves and parses the server's version (git version). + ServerVersionWithContext(ctx context.Context) (*version.Info, error) +} + +func ToServerVersionInterfaceWithContext(i ServerVersionInterface) ServerVersionInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(ServerVersionInterfaceWithContext); ok { + return i + } + return &serverVersionInterfaceWrapper{ + delegate: i, + } +} + +type serverVersionInterfaceWrapper struct { + delegate ServerVersionInterface +} + +func (i *serverVersionInterfaceWrapper) ServerVersionWithContext(ctx context.Context) (*version.Info, error) { + return i.delegate.ServerVersion() +} + // OpenAPISchemaInterface has a method to retrieve the open API schema. +// +// OpenAPISchemaInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use OpenAPISchemaInterfaceWithContext instead. type OpenAPISchemaInterface interface { // OpenAPISchema retrieves and parses the swagger API schema the server supports. + // + // OpenAPISchemaInterfaceWithContext.OpenAPISchemaWithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use OpenAPISchemaInterfaceWithContext.OpenAPISchemaWithContext instead. OpenAPISchema() (*openapi_v2.Document, error) } +// OpenAPISchemaInterfaceWithContext has a method to retrieve the open API schema. +type OpenAPISchemaInterfaceWithContext interface { + // OpenAPISchemaWithContext retrieves and parses the swagger API schema the server supports. + OpenAPISchemaWithContext(ctx context.Context) (*openapi_v2.Document, error) +} + +func ToOpenAPISchemaInterfaceWithContext(i OpenAPISchemaInterface) OpenAPISchemaInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(OpenAPISchemaInterfaceWithContext); ok { + return i + } + return &openAPISchemaInterfaceWrapper{ + delegate: i, + } +} + +type openAPISchemaInterfaceWrapper struct { + delegate OpenAPISchemaInterface +} + +func (i *openAPISchemaInterfaceWrapper) OpenAPISchemaWithContext(ctx context.Context) (*openapi_v2.Document, error) { + return i.delegate.OpenAPISchema() +} + +// OpenAPIV3SchemaInterfaceWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use OpenAPIV3SchemaInterfaceWithContext instead. type OpenAPIV3SchemaInterface interface { + // OpenAPIV3SchemaInterfaceWithContext.OpenAPIV3WithContext is a better alternative because it supports contextual logging and cancellation. + // + // Contextual logging: Use OpenAPIV3SchemaInterfaceWithContext.OpenAPIV3WithContext instead. OpenAPIV3() openapi.Client } +type OpenAPIV3SchemaInterfaceWithContext interface { + OpenAPIV3WithContext(ctx context.Context) openapi.ClientWithContext +} + +func OpenAPIV3ToSchemaInterfaceWithContext(i OpenAPIV3SchemaInterface) OpenAPIV3SchemaInterfaceWithContext { + if i == nil { + return nil + } + if i, ok := i.(OpenAPIV3SchemaInterfaceWithContext); ok { + return i + } + return &openAPIV3SchemaInterfaceWrapper{ + delegate: i, + } +} + +type openAPIV3SchemaInterfaceWrapper struct { + delegate OpenAPIV3SchemaInterface +} + +func (i *openAPIV3SchemaInterfaceWrapper) OpenAPIV3WithContext(ctx context.Context) openapi.ClientWithContext { + return ToOpenAPIClientWithContext(i.delegate.OpenAPIV3()) +} + +func ToOpenAPIClientWithContext(i openapi.Client) openapi.ClientWithContext { //nolint:staticcheck // Intentionally using the old interface here. + if i == nil { + return nil + } + if i, ok := i.(openapi.ClientWithContext); ok { + return i + } + return &openAPIClientWrapper{ + delegate: i, + } +} + +type openAPIClientWrapper struct { + //nolint:staticcheck // Intentionally using the old interface here. + delegate openapi.Client +} + +func (i *openAPIClientWrapper) PathsWithContext(ctx context.Context) (map[string]openapi.GroupVersionWithContext, error) { + resultWithoutContext, err := i.delegate.Paths() + result := make(map[string]openapi.GroupVersionWithContext, len(resultWithoutContext)) + for key, entry := range resultWithoutContext { + result[key] = openapi.ToGroupVersionWithContext(entry) + } + return result, err +} + // DiscoveryClient implements the functions that discover server-supported API groups, // versions and resources. type DiscoveryClient struct { @@ -202,19 +589,42 @@ func apiVersionsToAPIGroup(apiVersions *metav1.APIVersions) (apiGroup metav1.API // as aggregated discovery format or legacy format. For safety, resources will only // be returned if both endpoints returned resources. Returned "failedGVs" can be // empty, but will only be nil in the case an error is returned. +// +// GroupsAndMaybeResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use GroupsAndMaybeResourcesWithContext instead. func (d *DiscoveryClient) GroupsAndMaybeResources() ( *metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) { + return d.GroupsAndMaybeResourcesWithContext(context.Background()) +} + +// GroupsAndMaybeResources returns the discovery groups, and (if new aggregated +// discovery format) the resources keyed by group/version. Merges discovery groups +// and resources from /api and /apis (either aggregated or not). Legacy groups +// must be ordered first. The server will either return both endpoints (/api, /apis) +// as aggregated discovery format or legacy format. For safety, resources will only +// be returned if both endpoints returned resources. Returned "failedGVs" can be +// empty, but will only be nil in the case an error is returned. +func (d *DiscoveryClient) GroupsAndMaybeResourcesWithContext(ctx context.Context) ( + *metav1.APIGroupList, + map[schema.GroupVersion]*metav1.APIResourceList, + map[schema.GroupVersion]error, + error) { + if err := ctx.Err(); err != nil { + return nil, nil, nil, err + } + // Legacy group ordered first (there is only one -- core/v1 group). Returned groups must // be non-nil, but it could be empty. Returned resources, apiResources map could be nil. - groups, resources, failedGVs, err := d.downloadLegacy() + groups, resources, failedGVs, err := d.downloadLegacy(ctx) if err != nil { return nil, nil, nil, err } // Discovery groups and (possibly) resources downloaded from /apis. - apiGroups, apiResources, failedApisGVs, aerr := d.downloadAPIs() + apiGroups, apiResources, failedApisGVs, aerr := d.downloadAPIs(ctx) if aerr != nil { return nil, nil, nil, aerr } @@ -242,7 +652,7 @@ func (d *DiscoveryClient) GroupsAndMaybeResources() ( // possible for the resource map to be nil if the server returned // the unaggregated discovery. Returned "failedGVs" can be empty, but // will only be nil in the case of a returned error. -func (d *DiscoveryClient) downloadLegacy() ( +func (d *DiscoveryClient) downloadLegacy(ctx context.Context) ( *metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, @@ -252,7 +662,7 @@ func (d *DiscoveryClient) downloadLegacy() ( body, err := d.restClient.Get(). AbsPath("/api"). SetHeader("Accept", accept). - Do(context.TODO()). + Do(ctx). ContentType(&responseContentType). Raw() apiGroupList := &metav1.APIGroupList{} @@ -277,13 +687,6 @@ func (d *DiscoveryClient) downloadLegacy() ( return nil, nil, nil, err } apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery) - } else if isGVK, _ := ContentTypeIsGVK(responseContentType, v2Beta1GVK); isGVK { - var aggregatedDiscovery apidiscoveryv2beta1.APIGroupDiscoveryList - err = json.Unmarshal(body, &aggregatedDiscovery) - if err != nil { - return nil, nil, nil, err - } - apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResourcesV2Beta1(aggregatedDiscovery) } else { // Default is unaggregated discovery v1. var v metav1.APIVersions @@ -305,7 +708,7 @@ func (d *DiscoveryClient) downloadLegacy() ( // discovery resources. The returned groups will always exist, but the // resources map may be nil. Returned "failedGVs" can be empty, but will // only be nil in the case of a returned error. -func (d *DiscoveryClient) downloadAPIs() ( +func (d *DiscoveryClient) downloadAPIs(ctx context.Context) ( *metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, @@ -315,7 +718,7 @@ func (d *DiscoveryClient) downloadAPIs() ( body, err := d.restClient.Get(). AbsPath("/apis"). SetHeader("Accept", accept). - Do(context.TODO()). + Do(ctx). ContentType(&responseContentType). Raw() if err != nil { @@ -333,13 +736,6 @@ func (d *DiscoveryClient) downloadAPIs() ( return nil, nil, nil, err } apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery) - } else if isGVK, _ := ContentTypeIsGVK(responseContentType, v2Beta1GVK); isGVK { - var aggregatedDiscovery apidiscoveryv2beta1.APIGroupDiscoveryList - err = json.Unmarshal(body, &aggregatedDiscovery) - if err != nil { - return nil, nil, nil, err - } - apiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResourcesV2Beta1(aggregatedDiscovery) } else { // Default is unaggregated discovery v1. err = json.Unmarshal(body, apiGroupList) @@ -368,9 +764,9 @@ func selectDiscoveryAcceptHeader(useLegacy, nopeer bool) string { // content-type parameters, as well as parameters added by // intermediaries such as proxies or gateways. Examples: // -// ("application/json; g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil) -// ("application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil) -// ("application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io;charset=utf-8", {apidiscovery.k8s.io, v2beta1, APIGroupDiscoveryList}) = (true, nil) +// ("application/json; g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList", {apidiscovery.k8s.io, v2, APIGroupDiscoveryList}) = (true, nil) +// ("application/json; as=APIGroupDiscoveryList;v=v2;g=apidiscovery.k8s.io", {apidiscovery.k8s.io, v2, APIGroupDiscoveryList}) = (true, nil) +// ("application/json; as=APIGroupDiscoveryList;v=v2;g=apidiscovery.k8s.io;charset=utf-8", {apidiscovery.k8s.io, v2, APIGroupDiscoveryList}) = (true, nil) // ("application/json", any GVK) = (false, nil) // ("application/json; charset=UTF-8", any GVK) = (false, nil) // ("malformed content type string", any GVK) = (false, error) @@ -388,8 +784,18 @@ func ContentTypeIsGVK(contentType string, gvk schema.GroupVersionKind) (bool, er // ServerGroups returns the supported groups, with information like supported versions and the // preferred version. +// +// ServerGroupsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerGroupsWithContext instead. func (d *DiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) { - groups, _, _, err := d.GroupsAndMaybeResources() + return d.ServerGroupsWithContext(context.Background()) +} + +// ServerGroupsWithContext returns the supported groups, with information like supported versions and the +// preferred version. +func (d *DiscoveryClient) ServerGroupsWithContext(ctx context.Context) (*metav1.APIGroupList, error) { + groups, _, _, err := d.GroupsAndMaybeResourcesWithContext(ctx) if err != nil { return nil, err } @@ -397,7 +803,16 @@ func (d *DiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) { } // ServerResourcesForGroupVersion returns the supported resources for a group and version. +// +// ServerResourcesForGroupVersionWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerResourcesForGroupVersionWithContext instead. func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error) { + return d.ServerResourcesForGroupVersionWithContext(context.Background(), groupVersion) +} + +// ServerResourcesForGroupVersionWithContext returns the supported resources for a group and version. +func (d *DiscoveryClient) ServerResourcesForGroupVersionWithContext(ctx context.Context, groupVersion string) (resources *metav1.APIResourceList, err error) { url := url.URL{} if len(groupVersion) == 0 { return nil, fmt.Errorf("groupVersion shouldn't be empty") @@ -410,7 +825,7 @@ func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (r resources = &metav1.APIResourceList{ GroupVersion: groupVersion, } - err = d.restClient.Get().AbsPath(url.String()).Do(context.TODO()).Into(resources) + err = d.restClient.Get().AbsPath(url.String()).Do(ctx).Into(resources) if err != nil { // Tolerate core/v1 not found response by returning empty resource list; // this probably should not happen. But we should verify all callers are @@ -425,8 +840,13 @@ func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (r // ServerGroupsAndResources returns the supported resources for all groups and versions. func (d *DiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { - return withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { - return ServerGroupsAndResources(d) + return d.ServerGroupsAndResourcesWithContext(context.Background()) +} + +// ServerGroupsAndResourcesWithContext returns the supported resources for all groups and versions. +func (d *DiscoveryClient) ServerGroupsAndResourcesWithContext(ctx context.Context) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + return withRetries(ctx, defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + return ServerGroupsAndResourcesWithContext(ctx, d) }) } @@ -469,7 +889,18 @@ func GroupDiscoveryFailedErrorGroups(err error) (map[schema.GroupVersion]error, return nil, false } +// ServerGroupsAndResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerGroupsAndResourcesWithContext instead. func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + return ServerGroupsAndResourcesWithContext(context.Background(), ToDiscoveryInterfaceWithContext(d)) +} + +func ServerGroupsAndResourcesWithContext(ctx context.Context, d DiscoveryInterfaceWithContext) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + var sgs *metav1.APIGroupList var resources []*metav1.APIResourceList var failedGVs map[schema.GroupVersion]error @@ -477,14 +908,21 @@ func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*meta // If the passed discovery object implements the wider AggregatedDiscoveryInterface, // then attempt to retrieve aggregated discovery with both groups and the resources. - if ad, ok := d.(AggregatedDiscoveryInterface); ok { + ad, ok := d.(AggregatedDiscoveryInterfaceWithContext) + if !ok { + if ad2, ok2 := d.(AggregatedDiscoveryInterface); ok2 { + ad = ToAggregatedDiscoveryInterfaceWithContext(ad2) + ok = true + } + } + if ok { var resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList - sgs, resourcesByGV, failedGVs, err = ad.GroupsAndMaybeResources() + sgs, resourcesByGV, failedGVs, err = ad.GroupsAndMaybeResourcesWithContext(ctx) for _, resourceList := range resourcesByGV { resources = append(resources, resourceList) } } else { - sgs, err = d.ServerGroups() + sgs, err = d.ServerGroupsWithContext(ctx) } if sgs == nil { @@ -505,7 +943,7 @@ func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*meta return resultGroups, resources, ferr } - groupVersionResources, failedGroups := fetchGroupVersionResources(d, sgs) + groupVersionResources, failedGroups := fetchGroupVersionResources(ctx, d, sgs) // order results by group/version discovery order result := []*metav1.APIResourceList{} @@ -526,7 +964,20 @@ func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*meta } // ServerPreferredResources uses the provided discovery interface to look up preferred resources +// +// ServerPreferredResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerPreferredResourcesWithContext instead. func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) { + return ServerPreferredResourcesWithContext(context.Background(), ToDiscoveryInterfaceWithContext(d)) +} + +// ServerPreferredResourcesWithContext uses the provided discovery interface to look up preferred resources +func ServerPreferredResourcesWithContext(ctx context.Context, d DiscoveryInterfaceWithContext) ([]*metav1.APIResourceList, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + var serverGroupList *metav1.APIGroupList var failedGroups map[schema.GroupVersion]error var groupVersionResources map[schema.GroupVersion]*metav1.APIResourceList @@ -535,18 +986,24 @@ func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, // If the passed discovery object implements the wider AggregatedDiscoveryInterface, // then it is attempt to retrieve both the groups and the resources. "failedGroups" // are Group/Versions returned as stale in AggregatedDiscovery format. - ad, ok := d.(AggregatedDiscoveryInterface) + ad, ok := d.(AggregatedDiscoveryInterfaceWithContext) + if !ok { + if ad2, ok2 := d.(AggregatedDiscoveryInterface); ok2 { + ad = ToAggregatedDiscoveryInterfaceWithContext(ad2) + ok = true + } + } if ok { - serverGroupList, groupVersionResources, failedGroups, err = ad.GroupsAndMaybeResources() + serverGroupList, groupVersionResources, failedGroups, err = ad.GroupsAndMaybeResourcesWithContext(ctx) } else { - serverGroupList, err = d.ServerGroups() + serverGroupList, err = d.ServerGroupsWithContext(ctx) } if err != nil { return nil, err } // Non-aggregated discovery must fetch resources from Groups. if groupVersionResources == nil { - groupVersionResources, failedGroups = fetchGroupVersionResources(d, serverGroupList) + groupVersionResources, failedGroups = fetchGroupVersionResources(ctx, d, serverGroupList) } result := []*metav1.APIResourceList{} @@ -602,7 +1059,7 @@ func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, } // fetchServerResourcesForGroupVersions uses the discovery client to fetch the resources for the specified groups in parallel. -func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error) { +func fetchGroupVersionResources(ctx context.Context, d DiscoveryInterfaceWithContext, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error) { groupVersionResources := make(map[schema.GroupVersion]*metav1.APIResourceList) failedGroups := make(map[schema.GroupVersion]error) @@ -614,9 +1071,9 @@ func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroup wg.Add(1) go func() { defer wg.Done() - defer utilruntime.HandleCrash() + defer utilruntime.HandleCrashWithContext(ctx) - apiResourceList, err := d.ServerResourcesForGroupVersion(groupVersion.String()) + apiResourceList, err := d.ServerResourcesForGroupVersionWithContext(ctx, groupVersion.String()) // lock to record results resultLock.Lock() @@ -640,23 +1097,56 @@ func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroup // ServerPreferredResources returns the supported resources with the version preferred by the // server. +// +// ServerPreferredResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerPreferredResourcesWithContext instead. func (d *DiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) { - _, rs, err := withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + _, rs, err := withRetries(context.Background(), defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { rs, err := ServerPreferredResources(d) return nil, rs, err }) return rs, err } +// ServerPreferredResourcesWithContext returns the supported resources with the version preferred by the +// server. +func (d *DiscoveryClient) ServerPreferredResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) { + _, rs, err := withRetries(ctx, defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { + rs, err := ServerPreferredResourcesWithContext(ctx, d) + return nil, rs, err + }) + return rs, err +} + // ServerPreferredNamespacedResources returns the supported namespaced resources with the // version preferred by the server. +// +// ServerPreferredNamespacedResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerPreferredNamespacedResourcesWithContext instead. func (d *DiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) { return ServerPreferredNamespacedResources(d) } +// ServerPreferredNamespacedResources returns the supported namespaced resources with the +// version preferred by the server. +func (d *DiscoveryClient) ServerPreferredNamespacedResourcesWithContext(ctx context.Context) ([]*metav1.APIResourceList, error) { + return ServerPreferredNamespacedResourcesWithContext(ctx, d) +} + // ServerPreferredNamespacedResources uses the provided discovery interface to look up preferred namespaced resources +// +// ServerPreferredNamespacedResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ServerPreferredNamespacedResourcesWithContext instead. func ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) { - all, err := ServerPreferredResources(d) + return ServerPreferredNamespacedResourcesWithContext(context.Background(), ToDiscoveryInterfaceWithContext(d)) +} + +// ServerPreferredNamespacedResourcesWithContext uses the provided discovery interface to look up preferred namespaced resources +func ServerPreferredNamespacedResourcesWithContext(ctx context.Context, d DiscoveryInterfaceWithContext) ([]*metav1.APIResourceList, error) { + all, err := ServerPreferredResourcesWithContext(ctx, d) return FilteredBy(ResourcePredicateFunc(func(groupVersion string, r *metav1.APIResource) bool { return r.Namespaced }), all), err @@ -664,7 +1154,12 @@ func ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIReso // ServerVersion retrieves and parses the server's version (git version). func (d *DiscoveryClient) ServerVersion() (*version.Info, error) { - body, err := d.restClient.Get().AbsPath("/version").Do(context.TODO()).Raw() + return d.ServerVersionWithContext(context.Background()) +} + +// ServerVersionWithContext retrieves and parses the server's version (git version). +func (d *DiscoveryClient) ServerVersionWithContext(ctx context.Context) (*version.Info, error) { + body, err := d.restClient.Get().AbsPath("/version").Do(ctx).Raw() if err != nil { return nil, err } @@ -678,7 +1173,12 @@ func (d *DiscoveryClient) ServerVersion() (*version.Info, error) { // OpenAPISchema fetches the open api v2 schema using a rest client and parses the proto. func (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) { - data, err := d.restClient.Get().AbsPath("/openapi/v2").SetHeader("Accept", openAPIV2mimePb).Do(context.TODO()).Raw() + return d.OpenAPISchemaWithContext(context.Background()) +} + +// OpenAPISchemaWithContext fetches the open api v2 schema using a rest client and parses the proto. +func (d *DiscoveryClient) OpenAPISchemaWithContext(ctx context.Context) (*openapi_v2.Document, error) { + data, err := d.restClient.Get().AbsPath("/openapi/v2").SetHeader("Accept", openAPIV2mimePb).Do(ctx).Raw() if err != nil { return nil, err } @@ -690,20 +1190,40 @@ func (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) { return document, nil } +// OpenAPIV3WithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use OpenAPIV3WithContext instead. func (d *DiscoveryClient) OpenAPIV3() openapi.Client { return openapi.NewClient(d.restClient) } +func (d *DiscoveryClient) OpenAPIV3WithContext(ctx context.Context) openapi.ClientWithContext { + return openapi.NewClientWithContext(d.restClient) +} + // WithLegacy returns copy of current discovery client that will only // receive the legacy discovery format. +// +// WithLegacyWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use WithLegacyWithContext instead. func (d *DiscoveryClient) WithLegacy() DiscoveryInterface { client := *d client.UseLegacyDiscovery = true return &client } +// WithLegacyWithContext returns copy of current discovery client that will only +// receive the legacy discovery format. +func (d *DiscoveryClient) WithLegacyWithContext(ctx context.Context) DiscoveryInterfaceWithContext { + client := *d + client.UseLegacyDiscovery = true + return &client +} + // withRetries retries the given recovery function in case the groups supported by the server change after ServerGroup() returns. -func withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { +// It retries only if the context isn't canceled. +func withRetries(ctx context.Context, maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) { var result []*metav1.APIResourceList var resultGroups []*metav1.APIGroup var err error @@ -715,6 +1235,10 @@ func withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIReso if _, ok := err.(*ErrGroupDiscoveryFailed); !ok { return nil, nil, err } + if ctx.Err() != nil { + // Give up retrying because of context cancellation and propagate the error returned by f. + return nil, nil, err + } } return resultGroups, result, err } diff --git a/constraint/vendor/k8s.io/client-go/discovery/helper.go b/constraint/vendor/k8s.io/client-go/discovery/helper.go index e79f073b0..a58bae284 100644 --- a/constraint/vendor/k8s.io/client-go/discovery/helper.go +++ b/constraint/vendor/k8s.io/client-go/discovery/helper.go @@ -71,7 +71,7 @@ func ServerSupportsVersion(client DiscoveryInterface, requiredGV schema.GroupVer return err } versions := metav1.ExtractGroupVersions(groups) - serverVersions := sets.String{} + serverVersions := sets.Set[string]{} for _, v := range versions { serverVersions.Insert(v) } diff --git a/constraint/vendor/k8s.io/client-go/dynamic/simple.go b/constraint/vendor/k8s.io/client-go/dynamic/simple.go index 2532329d0..add5b1377 100644 --- a/constraint/vendor/k8s.io/client-go/dynamic/simple.go +++ b/constraint/vendor/k8s.io/client-go/dynamic/simple.go @@ -19,6 +19,8 @@ package dynamic import ( "context" "fmt" + "net/http" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -28,7 +30,6 @@ import ( "k8s.io/client-go/features" "k8s.io/client-go/rest" "k8s.io/client-go/util/apply" - "net/http" ) type DynamicClient struct { diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/interface.go index 4bfe9c4c6..8e643aa18 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/interface.go @@ -25,17 +25,17 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. - MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer + MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer // MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. - MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer + MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer // MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer. - MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer + MutatingWebhookConfigurations() TypedMutatingWebhookConfigurationInformer // ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. - ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer + ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer // ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. - ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer + ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer // ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer. - ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer + ValidatingWebhookConfigurations() TypedValidatingWebhookConfigurationInformer } type version struct { @@ -49,32 +49,32 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. -func (v *version) MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer { +// MutatingAdmissionPolicies returns a TypedMutatingAdmissionPolicyInformer. +func (v *version) MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer { return &mutatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. -func (v *version) MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer { +// MutatingAdmissionPolicyBindings returns a TypedMutatingAdmissionPolicyBindingInformer. +func (v *version) MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer { return &mutatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer. -func (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer { +// MutatingWebhookConfigurations returns a TypedMutatingWebhookConfigurationInformer. +func (v *version) MutatingWebhookConfigurations() TypedMutatingWebhookConfigurationInformer { return &mutatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. -func (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer { +// ValidatingAdmissionPolicies returns a TypedValidatingAdmissionPolicyInformer. +func (v *version) ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer { return &validatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. -func (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer { +// ValidatingAdmissionPolicyBindings returns a TypedValidatingAdmissionPolicyBindingInformer. +func (v *version) ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer { return &validatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer. -func (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer { +// ValidatingWebhookConfigurations returns a TypedValidatingWebhookConfigurationInformer. +func (v *version) ValidatingWebhookConfigurations() TypedValidatingWebhookConfigurationInformer { return &validatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicy.go index 65df1905a..8dbb9e8e4 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicies. +// MutatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyInformer]). type MutatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.MutatingAdmissionPolicyLister } +// TypedMutatingAdmissionPolicyInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyInformer. +type TypedMutatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1.MutatingAdmissionPolicyLister +} + +// MutatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + +// DeletedMutatingAdmissionPolicy is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicy. +type DeletedMutatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1.MutatingAdmissionPolicy] + type mutatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyInformer struct { // NewMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformer]). func NewMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyInformer]). func NewFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformerWithOptions]). func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "mutatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.MutatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyInformer) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1.MutatingAdmissionPolicy{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyInformer) Lister() admissionregistrationv1.MutatingAdmissionPolicyLister { return admissionregistrationv1.NewMutatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyInformer converts an untyped informer into a TypedMutatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyInformer(informer MutatingAdmissionPolicyInformer) TypedMutatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyInformer); ok { + return informer + } + return &mutatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyTypedInformerAdapter struct { + MutatingAdmissionPolicyInformer +} + +func (a *mutatingAdmissionPolicyTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicy](a.Informer()) +} + +// ToMutatingAdmissionPolicyIndexInformer converts an untyped informer into a MutatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicybinding.go index d06ca0b4e..11da9c840 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicyBindings. +// MutatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyBindingInformer]). type MutatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.MutatingAdmissionPolicyBindingLister } +// TypedMutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyBindingInformer. +type TypedMutatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1.MutatingAdmissionPolicyBindingLister +} + +// MutatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + +// DeletedMutatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicyBinding. +type DeletedMutatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding] + type mutatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyBindingInformer struct { // NewMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformer]). func NewMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyBindingInformer]). func NewFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformerWithOptions]). func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "mutatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.MutatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyBindingInformer) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1.MutatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1.MutatingAdmissionPolicyBindingLister { return admissionregistrationv1.NewMutatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedMutatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyBindingInformer(informer MutatingAdmissionPolicyBindingInformer) TypedMutatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &mutatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyBindingTypedInformerAdapter struct { + MutatingAdmissionPolicyBindingInformer +} + +func (a *mutatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding](a.Informer()) +} + +// ToMutatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a MutatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go index d7c48e78a..32f005c25 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go @@ -34,12 +34,40 @@ import ( ) // MutatingWebhookConfigurationInformer provides access to a shared informer and lister for -// MutatingWebhookConfigurations. +// MutatingWebhookConfigurations. Prefer using the type-safe variant (see [TypedMutatingWebhookConfigurationInformer]). type MutatingWebhookConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.MutatingWebhookConfigurationLister } +// TypedMutatingWebhookConfigurationInformer provides access to a shared informer and lister for +// MutatingWebhookConfigurations, including the type-safe TypedInformer variant. +// It is a superset of MutatingWebhookConfigurationInformer. +type TypedMutatingWebhookConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingWebhookConfigurationIndexInformer + Lister() admissionregistrationv1.MutatingWebhookConfigurationLister +} + +// MutatingWebhookConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingWebhookConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationIndexers is a specialization of [cache.TypedIndexers] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + +// DeletedMutatingWebhookConfiguration is a specialization of [cache.DeletedObject] for MutatingWebhookConfiguration. +type DeletedMutatingWebhookConfiguration = cache.DeletedObject[*apiadmissionregistrationv1.MutatingWebhookConfiguration] + type mutatingWebhookConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingWebhookConfigurationInformer struct { // NewMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingWebhookConfigurationInformer]). func NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingWebhookConfigurationIndexers) MutatingWebhookConfigurationIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingWebhookConfigurationInformer]). func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingWebhookConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingWebhookConfigurationIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingWebhookConfigurationInformerWithOptions constructs a new informer for MutatingWebhookConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingWebhookConfigurationInformerWithOptions]). func NewMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, options) +} + +// NewTypedMutatingWebhookConfigurationInformerWithOptions constructs a new informer for MutatingWebhookConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingWebhookConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "mutatingwebhookconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingWebhookConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interf Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.MutatingWebhookConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingWebhookConfigurationInformer) TypedInformer() MutatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingWebhookConfiguration](f.factory.InformerFor(&apiadmissionregistrationv1.MutatingWebhookConfiguration{}, f.defaultInformer)) } func (f *mutatingWebhookConfigurationInformer) Lister() admissionregistrationv1.MutatingWebhookConfigurationLister { return admissionregistrationv1.NewMutatingWebhookConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingWebhookConfigurationInformer converts an untyped informer into a TypedMutatingWebhookConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedMutatingWebhookConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingWebhookConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingWebhookConfigurationInformer(informer MutatingWebhookConfigurationInformer) TypedMutatingWebhookConfigurationInformer { + if informer, ok := informer.(TypedMutatingWebhookConfigurationInformer); ok { + return informer + } + return &mutatingWebhookConfigurationTypedInformerAdapter{informer} +} + +type mutatingWebhookConfigurationTypedInformerAdapter struct { + MutatingWebhookConfigurationInformer +} + +func (a *mutatingWebhookConfigurationTypedInformerAdapter) TypedInformer() MutatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingWebhookConfiguration](a.Informer()) +} + +// ToMutatingWebhookConfigurationIndexInformer converts an untyped informer into a MutatingWebhookConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// MutatingWebhookConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingWebhookConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingWebhookConfigurationIndexInformer(informer cache.SharedIndexInformer) MutatingWebhookConfigurationIndexInformer { + if informer, ok := informer.(MutatingWebhookConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.MutatingWebhookConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicy.go index bdc5c0b28..84017947a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicies. +// ValidatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyInformer]). type ValidatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.ValidatingAdmissionPolicyLister } +// TypedValidatingAdmissionPolicyInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyInformer. +type TypedValidatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1.ValidatingAdmissionPolicyLister +} + +// ValidatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + +// DeletedValidatingAdmissionPolicy is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicy. +type DeletedValidatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1.ValidatingAdmissionPolicy] + type validatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyInformer struct { // NewValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformer]). func NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyInformer]). func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformerWithOptions]). func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "validatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyInformer) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingAdmissionPolicy{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyInformer) Lister() admissionregistrationv1.ValidatingAdmissionPolicyLister { return admissionregistrationv1.NewValidatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyInformer converts an untyped informer into a TypedValidatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyInformer(informer ValidatingAdmissionPolicyInformer) TypedValidatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyInformer); ok { + return informer + } + return &validatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyTypedInformerAdapter struct { + ValidatingAdmissionPolicyInformer +} + +func (a *validatingAdmissionPolicyTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicy](a.Informer()) +} + +// ToValidatingAdmissionPolicyIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicybinding.go index 1ecf9703a..d79eaf541 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicyBindings. +// ValidatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyBindingInformer]). type ValidatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.ValidatingAdmissionPolicyBindingLister } +// TypedValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyBindingInformer. +type TypedValidatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1.ValidatingAdmissionPolicyBindingLister +} + +// ValidatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + +// DeletedValidatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicyBinding. +type DeletedValidatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding] + type validatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyBindingInformer struct { // NewValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformer]). func NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyBindingInformer]). func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformerWithOptions]). func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "validatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.In Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyBindingInformer) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1.ValidatingAdmissionPolicyBindingLister { return admissionregistrationv1.NewValidatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedValidatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyBindingInformer(informer ValidatingAdmissionPolicyBindingInformer) TypedValidatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &validatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyBindingTypedInformerAdapter struct { + ValidatingAdmissionPolicyBindingInformer +} + +func (a *validatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding](a.Informer()) +} + +// ToValidatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go index 07653c35c..98ba6e012 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go @@ -34,12 +34,40 @@ import ( ) // ValidatingWebhookConfigurationInformer provides access to a shared informer and lister for -// ValidatingWebhookConfigurations. +// ValidatingWebhookConfigurations. Prefer using the type-safe variant (see [TypedValidatingWebhookConfigurationInformer]). type ValidatingWebhookConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1.ValidatingWebhookConfigurationLister } +// TypedValidatingWebhookConfigurationInformer provides access to a shared informer and lister for +// ValidatingWebhookConfigurations, including the type-safe TypedInformer variant. +// It is a superset of ValidatingWebhookConfigurationInformer. +type TypedValidatingWebhookConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingWebhookConfigurationIndexInformer + Lister() admissionregistrationv1.ValidatingWebhookConfigurationLister +} + +// ValidatingWebhookConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingWebhookConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationIndexers is a specialization of [cache.TypedIndexers] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationIndexers = cache.TypedIndexers[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + +// DeletedValidatingWebhookConfiguration is a specialization of [cache.DeletedObject] for ValidatingWebhookConfiguration. +type DeletedValidatingWebhookConfiguration = cache.DeletedObject[*apiadmissionregistrationv1.ValidatingWebhookConfiguration] + type validatingWebhookConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingWebhookConfigurationInformer struct { // NewValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingWebhookConfigurationInformer]). func NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingWebhookConfigurationIndexers) ValidatingWebhookConfigurationIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingWebhookConfigurationInformer]). func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingWebhookConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingWebhookConfigurationIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingWebhookConfigurationInformerWithOptions constructs a new informer for ValidatingWebhookConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingWebhookConfigurationInformerWithOptions]). func NewValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, options) +} + +// NewTypedValidatingWebhookConfigurationInformerWithOptions constructs a new informer for ValidatingWebhookConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingWebhookConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1", Resource: "validatingwebhookconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingWebhookConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingWebhookConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingWebhookConfigurationInformer) TypedInformer() ValidatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingWebhookConfiguration](f.factory.InformerFor(&apiadmissionregistrationv1.ValidatingWebhookConfiguration{}, f.defaultInformer)) } func (f *validatingWebhookConfigurationInformer) Lister() admissionregistrationv1.ValidatingWebhookConfigurationLister { return admissionregistrationv1.NewValidatingWebhookConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingWebhookConfigurationInformer converts an untyped informer into a TypedValidatingWebhookConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedValidatingWebhookConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingWebhookConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingWebhookConfigurationInformer(informer ValidatingWebhookConfigurationInformer) TypedValidatingWebhookConfigurationInformer { + if informer, ok := informer.(TypedValidatingWebhookConfigurationInformer); ok { + return informer + } + return &validatingWebhookConfigurationTypedInformerAdapter{informer} +} + +type validatingWebhookConfigurationTypedInformerAdapter struct { + ValidatingWebhookConfigurationInformer +} + +func (a *validatingWebhookConfigurationTypedInformerAdapter) TypedInformer() ValidatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingWebhookConfiguration](a.Informer()) +} + +// ToValidatingWebhookConfigurationIndexInformer converts an untyped informer into a ValidatingWebhookConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// ValidatingWebhookConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingWebhookConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingWebhookConfigurationIndexInformer(informer cache.SharedIndexInformer) ValidatingWebhookConfigurationIndexInformer { + if informer, ok := informer.(ValidatingWebhookConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1.ValidatingWebhookConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go index 68ae4e25c..43702bde9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. - MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer + MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer // MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. - MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer + MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer // ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. - ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer + ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer // ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. - ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer + ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. -func (v *version) MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer { +// MutatingAdmissionPolicies returns a TypedMutatingAdmissionPolicyInformer. +func (v *version) MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer { return &mutatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. -func (v *version) MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer { +// MutatingAdmissionPolicyBindings returns a TypedMutatingAdmissionPolicyBindingInformer. +func (v *version) MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer { return &mutatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. -func (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer { +// ValidatingAdmissionPolicies returns a TypedValidatingAdmissionPolicyInformer. +func (v *version) ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer { return &validatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. -func (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer { +// ValidatingAdmissionPolicyBindings returns a TypedValidatingAdmissionPolicyBindingInformer. +func (v *version) ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer { return &validatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go index 3441d6df4..387e8c904 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicies. +// MutatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyInformer]). type MutatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyLister } +// TypedMutatingAdmissionPolicyInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyInformer. +type TypedMutatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyLister +} + +// MutatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + +// DeletedMutatingAdmissionPolicy is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicy. +type DeletedMutatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy] + type mutatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyInformer struct { // NewMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformer]). func NewMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyInformer]). func NewFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformerWithOptions]). func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1alpha1", Resource: "mutatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyInformer) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyInformer) Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyLister { return admissionregistrationv1alpha1.NewMutatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyInformer converts an untyped informer into a TypedMutatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyInformer(informer MutatingAdmissionPolicyInformer) TypedMutatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyInformer); ok { + return informer + } + return &mutatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyTypedInformerAdapter struct { + MutatingAdmissionPolicyInformer +} + +func (a *mutatingAdmissionPolicyTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy](a.Informer()) +} + +// ToMutatingAdmissionPolicyIndexInformer converts an untyped informer into a MutatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go index 568c91115..b831a8d7a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/mutatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicyBindings. +// MutatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyBindingInformer]). type MutatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyBindingLister } +// TypedMutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyBindingInformer. +type TypedMutatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyBindingLister +} + +// MutatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + +// DeletedMutatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicyBinding. +type DeletedMutatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding] + type mutatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyBindingInformer struct { // NewMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformer]). func NewMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyBindingInformer]). func NewFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformerWithOptions]). func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1alpha1", Resource: "mutatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyBindingInformer) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1alpha1.MutatingAdmissionPolicyBindingLister { return admissionregistrationv1alpha1.NewMutatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedMutatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyBindingInformer(informer MutatingAdmissionPolicyBindingInformer) TypedMutatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &mutatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyBindingTypedInformerAdapter struct { + MutatingAdmissionPolicyBindingInformer +} + +func (a *mutatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding](a.Informer()) +} + +// ToMutatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a MutatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.MutatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go index c86ca6da6..db8efca26 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicies. +// ValidatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyInformer]). type ValidatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyLister } +// TypedValidatingAdmissionPolicyInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyInformer. +type TypedValidatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyLister +} + +// ValidatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + +// DeletedValidatingAdmissionPolicy is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicy. +type DeletedValidatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy] + type validatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyInformer struct { // NewValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformer]). func NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyInformer]). func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformerWithOptions]). func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1alpha1", Resource: "validatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyInformer) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyInformer) Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyLister { return admissionregistrationv1alpha1.NewValidatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyInformer converts an untyped informer into a TypedValidatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyInformer(informer ValidatingAdmissionPolicyInformer) TypedValidatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyInformer); ok { + return informer + } + return &validatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyTypedInformerAdapter struct { + ValidatingAdmissionPolicyInformer +} + +func (a *validatingAdmissionPolicyTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy](a.Informer()) +} + +// ToValidatingAdmissionPolicyIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go index 224049a25..5e1c4acca 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicyBindings. +// ValidatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyBindingInformer]). type ValidatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingLister } +// TypedValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyBindingInformer. +type TypedValidatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingLister +} + +// ValidatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + +// DeletedValidatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicyBinding. +type DeletedValidatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding] + type validatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyBindingInformer struct { // NewValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformer]). func NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyBindingInformer]). func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformerWithOptions]). func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1alpha1", Resource: "validatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.In Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyBindingInformer) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingLister { return admissionregistrationv1alpha1.NewValidatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedValidatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyBindingInformer(informer ValidatingAdmissionPolicyBindingInformer) TypedValidatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &validatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyBindingTypedInformerAdapter struct { + ValidatingAdmissionPolicyBindingInformer +} + +func (a *validatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding](a.Informer()) +} + +// ToValidatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go index 9174fd1c7..fa0818f41 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go @@ -25,17 +25,17 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. - MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer + MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer // MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. - MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer + MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer // MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer. - MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer + MutatingWebhookConfigurations() TypedMutatingWebhookConfigurationInformer // ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. - ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer + ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer // ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. - ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer + ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer // ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer. - ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer + ValidatingWebhookConfigurations() TypedValidatingWebhookConfigurationInformer } type version struct { @@ -49,32 +49,32 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// MutatingAdmissionPolicies returns a MutatingAdmissionPolicyInformer. -func (v *version) MutatingAdmissionPolicies() MutatingAdmissionPolicyInformer { +// MutatingAdmissionPolicies returns a TypedMutatingAdmissionPolicyInformer. +func (v *version) MutatingAdmissionPolicies() TypedMutatingAdmissionPolicyInformer { return &mutatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// MutatingAdmissionPolicyBindings returns a MutatingAdmissionPolicyBindingInformer. -func (v *version) MutatingAdmissionPolicyBindings() MutatingAdmissionPolicyBindingInformer { +// MutatingAdmissionPolicyBindings returns a TypedMutatingAdmissionPolicyBindingInformer. +func (v *version) MutatingAdmissionPolicyBindings() TypedMutatingAdmissionPolicyBindingInformer { return &mutatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer. -func (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer { +// MutatingWebhookConfigurations returns a TypedMutatingWebhookConfigurationInformer. +func (v *version) MutatingWebhookConfigurations() TypedMutatingWebhookConfigurationInformer { return &mutatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer. -func (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer { +// ValidatingAdmissionPolicies returns a TypedValidatingAdmissionPolicyInformer. +func (v *version) ValidatingAdmissionPolicies() TypedValidatingAdmissionPolicyInformer { return &validatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer. -func (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer { +// ValidatingAdmissionPolicyBindings returns a TypedValidatingAdmissionPolicyBindingInformer. +func (v *version) ValidatingAdmissionPolicyBindings() TypedValidatingAdmissionPolicyBindingInformer { return &validatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer. -func (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer { +// ValidatingWebhookConfigurations returns a TypedValidatingWebhookConfigurationInformer. +func (v *version) ValidatingWebhookConfigurations() TypedValidatingWebhookConfigurationInformer { return &validatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicy.go index edfe94417..5eaff9989 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicies. +// MutatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyInformer]). type MutatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyLister } +// TypedMutatingAdmissionPolicyInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyInformer. +type TypedMutatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyLister +} + +// MutatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + +// MutatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicy. +type MutatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + +// DeletedMutatingAdmissionPolicy is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicy. +type DeletedMutatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy] + type mutatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyInformer struct { // NewMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformer]). func NewMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyInformer]). func NewFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyInformer constructs a new informer for MutatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyInformerWithOptions]). func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyInformerWithOptions constructs a new informer for MutatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "mutatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyInformer) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingAdmissionPolicy{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyInformer) Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyLister { return admissionregistrationv1beta1.NewMutatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyInformer converts an untyped informer into a TypedMutatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyInformer(informer MutatingAdmissionPolicyInformer) TypedMutatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyInformer); ok { + return informer + } + return &mutatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyTypedInformerAdapter struct { + MutatingAdmissionPolicyInformer +} + +func (a *mutatingAdmissionPolicyTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy](a.Informer()) +} + +// ToMutatingAdmissionPolicyIndexInformer converts an untyped informer into a MutatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go index bb833f444..6422d2f7f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // MutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// MutatingAdmissionPolicyBindings. +// MutatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedMutatingAdmissionPolicyBindingInformer]). type MutatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyBindingLister } +// TypedMutatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// MutatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of MutatingAdmissionPolicyBindingInformer. +type TypedMutatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyBindingLister +} + +// MutatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + +// MutatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for MutatingAdmissionPolicyBinding. +type MutatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + +// DeletedMutatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for MutatingAdmissionPolicyBinding. +type DeletedMutatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding] + type mutatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingAdmissionPolicyBindingInformer struct { // NewMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformer]). func NewMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingAdmissionPolicyBindingInformer]). func NewFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingAdmissionPolicyBindingInformer constructs a new informer for MutatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingAdmissionPolicyBindingIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingAdmissionPolicyBindingInformerWithOptions]). func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedMutatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for MutatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "mutatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingAdmissionPolicyBindingInformer) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *mutatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1beta1.MutatingAdmissionPolicyBindingLister { return admissionregistrationv1beta1.NewMutatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedMutatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedMutatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingAdmissionPolicyBindingInformer(informer MutatingAdmissionPolicyBindingInformer) TypedMutatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedMutatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &mutatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type mutatingAdmissionPolicyBindingTypedInformerAdapter struct { + MutatingAdmissionPolicyBindingInformer +} + +func (a *mutatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() MutatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding](a.Informer()) +} + +// ToMutatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a MutatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// MutatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) MutatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(MutatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go index bb077a174..2aef3f296 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go @@ -34,12 +34,40 @@ import ( ) // MutatingWebhookConfigurationInformer provides access to a shared informer and lister for -// MutatingWebhookConfigurations. +// MutatingWebhookConfigurations. Prefer using the type-safe variant (see [TypedMutatingWebhookConfigurationInformer]). type MutatingWebhookConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.MutatingWebhookConfigurationLister } +// TypedMutatingWebhookConfigurationInformer provides access to a shared informer and lister for +// MutatingWebhookConfigurations, including the type-safe TypedInformer variant. +// It is a superset of MutatingWebhookConfigurationInformer. +type TypedMutatingWebhookConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() MutatingWebhookConfigurationIndexInformer + Lister() admissionregistrationv1beta1.MutatingWebhookConfigurationLister +} + +// MutatingWebhookConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type MutatingWebhookConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + +// MutatingWebhookConfigurationIndexers is a specialization of [cache.TypedIndexers] for MutatingWebhookConfiguration. +type MutatingWebhookConfigurationIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + +// DeletedMutatingWebhookConfiguration is a specialization of [cache.DeletedObject] for MutatingWebhookConfiguration. +type DeletedMutatingWebhookConfiguration = cache.DeletedObject[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration] + type mutatingWebhookConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type mutatingWebhookConfigurationInformer struct { // NewMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingWebhookConfigurationInformer]). func NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingWebhookConfigurationIndexers) MutatingWebhookConfigurationIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredMutatingWebhookConfigurationInformer]). func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers MutatingWebhookConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) MutatingWebhookConfigurationIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewMutatingWebhookConfigurationInformerWithOptions constructs a new informer for MutatingWebhookConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedMutatingWebhookConfigurationInformerWithOptions]). func NewMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, options) +} + +// NewTypedMutatingWebhookConfigurationInformerWithOptions constructs a new informer for MutatingWebhookConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) MutatingWebhookConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "mutatingwebhookconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewMutatingWebhookConfigurationInformerWithOptions(client kubernetes.Interf Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedMutatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingWebhookConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *mutatingWebhookConfigurationInformer) TypedInformer() MutatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration](f.factory.InformerFor(&apiadmissionregistrationv1beta1.MutatingWebhookConfiguration{}, f.defaultInformer)) } func (f *mutatingWebhookConfigurationInformer) Lister() admissionregistrationv1beta1.MutatingWebhookConfigurationLister { return admissionregistrationv1beta1.NewMutatingWebhookConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedMutatingWebhookConfigurationInformer converts an untyped informer into a TypedMutatingWebhookConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedMutatingWebhookConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedMutatingWebhookConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedMutatingWebhookConfigurationInformer(informer MutatingWebhookConfigurationInformer) TypedMutatingWebhookConfigurationInformer { + if informer, ok := informer.(TypedMutatingWebhookConfigurationInformer); ok { + return informer + } + return &mutatingWebhookConfigurationTypedInformerAdapter{informer} +} + +type mutatingWebhookConfigurationTypedInformerAdapter struct { + MutatingWebhookConfigurationInformer +} + +func (a *mutatingWebhookConfigurationTypedInformerAdapter) TypedInformer() MutatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration](a.Informer()) +} + +// ToMutatingWebhookConfigurationIndexInformer converts an untyped informer into a MutatingWebhookConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *MutatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// MutatingWebhookConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a MutatingWebhookConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToMutatingWebhookConfigurationIndexInformer(informer cache.SharedIndexInformer) MutatingWebhookConfigurationIndexInformer { + if informer, ok := informer.(MutatingWebhookConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.MutatingWebhookConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go index a88a254d6..2a4f9ad12 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicy.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicies. +// ValidatingAdmissionPolicies. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyInformer]). type ValidatingAdmissionPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyLister } +// TypedValidatingAdmissionPolicyInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicies, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyInformer. +type TypedValidatingAdmissionPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyIndexInformer + Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyLister +} + +// ValidatingAdmissionPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + +// ValidatingAdmissionPolicyIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicy. +type ValidatingAdmissionPolicyIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + +// DeletedValidatingAdmissionPolicy is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicy. +type DeletedValidatingAdmissionPolicy = cache.DeletedObject[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy] + type validatingAdmissionPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyInformer struct { // NewValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformer]). func NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyInformer]). func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyInformerWithOptions]). func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyInformerWithOptions constructs a new informer for ValidatingAdmissionPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingadmissionpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyInformer) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy](f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyInformer) Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyLister { return admissionregistrationv1beta1.NewValidatingAdmissionPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyInformer converts an untyped informer into a TypedValidatingAdmissionPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyInformer(informer ValidatingAdmissionPolicyInformer) TypedValidatingAdmissionPolicyInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyInformer); ok { + return informer + } + return &validatingAdmissionPolicyTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyTypedInformerAdapter struct { + ValidatingAdmissionPolicyInformer +} + +func (a *validatingAdmissionPolicyTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy](a.Informer()) +} + +// ToValidatingAdmissionPolicyIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicy. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go index d1df5a3f2..2cbc29ac5 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingadmissionpolicybinding.go @@ -34,12 +34,40 @@ import ( ) // ValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for -// ValidatingAdmissionPolicyBindings. +// ValidatingAdmissionPolicyBindings. Prefer using the type-safe variant (see [TypedValidatingAdmissionPolicyBindingInformer]). type ValidatingAdmissionPolicyBindingInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyBindingLister } +// TypedValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for +// ValidatingAdmissionPolicyBindings, including the type-safe TypedInformer variant. +// It is a superset of ValidatingAdmissionPolicyBindingInformer. +type TypedValidatingAdmissionPolicyBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer + Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyBindingLister +} + +// ValidatingAdmissionPolicyBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingAdmissionPolicyBindingIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + +// ValidatingAdmissionPolicyBindingIndexers is a specialization of [cache.TypedIndexers] for ValidatingAdmissionPolicyBinding. +type ValidatingAdmissionPolicyBindingIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + +// DeletedValidatingAdmissionPolicyBinding is a specialization of [cache.DeletedObject] for ValidatingAdmissionPolicyBinding. +type DeletedValidatingAdmissionPolicyBinding = cache.DeletedObject[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding] + type validatingAdmissionPolicyBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingAdmissionPolicyBindingInformer struct { // NewValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformer]). func NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingAdmissionPolicyBindingInformer]). func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingAdmissionPolicyBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingAdmissionPolicyBindingIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingAdmissionPolicyBindingInformerWithOptions]). func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, options) +} + +// NewTypedValidatingAdmissionPolicyBindingInformerWithOptions constructs a new informer for ValidatingAdmissionPolicyBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingAdmissionPolicyBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingadmissionpolicybindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingAdmissionPolicyBindingInformerWithOptions(client kubernetes.In Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingAdmissionPolicyBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingAdmissionPolicyBindingInformer) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding](f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer)) } func (f *validatingAdmissionPolicyBindingInformer) Lister() admissionregistrationv1beta1.ValidatingAdmissionPolicyBindingLister { return admissionregistrationv1beta1.NewValidatingAdmissionPolicyBindingLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingAdmissionPolicyBindingInformer converts an untyped informer into a TypedValidatingAdmissionPolicyBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// TypedValidatingAdmissionPolicyBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingAdmissionPolicyBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingAdmissionPolicyBindingInformer(informer ValidatingAdmissionPolicyBindingInformer) TypedValidatingAdmissionPolicyBindingInformer { + if informer, ok := informer.(TypedValidatingAdmissionPolicyBindingInformer); ok { + return informer + } + return &validatingAdmissionPolicyBindingTypedInformerAdapter{informer} +} + +type validatingAdmissionPolicyBindingTypedInformerAdapter struct { + ValidatingAdmissionPolicyBindingInformer +} + +func (a *validatingAdmissionPolicyBindingTypedInformerAdapter) TypedInformer() ValidatingAdmissionPolicyBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding](a.Informer()) +} + +// ToValidatingAdmissionPolicyBindingIndexInformer converts an untyped informer into a ValidatingAdmissionPolicyBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingAdmissionPolicyBinding. If that is not the case, calling type-safe methods of the returned +// ValidatingAdmissionPolicyBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingAdmissionPolicyBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingAdmissionPolicyBindingIndexInformer(informer cache.SharedIndexInformer) ValidatingAdmissionPolicyBindingIndexInformer { + if informer, ok := informer.(ValidatingAdmissionPolicyBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingAdmissionPolicyBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go index 41852cb03..b7497aaca 100644 --- a/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go @@ -34,12 +34,40 @@ import ( ) // ValidatingWebhookConfigurationInformer provides access to a shared informer and lister for -// ValidatingWebhookConfigurations. +// ValidatingWebhookConfigurations. Prefer using the type-safe variant (see [TypedValidatingWebhookConfigurationInformer]). type ValidatingWebhookConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() admissionregistrationv1beta1.ValidatingWebhookConfigurationLister } +// TypedValidatingWebhookConfigurationInformer provides access to a shared informer and lister for +// ValidatingWebhookConfigurations, including the type-safe TypedInformer variant. +// It is a superset of ValidatingWebhookConfigurationInformer. +type TypedValidatingWebhookConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ValidatingWebhookConfigurationIndexInformer + Lister() admissionregistrationv1beta1.ValidatingWebhookConfigurationLister +} + +// ValidatingWebhookConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ValidatingWebhookConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + +// ValidatingWebhookConfigurationIndexers is a specialization of [cache.TypedIndexers] for ValidatingWebhookConfiguration. +type ValidatingWebhookConfigurationIndexers = cache.TypedIndexers[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + +// DeletedValidatingWebhookConfiguration is a specialization of [cache.DeletedObject] for ValidatingWebhookConfiguration. +type DeletedValidatingWebhookConfiguration = cache.DeletedObject[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration] + type validatingWebhookConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type validatingWebhookConfigurationInformer struct { // NewValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingWebhookConfigurationInformer]). func NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingWebhookConfigurationIndexers) ValidatingWebhookConfigurationIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredValidatingWebhookConfigurationInformer]). func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ValidatingWebhookConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ValidatingWebhookConfigurationIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewValidatingWebhookConfigurationInformerWithOptions constructs a new informer for ValidatingWebhookConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedValidatingWebhookConfigurationInformerWithOptions]). func NewValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, options) +} + +// NewTypedValidatingWebhookConfigurationInformerWithOptions constructs a new informer for ValidatingWebhookConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ValidatingWebhookConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingwebhookconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewValidatingWebhookConfigurationInformerWithOptions(client kubernetes.Inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedValidatingWebhookConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *validatingWebhookConfigurationInformer) TypedInformer() ValidatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration](f.factory.InformerFor(&apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration{}, f.defaultInformer)) } func (f *validatingWebhookConfigurationInformer) Lister() admissionregistrationv1beta1.ValidatingWebhookConfigurationLister { return admissionregistrationv1beta1.NewValidatingWebhookConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedValidatingWebhookConfigurationInformer converts an untyped informer into a TypedValidatingWebhookConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedValidatingWebhookConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedValidatingWebhookConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedValidatingWebhookConfigurationInformer(informer ValidatingWebhookConfigurationInformer) TypedValidatingWebhookConfigurationInformer { + if informer, ok := informer.(TypedValidatingWebhookConfigurationInformer); ok { + return informer + } + return &validatingWebhookConfigurationTypedInformerAdapter{informer} +} + +type validatingWebhookConfigurationTypedInformerAdapter struct { + ValidatingWebhookConfigurationInformer +} + +func (a *validatingWebhookConfigurationTypedInformerAdapter) TypedInformer() ValidatingWebhookConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration](a.Informer()) +} + +// ToValidatingWebhookConfigurationIndexInformer converts an untyped informer into a ValidatingWebhookConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ValidatingWebhookConfiguration. If that is not the case, calling type-safe methods of the returned +// ValidatingWebhookConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ValidatingWebhookConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToValidatingWebhookConfigurationIndexInformer(informer cache.SharedIndexInformer) ValidatingWebhookConfigurationIndexInformer { + if informer, ok := informer.(ValidatingWebhookConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiadmissionregistrationv1beta1.ValidatingWebhookConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go index 9778325c6..5b6f5eafc 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // StorageVersions returns a StorageVersionInformer. - StorageVersions() StorageVersionInformer + StorageVersions() TypedStorageVersionInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// StorageVersions returns a StorageVersionInformer. -func (v *version) StorageVersions() StorageVersionInformer { +// StorageVersions returns a TypedStorageVersionInformer. +func (v *version) StorageVersions() TypedStorageVersionInformer { return &storageVersionInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go b/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go index 6d164a317..c4ce84fb2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go +++ b/constraint/vendor/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go @@ -34,12 +34,40 @@ import ( ) // StorageVersionInformer provides access to a shared informer and lister for -// StorageVersions. +// StorageVersions. Prefer using the type-safe variant (see [TypedStorageVersionInformer]). type StorageVersionInformer interface { Informer() cache.SharedIndexInformer Lister() apiserverinternalv1alpha1.StorageVersionLister } +// TypedStorageVersionInformer provides access to a shared informer and lister for +// StorageVersions, including the type-safe TypedInformer variant. +// It is a superset of StorageVersionInformer. +type TypedStorageVersionInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StorageVersionIndexInformer + Lister() apiserverinternalv1alpha1.StorageVersionLister +} + +// StorageVersionIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StorageVersionIndexInformer cache.TypedSharedIndexInformer[*apiapiserverinternalv1alpha1.StorageVersion] + +// StorageVersionHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StorageVersion. +type StorageVersionHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiapiserverinternalv1alpha1.StorageVersion] + +// StorageVersionDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StorageVersion. +type StorageVersionDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiapiserverinternalv1alpha1.StorageVersion] + +// StorageVersionFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StorageVersion. +type StorageVersionFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiapiserverinternalv1alpha1.StorageVersion] + +// StorageVersionIndexers is a specialization of [cache.TypedIndexers] for StorageVersion. +type StorageVersionIndexers = cache.TypedIndexers[*apiapiserverinternalv1alpha1.StorageVersion] + +// DeletedStorageVersion is a specialization of [cache.DeletedObject] for StorageVersion. +type DeletedStorageVersion = cache.DeletedObject[*apiapiserverinternalv1alpha1.StorageVersion] + type storageVersionInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type storageVersionInformer struct { // NewStorageVersionInformer constructs a new informer for StorageVersion type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionInformer]). func NewStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStorageVersionInformer constructs a new informer for StorageVersion type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionIndexers) StorageVersionIndexInformer { + return NewTypedStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStorageVersionInformer constructs a new informer for StorageVersion type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStorageVersionInformer]). func NewFilteredStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStorageVersionInformer constructs a new informer for StorageVersion type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StorageVersionIndexInformer { + return NewTypedStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStorageVersionInformerWithOptions constructs a new informer for StorageVersion type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionInformerWithOptions]). func NewStorageVersionInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStorageVersionInformerWithOptions(client, options) +} + +// NewTypedStorageVersionInformerWithOptions constructs a new informer for StorageVersion type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) StorageVersionIndexInformer { gvr := schema.GroupVersionResource{Group: "internal.apiserver.k8s.io", Version: "v1alpha1", Resource: "storageversions"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiapiserverinternalv1alpha1.StorageVersion](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewStorageVersionInformerWithOptions(client kubernetes.Interface, options i Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *storageVersionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStorageVersionInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *storageVersionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiapiserverinternalv1alpha1.StorageVersion{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *storageVersionInformer) TypedInformer() StorageVersionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiapiserverinternalv1alpha1.StorageVersion](f.factory.InformerFor(&apiapiserverinternalv1alpha1.StorageVersion{}, f.defaultInformer)) } func (f *storageVersionInformer) Lister() apiserverinternalv1alpha1.StorageVersionLister { return apiserverinternalv1alpha1.NewStorageVersionLister(f.Informer().GetIndexer()) } + +// ToTypedStorageVersionInformer converts an untyped informer into a TypedStorageVersionInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersion. If that is not the case, calling type-safe methods of the returned +// TypedStorageVersionInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStorageVersionInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStorageVersionInformer(informer StorageVersionInformer) TypedStorageVersionInformer { + if informer, ok := informer.(TypedStorageVersionInformer); ok { + return informer + } + return &storageVersionTypedInformerAdapter{informer} +} + +type storageVersionTypedInformerAdapter struct { + StorageVersionInformer +} + +func (a *storageVersionTypedInformerAdapter) TypedInformer() StorageVersionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiapiserverinternalv1alpha1.StorageVersion](a.Informer()) +} + +// ToStorageVersionIndexInformer converts an untyped informer into a StorageVersionIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersion. If that is not the case, calling type-safe methods of the returned +// StorageVersionIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StorageVersionIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStorageVersionIndexInformer(informer cache.SharedIndexInformer) StorageVersionIndexInformer { + if informer, ok := informer.(StorageVersionIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiapiserverinternalv1alpha1.StorageVersion](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/controllerrevision.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/controllerrevision.go index f58da53f1..86a7796c8 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/controllerrevision.go @@ -34,12 +34,40 @@ import ( ) // ControllerRevisionInformer provides access to a shared informer and lister for -// ControllerRevisions. +// ControllerRevisions. Prefer using the type-safe variant (see [TypedControllerRevisionInformer]). type ControllerRevisionInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1.ControllerRevisionLister } +// TypedControllerRevisionInformer provides access to a shared informer and lister for +// ControllerRevisions, including the type-safe TypedInformer variant. +// It is a superset of ControllerRevisionInformer. +type TypedControllerRevisionInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ControllerRevisionIndexInformer + Lister() appsv1.ControllerRevisionLister +} + +// ControllerRevisionIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ControllerRevisionIndexInformer cache.TypedSharedIndexInformer[*apiappsv1.ControllerRevision] + +// ControllerRevisionHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ControllerRevision. +type ControllerRevisionHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1.ControllerRevision] + +// ControllerRevisionDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ControllerRevision. +type ControllerRevisionDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1.ControllerRevision] + +// ControllerRevisionFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ControllerRevision. +type ControllerRevisionFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1.ControllerRevision] + +// ControllerRevisionIndexers is a specialization of [cache.TypedIndexers] for ControllerRevision. +type ControllerRevisionIndexers = cache.TypedIndexers[*apiappsv1.ControllerRevision] + +// DeletedControllerRevision is a specialization of [cache.DeletedObject] for ControllerRevision. +type DeletedControllerRevision = cache.DeletedObject[*apiappsv1.ControllerRevision] + type controllerRevisionInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type controllerRevisionInformer struct { // NewControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformer]). func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredControllerRevisionInformer]). func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformerWithOptions]). func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, options) +} + +// NewTypedControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ControllerRevisionIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "controllerrevisions"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1.ControllerRevision](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1.ControllerRevision{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *controllerRevisionInformer) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.ControllerRevision](f.factory.InformerFor(&apiappsv1.ControllerRevision{}, f.defaultInformer)) } func (f *controllerRevisionInformer) Lister() appsv1.ControllerRevisionLister { return appsv1.NewControllerRevisionLister(f.Informer().GetIndexer()) } + +// ToTypedControllerRevisionInformer converts an untyped informer into a TypedControllerRevisionInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// TypedControllerRevisionInformer leads to runtime panics. A safer alternative is to pass +// around a TypedControllerRevisionInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedControllerRevisionInformer(informer ControllerRevisionInformer) TypedControllerRevisionInformer { + if informer, ok := informer.(TypedControllerRevisionInformer); ok { + return informer + } + return &controllerRevisionTypedInformerAdapter{informer} +} + +type controllerRevisionTypedInformerAdapter struct { + ControllerRevisionInformer +} + +func (a *controllerRevisionTypedInformerAdapter) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.ControllerRevision](a.Informer()) +} + +// ToControllerRevisionIndexInformer converts an untyped informer into a ControllerRevisionIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// ControllerRevisionIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ControllerRevisionIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToControllerRevisionIndexInformer(informer cache.SharedIndexInformer) ControllerRevisionIndexInformer { + if informer, ok := informer.(ControllerRevisionIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1.ControllerRevision](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/daemonset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/daemonset.go index dbdc40124..110fbdbcc 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/daemonset.go @@ -34,12 +34,40 @@ import ( ) // DaemonSetInformer provides access to a shared informer and lister for -// DaemonSets. +// DaemonSets. Prefer using the type-safe variant (see [TypedDaemonSetInformer]). type DaemonSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1.DaemonSetLister } +// TypedDaemonSetInformer provides access to a shared informer and lister for +// DaemonSets, including the type-safe TypedInformer variant. +// It is a superset of DaemonSetInformer. +type TypedDaemonSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DaemonSetIndexInformer + Lister() appsv1.DaemonSetLister +} + +// DaemonSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DaemonSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1.DaemonSet] + +// DaemonSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DaemonSet. +type DaemonSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1.DaemonSet] + +// DaemonSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DaemonSet. +type DaemonSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1.DaemonSet] + +// DaemonSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DaemonSet. +type DaemonSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1.DaemonSet] + +// DaemonSetIndexers is a specialization of [cache.TypedIndexers] for DaemonSet. +type DaemonSetIndexers = cache.TypedIndexers[*apiappsv1.DaemonSet] + +// DeletedDaemonSet is a specialization of [cache.DeletedObject] for DaemonSet. +type DeletedDaemonSet = cache.DeletedObject[*apiappsv1.DaemonSet] + type daemonSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type daemonSetInformer struct { // NewDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformer]). func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDaemonSetInformer]). func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformerWithOptions]). func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, options) +} + +// NewTypedDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DaemonSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "daemonsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1.DaemonSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace stri Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *daemonSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1.DaemonSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *daemonSetInformer) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.DaemonSet](f.factory.InformerFor(&apiappsv1.DaemonSet{}, f.defaultInformer)) } func (f *daemonSetInformer) Lister() appsv1.DaemonSetLister { return appsv1.NewDaemonSetLister(f.Informer().GetIndexer()) } + +// ToTypedDaemonSetInformer converts an untyped informer into a TypedDaemonSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// TypedDaemonSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDaemonSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDaemonSetInformer(informer DaemonSetInformer) TypedDaemonSetInformer { + if informer, ok := informer.(TypedDaemonSetInformer); ok { + return informer + } + return &daemonSetTypedInformerAdapter{informer} +} + +type daemonSetTypedInformerAdapter struct { + DaemonSetInformer +} + +func (a *daemonSetTypedInformerAdapter) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.DaemonSet](a.Informer()) +} + +// ToDaemonSetIndexInformer converts an untyped informer into a DaemonSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// DaemonSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DaemonSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDaemonSetIndexInformer(informer cache.SharedIndexInformer) DaemonSetIndexInformer { + if informer, ok := informer.(DaemonSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1.DaemonSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/deployment.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/deployment.go index dbf4df6a8..1079bc190 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/deployment.go @@ -34,12 +34,40 @@ import ( ) // DeploymentInformer provides access to a shared informer and lister for -// Deployments. +// Deployments. Prefer using the type-safe variant (see [TypedDeploymentInformer]). type DeploymentInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1.DeploymentLister } +// TypedDeploymentInformer provides access to a shared informer and lister for +// Deployments, including the type-safe TypedInformer variant. +// It is a superset of DeploymentInformer. +type TypedDeploymentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeploymentIndexInformer + Lister() appsv1.DeploymentLister +} + +// DeploymentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeploymentIndexInformer cache.TypedSharedIndexInformer[*apiappsv1.Deployment] + +// DeploymentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Deployment. +type DeploymentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1.Deployment] + +// DeploymentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Deployment. +type DeploymentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1.Deployment] + +// DeploymentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Deployment. +type DeploymentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1.Deployment] + +// DeploymentIndexers is a specialization of [cache.TypedIndexers] for Deployment. +type DeploymentIndexers = cache.TypedIndexers[*apiappsv1.Deployment] + +// DeletedDeployment is a specialization of [cache.DeletedObject] for Deployment. +type DeletedDeployment = cache.DeletedObject[*apiappsv1.Deployment] + type deploymentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type deploymentInformer struct { // NewDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformer]). func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeploymentInformer]). func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformerWithOptions]). func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, options) +} + +// NewTypedDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DeploymentIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1.Deployment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deploymentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1.Deployment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deploymentInformer) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.Deployment](f.factory.InformerFor(&apiappsv1.Deployment{}, f.defaultInformer)) } func (f *deploymentInformer) Lister() appsv1.DeploymentLister { return appsv1.NewDeploymentLister(f.Informer().GetIndexer()) } + +// ToTypedDeploymentInformer converts an untyped informer into a TypedDeploymentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// TypedDeploymentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeploymentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeploymentInformer(informer DeploymentInformer) TypedDeploymentInformer { + if informer, ok := informer.(TypedDeploymentInformer); ok { + return informer + } + return &deploymentTypedInformerAdapter{informer} +} + +type deploymentTypedInformerAdapter struct { + DeploymentInformer +} + +func (a *deploymentTypedInformerAdapter) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.Deployment](a.Informer()) +} + +// ToDeploymentIndexInformer converts an untyped informer into a DeploymentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// DeploymentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeploymentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeploymentIndexInformer(informer cache.SharedIndexInformer) DeploymentIndexInformer { + if informer, ok := informer.(DeploymentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1.Deployment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/interface.go index fab1e76bd..d8e4e3bf1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/interface.go @@ -25,15 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ControllerRevisions returns a ControllerRevisionInformer. - ControllerRevisions() ControllerRevisionInformer + ControllerRevisions() TypedControllerRevisionInformer // DaemonSets returns a DaemonSetInformer. - DaemonSets() DaemonSetInformer + DaemonSets() TypedDaemonSetInformer // Deployments returns a DeploymentInformer. - Deployments() DeploymentInformer + Deployments() TypedDeploymentInformer // ReplicaSets returns a ReplicaSetInformer. - ReplicaSets() ReplicaSetInformer + ReplicaSets() TypedReplicaSetInformer // StatefulSets returns a StatefulSetInformer. - StatefulSets() StatefulSetInformer + StatefulSets() TypedStatefulSetInformer } type version struct { @@ -47,27 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ControllerRevisions returns a ControllerRevisionInformer. -func (v *version) ControllerRevisions() ControllerRevisionInformer { +// ControllerRevisions returns a TypedControllerRevisionInformer. +func (v *version) ControllerRevisions() TypedControllerRevisionInformer { return &controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// DaemonSets returns a DaemonSetInformer. -func (v *version) DaemonSets() DaemonSetInformer { +// DaemonSets returns a TypedDaemonSetInformer. +func (v *version) DaemonSets() TypedDaemonSetInformer { return &daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Deployments returns a DeploymentInformer. -func (v *version) Deployments() DeploymentInformer { +// Deployments returns a TypedDeploymentInformer. +func (v *version) Deployments() TypedDeploymentInformer { return &deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ReplicaSets returns a ReplicaSetInformer. -func (v *version) ReplicaSets() ReplicaSetInformer { +// ReplicaSets returns a TypedReplicaSetInformer. +func (v *version) ReplicaSets() TypedReplicaSetInformer { return &replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// StatefulSets returns a StatefulSetInformer. -func (v *version) StatefulSets() StatefulSetInformer { +// StatefulSets returns a TypedStatefulSetInformer. +func (v *version) StatefulSets() TypedStatefulSetInformer { return &statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/replicaset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/replicaset.go index 1115e5adc..13983f2a7 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/replicaset.go @@ -34,12 +34,40 @@ import ( ) // ReplicaSetInformer provides access to a shared informer and lister for -// ReplicaSets. +// ReplicaSets. Prefer using the type-safe variant (see [TypedReplicaSetInformer]). type ReplicaSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1.ReplicaSetLister } +// TypedReplicaSetInformer provides access to a shared informer and lister for +// ReplicaSets, including the type-safe TypedInformer variant. +// It is a superset of ReplicaSetInformer. +type TypedReplicaSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ReplicaSetIndexInformer + Lister() appsv1.ReplicaSetLister +} + +// ReplicaSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ReplicaSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1.ReplicaSet] + +// ReplicaSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ReplicaSet. +type ReplicaSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1.ReplicaSet] + +// ReplicaSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ReplicaSet. +type ReplicaSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1.ReplicaSet] + +// ReplicaSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ReplicaSet. +type ReplicaSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1.ReplicaSet] + +// ReplicaSetIndexers is a specialization of [cache.TypedIndexers] for ReplicaSet. +type ReplicaSetIndexers = cache.TypedIndexers[*apiappsv1.ReplicaSet] + +// DeletedReplicaSet is a specialization of [cache.DeletedObject] for ReplicaSet. +type DeletedReplicaSet = cache.DeletedObject[*apiappsv1.ReplicaSet] + type replicaSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type replicaSetInformer struct { // NewReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformer]). func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredReplicaSetInformer]). func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformerWithOptions]). func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, options) +} + +// NewTypedReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ReplicaSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "replicasets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1.ReplicaSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *replicaSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1.ReplicaSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *replicaSetInformer) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.ReplicaSet](f.factory.InformerFor(&apiappsv1.ReplicaSet{}, f.defaultInformer)) } func (f *replicaSetInformer) Lister() appsv1.ReplicaSetLister { return appsv1.NewReplicaSetLister(f.Informer().GetIndexer()) } + +// ToTypedReplicaSetInformer converts an untyped informer into a TypedReplicaSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// TypedReplicaSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedReplicaSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedReplicaSetInformer(informer ReplicaSetInformer) TypedReplicaSetInformer { + if informer, ok := informer.(TypedReplicaSetInformer); ok { + return informer + } + return &replicaSetTypedInformerAdapter{informer} +} + +type replicaSetTypedInformerAdapter struct { + ReplicaSetInformer +} + +func (a *replicaSetTypedInformerAdapter) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.ReplicaSet](a.Informer()) +} + +// ToReplicaSetIndexInformer converts an untyped informer into a ReplicaSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// ReplicaSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ReplicaSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToReplicaSetIndexInformer(informer cache.SharedIndexInformer) ReplicaSetIndexInformer { + if informer, ok := informer.(ReplicaSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1.ReplicaSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1/statefulset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1/statefulset.go index 998251ede..64c766e15 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1/statefulset.go @@ -34,12 +34,40 @@ import ( ) // StatefulSetInformer provides access to a shared informer and lister for -// StatefulSets. +// StatefulSets. Prefer using the type-safe variant (see [TypedStatefulSetInformer]). type StatefulSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1.StatefulSetLister } +// TypedStatefulSetInformer provides access to a shared informer and lister for +// StatefulSets, including the type-safe TypedInformer variant. +// It is a superset of StatefulSetInformer. +type TypedStatefulSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StatefulSetIndexInformer + Lister() appsv1.StatefulSetLister +} + +// StatefulSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StatefulSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1.StatefulSet] + +// StatefulSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StatefulSet. +type StatefulSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1.StatefulSet] + +// StatefulSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StatefulSet. +type StatefulSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1.StatefulSet] + +// StatefulSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StatefulSet. +type StatefulSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1.StatefulSet] + +// StatefulSetIndexers is a specialization of [cache.TypedIndexers] for StatefulSet. +type StatefulSetIndexers = cache.TypedIndexers[*apiappsv1.StatefulSet] + +// DeletedStatefulSet is a specialization of [cache.DeletedObject] for StatefulSet. +type DeletedStatefulSet = cache.DeletedObject[*apiappsv1.StatefulSet] + type statefulSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type statefulSetInformer struct { // NewStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformer]). func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStatefulSetInformer]). func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformerWithOptions]). func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, options) +} + +// NewTypedStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) StatefulSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "statefulsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1.StatefulSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *statefulSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1.StatefulSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *statefulSetInformer) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.StatefulSet](f.factory.InformerFor(&apiappsv1.StatefulSet{}, f.defaultInformer)) } func (f *statefulSetInformer) Lister() appsv1.StatefulSetLister { return appsv1.NewStatefulSetLister(f.Informer().GetIndexer()) } + +// ToTypedStatefulSetInformer converts an untyped informer into a TypedStatefulSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// TypedStatefulSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStatefulSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStatefulSetInformer(informer StatefulSetInformer) TypedStatefulSetInformer { + if informer, ok := informer.(TypedStatefulSetInformer); ok { + return informer + } + return &statefulSetTypedInformerAdapter{informer} +} + +type statefulSetTypedInformerAdapter struct { + StatefulSetInformer +} + +func (a *statefulSetTypedInformerAdapter) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1.StatefulSet](a.Informer()) +} + +// ToStatefulSetIndexInformer converts an untyped informer into a StatefulSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// StatefulSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StatefulSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStatefulSetIndexInformer(informer cache.SharedIndexInformer) StatefulSetIndexInformer { + if informer, ok := informer.(StatefulSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1.StatefulSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go index ee3b156e0..02215f900 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go @@ -34,12 +34,40 @@ import ( ) // ControllerRevisionInformer provides access to a shared informer and lister for -// ControllerRevisions. +// ControllerRevisions. Prefer using the type-safe variant (see [TypedControllerRevisionInformer]). type ControllerRevisionInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta1.ControllerRevisionLister } +// TypedControllerRevisionInformer provides access to a shared informer and lister for +// ControllerRevisions, including the type-safe TypedInformer variant. +// It is a superset of ControllerRevisionInformer. +type TypedControllerRevisionInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ControllerRevisionIndexInformer + Lister() appsv1beta1.ControllerRevisionLister +} + +// ControllerRevisionIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ControllerRevisionIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta1.ControllerRevision] + +// ControllerRevisionHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ControllerRevision. +type ControllerRevisionHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta1.ControllerRevision] + +// ControllerRevisionDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ControllerRevision. +type ControllerRevisionDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta1.ControllerRevision] + +// ControllerRevisionFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ControllerRevision. +type ControllerRevisionFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta1.ControllerRevision] + +// ControllerRevisionIndexers is a specialization of [cache.TypedIndexers] for ControllerRevision. +type ControllerRevisionIndexers = cache.TypedIndexers[*apiappsv1beta1.ControllerRevision] + +// DeletedControllerRevision is a specialization of [cache.DeletedObject] for ControllerRevision. +type DeletedControllerRevision = cache.DeletedObject[*apiappsv1beta1.ControllerRevision] + type controllerRevisionInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type controllerRevisionInformer struct { // NewControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformer]). func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredControllerRevisionInformer]). func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformerWithOptions]). func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, options) +} + +// NewTypedControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ControllerRevisionIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta1", Resource: "controllerrevisions"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.ControllerRevision](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta1.ControllerRevision{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *controllerRevisionInformer) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.ControllerRevision](f.factory.InformerFor(&apiappsv1beta1.ControllerRevision{}, f.defaultInformer)) } func (f *controllerRevisionInformer) Lister() appsv1beta1.ControllerRevisionLister { return appsv1beta1.NewControllerRevisionLister(f.Informer().GetIndexer()) } + +// ToTypedControllerRevisionInformer converts an untyped informer into a TypedControllerRevisionInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// TypedControllerRevisionInformer leads to runtime panics. A safer alternative is to pass +// around a TypedControllerRevisionInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedControllerRevisionInformer(informer ControllerRevisionInformer) TypedControllerRevisionInformer { + if informer, ok := informer.(TypedControllerRevisionInformer); ok { + return informer + } + return &controllerRevisionTypedInformerAdapter{informer} +} + +type controllerRevisionTypedInformerAdapter struct { + ControllerRevisionInformer +} + +func (a *controllerRevisionTypedInformerAdapter) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.ControllerRevision](a.Informer()) +} + +// ToControllerRevisionIndexInformer converts an untyped informer into a ControllerRevisionIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// ControllerRevisionIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ControllerRevisionIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToControllerRevisionIndexInformer(informer cache.SharedIndexInformer) ControllerRevisionIndexInformer { + if informer, ok := informer.(ControllerRevisionIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.ControllerRevision](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/deployment.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/deployment.go index 699375e3e..c29a3b39b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/deployment.go @@ -34,12 +34,40 @@ import ( ) // DeploymentInformer provides access to a shared informer and lister for -// Deployments. +// Deployments. Prefer using the type-safe variant (see [TypedDeploymentInformer]). type DeploymentInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta1.DeploymentLister } +// TypedDeploymentInformer provides access to a shared informer and lister for +// Deployments, including the type-safe TypedInformer variant. +// It is a superset of DeploymentInformer. +type TypedDeploymentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeploymentIndexInformer + Lister() appsv1beta1.DeploymentLister +} + +// DeploymentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeploymentIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta1.Deployment] + +// DeploymentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Deployment. +type DeploymentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta1.Deployment] + +// DeploymentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Deployment. +type DeploymentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta1.Deployment] + +// DeploymentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Deployment. +type DeploymentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta1.Deployment] + +// DeploymentIndexers is a specialization of [cache.TypedIndexers] for Deployment. +type DeploymentIndexers = cache.TypedIndexers[*apiappsv1beta1.Deployment] + +// DeletedDeployment is a specialization of [cache.DeletedObject] for Deployment. +type DeletedDeployment = cache.DeletedObject[*apiappsv1beta1.Deployment] + type deploymentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type deploymentInformer struct { // NewDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformer]). func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeploymentInformer]). func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformerWithOptions]). func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, options) +} + +// NewTypedDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DeploymentIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta1", Resource: "deployments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.Deployment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deploymentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta1.Deployment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deploymentInformer) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.Deployment](f.factory.InformerFor(&apiappsv1beta1.Deployment{}, f.defaultInformer)) } func (f *deploymentInformer) Lister() appsv1beta1.DeploymentLister { return appsv1beta1.NewDeploymentLister(f.Informer().GetIndexer()) } + +// ToTypedDeploymentInformer converts an untyped informer into a TypedDeploymentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// TypedDeploymentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeploymentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeploymentInformer(informer DeploymentInformer) TypedDeploymentInformer { + if informer, ok := informer.(TypedDeploymentInformer); ok { + return informer + } + return &deploymentTypedInformerAdapter{informer} +} + +type deploymentTypedInformerAdapter struct { + DeploymentInformer +} + +func (a *deploymentTypedInformerAdapter) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.Deployment](a.Informer()) +} + +// ToDeploymentIndexInformer converts an untyped informer into a DeploymentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// DeploymentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeploymentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeploymentIndexInformer(informer cache.SharedIndexInformer) DeploymentIndexInformer { + if informer, ok := informer.(DeploymentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.Deployment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/interface.go index 326939cd1..4a4d87e93 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/interface.go @@ -25,11 +25,11 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ControllerRevisions returns a ControllerRevisionInformer. - ControllerRevisions() ControllerRevisionInformer + ControllerRevisions() TypedControllerRevisionInformer // Deployments returns a DeploymentInformer. - Deployments() DeploymentInformer + Deployments() TypedDeploymentInformer // StatefulSets returns a StatefulSetInformer. - StatefulSets() StatefulSetInformer + StatefulSets() TypedStatefulSetInformer } type version struct { @@ -43,17 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ControllerRevisions returns a ControllerRevisionInformer. -func (v *version) ControllerRevisions() ControllerRevisionInformer { +// ControllerRevisions returns a TypedControllerRevisionInformer. +func (v *version) ControllerRevisions() TypedControllerRevisionInformer { return &controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Deployments returns a DeploymentInformer. -func (v *version) Deployments() DeploymentInformer { +// Deployments returns a TypedDeploymentInformer. +func (v *version) Deployments() TypedDeploymentInformer { return &deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// StatefulSets returns a StatefulSetInformer. -func (v *version) StatefulSets() StatefulSetInformer { +// StatefulSets returns a TypedStatefulSetInformer. +func (v *version) StatefulSets() TypedStatefulSetInformer { return &statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/statefulset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/statefulset.go index 480e68f9d..ad9dc2d3b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta1/statefulset.go @@ -34,12 +34,40 @@ import ( ) // StatefulSetInformer provides access to a shared informer and lister for -// StatefulSets. +// StatefulSets. Prefer using the type-safe variant (see [TypedStatefulSetInformer]). type StatefulSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta1.StatefulSetLister } +// TypedStatefulSetInformer provides access to a shared informer and lister for +// StatefulSets, including the type-safe TypedInformer variant. +// It is a superset of StatefulSetInformer. +type TypedStatefulSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StatefulSetIndexInformer + Lister() appsv1beta1.StatefulSetLister +} + +// StatefulSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StatefulSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta1.StatefulSet] + +// StatefulSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StatefulSet. +type StatefulSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta1.StatefulSet] + +// StatefulSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StatefulSet. +type StatefulSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta1.StatefulSet] + +// StatefulSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StatefulSet. +type StatefulSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta1.StatefulSet] + +// StatefulSetIndexers is a specialization of [cache.TypedIndexers] for StatefulSet. +type StatefulSetIndexers = cache.TypedIndexers[*apiappsv1beta1.StatefulSet] + +// DeletedStatefulSet is a specialization of [cache.DeletedObject] for StatefulSet. +type DeletedStatefulSet = cache.DeletedObject[*apiappsv1beta1.StatefulSet] + type statefulSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type statefulSetInformer struct { // NewStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformer]). func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStatefulSetInformer]). func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformerWithOptions]). func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, options) +} + +// NewTypedStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) StatefulSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta1", Resource: "statefulsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.StatefulSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *statefulSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta1.StatefulSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *statefulSetInformer) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.StatefulSet](f.factory.InformerFor(&apiappsv1beta1.StatefulSet{}, f.defaultInformer)) } func (f *statefulSetInformer) Lister() appsv1beta1.StatefulSetLister { return appsv1beta1.NewStatefulSetLister(f.Informer().GetIndexer()) } + +// ToTypedStatefulSetInformer converts an untyped informer into a TypedStatefulSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// TypedStatefulSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStatefulSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStatefulSetInformer(informer StatefulSetInformer) TypedStatefulSetInformer { + if informer, ok := informer.(TypedStatefulSetInformer); ok { + return informer + } + return &statefulSetTypedInformerAdapter{informer} +} + +type statefulSetTypedInformerAdapter struct { + StatefulSetInformer +} + +func (a *statefulSetTypedInformerAdapter) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.StatefulSet](a.Informer()) +} + +// ToStatefulSetIndexInformer converts an untyped informer into a StatefulSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// StatefulSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StatefulSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStatefulSetIndexInformer(informer cache.SharedIndexInformer) StatefulSetIndexInformer { + if informer, ok := informer.(StatefulSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta1.StatefulSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go index 41e3bf156..0d686ae44 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go @@ -34,12 +34,40 @@ import ( ) // ControllerRevisionInformer provides access to a shared informer and lister for -// ControllerRevisions. +// ControllerRevisions. Prefer using the type-safe variant (see [TypedControllerRevisionInformer]). type ControllerRevisionInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta2.ControllerRevisionLister } +// TypedControllerRevisionInformer provides access to a shared informer and lister for +// ControllerRevisions, including the type-safe TypedInformer variant. +// It is a superset of ControllerRevisionInformer. +type TypedControllerRevisionInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ControllerRevisionIndexInformer + Lister() appsv1beta2.ControllerRevisionLister +} + +// ControllerRevisionIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ControllerRevisionIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta2.ControllerRevision] + +// ControllerRevisionHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ControllerRevision. +type ControllerRevisionHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta2.ControllerRevision] + +// ControllerRevisionDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ControllerRevision. +type ControllerRevisionDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta2.ControllerRevision] + +// ControllerRevisionFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ControllerRevision. +type ControllerRevisionFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta2.ControllerRevision] + +// ControllerRevisionIndexers is a specialization of [cache.TypedIndexers] for ControllerRevision. +type ControllerRevisionIndexers = cache.TypedIndexers[*apiappsv1beta2.ControllerRevision] + +// DeletedControllerRevision is a specialization of [cache.DeletedObject] for ControllerRevision. +type DeletedControllerRevision = cache.DeletedObject[*apiappsv1beta2.ControllerRevision] + type controllerRevisionInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type controllerRevisionInformer struct { // NewControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformer]). func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredControllerRevisionInformer]). func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ControllerRevisionIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ControllerRevisionIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedControllerRevisionInformerWithOptions]). func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedControllerRevisionInformerWithOptions(client, namespace, options) +} + +// NewTypedControllerRevisionInformerWithOptions constructs a new informer for ControllerRevision type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedControllerRevisionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ControllerRevisionIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta2", Resource: "controllerrevisions"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ControllerRevision](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewControllerRevisionInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedControllerRevisionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta2.ControllerRevision{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *controllerRevisionInformer) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ControllerRevision](f.factory.InformerFor(&apiappsv1beta2.ControllerRevision{}, f.defaultInformer)) } func (f *controllerRevisionInformer) Lister() appsv1beta2.ControllerRevisionLister { return appsv1beta2.NewControllerRevisionLister(f.Informer().GetIndexer()) } + +// ToTypedControllerRevisionInformer converts an untyped informer into a TypedControllerRevisionInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// TypedControllerRevisionInformer leads to runtime panics. A safer alternative is to pass +// around a TypedControllerRevisionInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedControllerRevisionInformer(informer ControllerRevisionInformer) TypedControllerRevisionInformer { + if informer, ok := informer.(TypedControllerRevisionInformer); ok { + return informer + } + return &controllerRevisionTypedInformerAdapter{informer} +} + +type controllerRevisionTypedInformerAdapter struct { + ControllerRevisionInformer +} + +func (a *controllerRevisionTypedInformerAdapter) TypedInformer() ControllerRevisionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ControllerRevision](a.Informer()) +} + +// ToControllerRevisionIndexInformer converts an untyped informer into a ControllerRevisionIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ControllerRevision. If that is not the case, calling type-safe methods of the returned +// ControllerRevisionIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ControllerRevisionIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToControllerRevisionIndexInformer(informer cache.SharedIndexInformer) ControllerRevisionIndexInformer { + if informer, ok := informer.(ControllerRevisionIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ControllerRevision](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/daemonset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/daemonset.go index 5c339a78a..16c73e28f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/daemonset.go @@ -34,12 +34,40 @@ import ( ) // DaemonSetInformer provides access to a shared informer and lister for -// DaemonSets. +// DaemonSets. Prefer using the type-safe variant (see [TypedDaemonSetInformer]). type DaemonSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta2.DaemonSetLister } +// TypedDaemonSetInformer provides access to a shared informer and lister for +// DaemonSets, including the type-safe TypedInformer variant. +// It is a superset of DaemonSetInformer. +type TypedDaemonSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DaemonSetIndexInformer + Lister() appsv1beta2.DaemonSetLister +} + +// DaemonSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DaemonSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta2.DaemonSet] + +// DaemonSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DaemonSet. +type DaemonSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta2.DaemonSet] + +// DaemonSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DaemonSet. +type DaemonSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta2.DaemonSet] + +// DaemonSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DaemonSet. +type DaemonSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta2.DaemonSet] + +// DaemonSetIndexers is a specialization of [cache.TypedIndexers] for DaemonSet. +type DaemonSetIndexers = cache.TypedIndexers[*apiappsv1beta2.DaemonSet] + +// DeletedDaemonSet is a specialization of [cache.DeletedObject] for DaemonSet. +type DeletedDaemonSet = cache.DeletedObject[*apiappsv1beta2.DaemonSet] + type daemonSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type daemonSetInformer struct { // NewDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformer]). func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDaemonSetInformer]). func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformerWithOptions]). func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, options) +} + +// NewTypedDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DaemonSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta2", Resource: "daemonsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.DaemonSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace stri Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *daemonSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta2.DaemonSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *daemonSetInformer) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.DaemonSet](f.factory.InformerFor(&apiappsv1beta2.DaemonSet{}, f.defaultInformer)) } func (f *daemonSetInformer) Lister() appsv1beta2.DaemonSetLister { return appsv1beta2.NewDaemonSetLister(f.Informer().GetIndexer()) } + +// ToTypedDaemonSetInformer converts an untyped informer into a TypedDaemonSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// TypedDaemonSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDaemonSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDaemonSetInformer(informer DaemonSetInformer) TypedDaemonSetInformer { + if informer, ok := informer.(TypedDaemonSetInformer); ok { + return informer + } + return &daemonSetTypedInformerAdapter{informer} +} + +type daemonSetTypedInformerAdapter struct { + DaemonSetInformer +} + +func (a *daemonSetTypedInformerAdapter) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.DaemonSet](a.Informer()) +} + +// ToDaemonSetIndexInformer converts an untyped informer into a DaemonSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// DaemonSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DaemonSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDaemonSetIndexInformer(informer cache.SharedIndexInformer) DaemonSetIndexInformer { + if informer, ok := informer.(DaemonSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.DaemonSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/deployment.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/deployment.go index 1e0b64cb2..04743e327 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/deployment.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/deployment.go @@ -34,12 +34,40 @@ import ( ) // DeploymentInformer provides access to a shared informer and lister for -// Deployments. +// Deployments. Prefer using the type-safe variant (see [TypedDeploymentInformer]). type DeploymentInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta2.DeploymentLister } +// TypedDeploymentInformer provides access to a shared informer and lister for +// Deployments, including the type-safe TypedInformer variant. +// It is a superset of DeploymentInformer. +type TypedDeploymentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeploymentIndexInformer + Lister() appsv1beta2.DeploymentLister +} + +// DeploymentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeploymentIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta2.Deployment] + +// DeploymentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Deployment. +type DeploymentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta2.Deployment] + +// DeploymentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Deployment. +type DeploymentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta2.Deployment] + +// DeploymentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Deployment. +type DeploymentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta2.Deployment] + +// DeploymentIndexers is a specialization of [cache.TypedIndexers] for Deployment. +type DeploymentIndexers = cache.TypedIndexers[*apiappsv1beta2.Deployment] + +// DeletedDeployment is a specialization of [cache.DeletedObject] for Deployment. +type DeletedDeployment = cache.DeletedObject[*apiappsv1beta2.Deployment] + type deploymentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type deploymentInformer struct { // NewDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformer]). func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeploymentInformer]). func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformerWithOptions]). func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, options) +} + +// NewTypedDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DeploymentIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta2", Resource: "deployments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.Deployment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deploymentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta2.Deployment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deploymentInformer) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.Deployment](f.factory.InformerFor(&apiappsv1beta2.Deployment{}, f.defaultInformer)) } func (f *deploymentInformer) Lister() appsv1beta2.DeploymentLister { return appsv1beta2.NewDeploymentLister(f.Informer().GetIndexer()) } + +// ToTypedDeploymentInformer converts an untyped informer into a TypedDeploymentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// TypedDeploymentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeploymentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeploymentInformer(informer DeploymentInformer) TypedDeploymentInformer { + if informer, ok := informer.(TypedDeploymentInformer); ok { + return informer + } + return &deploymentTypedInformerAdapter{informer} +} + +type deploymentTypedInformerAdapter struct { + DeploymentInformer +} + +func (a *deploymentTypedInformerAdapter) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.Deployment](a.Informer()) +} + +// ToDeploymentIndexInformer converts an untyped informer into a DeploymentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// DeploymentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeploymentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeploymentIndexInformer(informer cache.SharedIndexInformer) DeploymentIndexInformer { + if informer, ok := informer.(DeploymentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.Deployment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/interface.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/interface.go index ded89bd5b..b00e797b9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/interface.go @@ -25,15 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ControllerRevisions returns a ControllerRevisionInformer. - ControllerRevisions() ControllerRevisionInformer + ControllerRevisions() TypedControllerRevisionInformer // DaemonSets returns a DaemonSetInformer. - DaemonSets() DaemonSetInformer + DaemonSets() TypedDaemonSetInformer // Deployments returns a DeploymentInformer. - Deployments() DeploymentInformer + Deployments() TypedDeploymentInformer // ReplicaSets returns a ReplicaSetInformer. - ReplicaSets() ReplicaSetInformer + ReplicaSets() TypedReplicaSetInformer // StatefulSets returns a StatefulSetInformer. - StatefulSets() StatefulSetInformer + StatefulSets() TypedStatefulSetInformer } type version struct { @@ -47,27 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ControllerRevisions returns a ControllerRevisionInformer. -func (v *version) ControllerRevisions() ControllerRevisionInformer { +// ControllerRevisions returns a TypedControllerRevisionInformer. +func (v *version) ControllerRevisions() TypedControllerRevisionInformer { return &controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// DaemonSets returns a DaemonSetInformer. -func (v *version) DaemonSets() DaemonSetInformer { +// DaemonSets returns a TypedDaemonSetInformer. +func (v *version) DaemonSets() TypedDaemonSetInformer { return &daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Deployments returns a DeploymentInformer. -func (v *version) Deployments() DeploymentInformer { +// Deployments returns a TypedDeploymentInformer. +func (v *version) Deployments() TypedDeploymentInformer { return &deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ReplicaSets returns a ReplicaSetInformer. -func (v *version) ReplicaSets() ReplicaSetInformer { +// ReplicaSets returns a TypedReplicaSetInformer. +func (v *version) ReplicaSets() TypedReplicaSetInformer { return &replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// StatefulSets returns a StatefulSetInformer. -func (v *version) StatefulSets() StatefulSetInformer { +// StatefulSets returns a TypedStatefulSetInformer. +func (v *version) StatefulSets() TypedStatefulSetInformer { return &statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/replicaset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/replicaset.go index 425ad5533..3ee75c162 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/replicaset.go @@ -34,12 +34,40 @@ import ( ) // ReplicaSetInformer provides access to a shared informer and lister for -// ReplicaSets. +// ReplicaSets. Prefer using the type-safe variant (see [TypedReplicaSetInformer]). type ReplicaSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta2.ReplicaSetLister } +// TypedReplicaSetInformer provides access to a shared informer and lister for +// ReplicaSets, including the type-safe TypedInformer variant. +// It is a superset of ReplicaSetInformer. +type TypedReplicaSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ReplicaSetIndexInformer + Lister() appsv1beta2.ReplicaSetLister +} + +// ReplicaSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ReplicaSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta2.ReplicaSet] + +// ReplicaSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ReplicaSet. +type ReplicaSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta2.ReplicaSet] + +// ReplicaSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ReplicaSet. +type ReplicaSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta2.ReplicaSet] + +// ReplicaSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ReplicaSet. +type ReplicaSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta2.ReplicaSet] + +// ReplicaSetIndexers is a specialization of [cache.TypedIndexers] for ReplicaSet. +type ReplicaSetIndexers = cache.TypedIndexers[*apiappsv1beta2.ReplicaSet] + +// DeletedReplicaSet is a specialization of [cache.DeletedObject] for ReplicaSet. +type DeletedReplicaSet = cache.DeletedObject[*apiappsv1beta2.ReplicaSet] + type replicaSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type replicaSetInformer struct { // NewReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformer]). func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredReplicaSetInformer]). func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformerWithOptions]). func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, options) +} + +// NewTypedReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ReplicaSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta2", Resource: "replicasets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ReplicaSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *replicaSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta2.ReplicaSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *replicaSetInformer) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ReplicaSet](f.factory.InformerFor(&apiappsv1beta2.ReplicaSet{}, f.defaultInformer)) } func (f *replicaSetInformer) Lister() appsv1beta2.ReplicaSetLister { return appsv1beta2.NewReplicaSetLister(f.Informer().GetIndexer()) } + +// ToTypedReplicaSetInformer converts an untyped informer into a TypedReplicaSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// TypedReplicaSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedReplicaSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedReplicaSetInformer(informer ReplicaSetInformer) TypedReplicaSetInformer { + if informer, ok := informer.(TypedReplicaSetInformer); ok { + return informer + } + return &replicaSetTypedInformerAdapter{informer} +} + +type replicaSetTypedInformerAdapter struct { + ReplicaSetInformer +} + +func (a *replicaSetTypedInformerAdapter) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ReplicaSet](a.Informer()) +} + +// ToReplicaSetIndexInformer converts an untyped informer into a ReplicaSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// ReplicaSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ReplicaSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToReplicaSetIndexInformer(informer cache.SharedIndexInformer) ReplicaSetIndexInformer { + if informer, ok := informer.(ReplicaSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.ReplicaSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/statefulset.go b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/statefulset.go index 0fb22661c..4b449a9c3 100644 --- a/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/statefulset.go +++ b/constraint/vendor/k8s.io/client-go/informers/apps/v1beta2/statefulset.go @@ -34,12 +34,40 @@ import ( ) // StatefulSetInformer provides access to a shared informer and lister for -// StatefulSets. +// StatefulSets. Prefer using the type-safe variant (see [TypedStatefulSetInformer]). type StatefulSetInformer interface { Informer() cache.SharedIndexInformer Lister() appsv1beta2.StatefulSetLister } +// TypedStatefulSetInformer provides access to a shared informer and lister for +// StatefulSets, including the type-safe TypedInformer variant. +// It is a superset of StatefulSetInformer. +type TypedStatefulSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StatefulSetIndexInformer + Lister() appsv1beta2.StatefulSetLister +} + +// StatefulSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StatefulSetIndexInformer cache.TypedSharedIndexInformer[*apiappsv1beta2.StatefulSet] + +// StatefulSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StatefulSet. +type StatefulSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiappsv1beta2.StatefulSet] + +// StatefulSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StatefulSet. +type StatefulSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiappsv1beta2.StatefulSet] + +// StatefulSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StatefulSet. +type StatefulSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiappsv1beta2.StatefulSet] + +// StatefulSetIndexers is a specialization of [cache.TypedIndexers] for StatefulSet. +type StatefulSetIndexers = cache.TypedIndexers[*apiappsv1beta2.StatefulSet] + +// DeletedStatefulSet is a specialization of [cache.DeletedObject] for StatefulSet. +type DeletedStatefulSet = cache.DeletedObject[*apiappsv1beta2.StatefulSet] + type statefulSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type statefulSetInformer struct { // NewStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformer]). func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStatefulSetInformer]). func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStatefulSetInformer constructs a new informer for StatefulSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers StatefulSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StatefulSetIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStatefulSetInformerWithOptions]). func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStatefulSetInformerWithOptions(client, namespace, options) +} + +// NewTypedStatefulSetInformerWithOptions constructs a new informer for StatefulSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStatefulSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) StatefulSetIndexInformer { gvr := schema.GroupVersionResource{Group: "apps", Version: "v1beta2", Resource: "statefulsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.StatefulSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewStatefulSetInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStatefulSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *statefulSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiappsv1beta2.StatefulSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *statefulSetInformer) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.StatefulSet](f.factory.InformerFor(&apiappsv1beta2.StatefulSet{}, f.defaultInformer)) } func (f *statefulSetInformer) Lister() appsv1beta2.StatefulSetLister { return appsv1beta2.NewStatefulSetLister(f.Informer().GetIndexer()) } + +// ToTypedStatefulSetInformer converts an untyped informer into a TypedStatefulSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// TypedStatefulSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStatefulSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStatefulSetInformer(informer StatefulSetInformer) TypedStatefulSetInformer { + if informer, ok := informer.(TypedStatefulSetInformer); ok { + return informer + } + return &statefulSetTypedInformerAdapter{informer} +} + +type statefulSetTypedInformerAdapter struct { + StatefulSetInformer +} + +func (a *statefulSetTypedInformerAdapter) TypedInformer() StatefulSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.StatefulSet](a.Informer()) +} + +// ToStatefulSetIndexInformer converts an untyped informer into a StatefulSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StatefulSet. If that is not the case, calling type-safe methods of the returned +// StatefulSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StatefulSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStatefulSetIndexInformer(informer cache.SharedIndexInformer) StatefulSetIndexInformer { + if informer, ok := informer.(StatefulSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiappsv1beta2.StatefulSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go index e49b03524..e8b5eb54f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go +++ b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go @@ -34,12 +34,40 @@ import ( ) // HorizontalPodAutoscalerInformer provides access to a shared informer and lister for -// HorizontalPodAutoscalers. +// HorizontalPodAutoscalers. Prefer using the type-safe variant (see [TypedHorizontalPodAutoscalerInformer]). type HorizontalPodAutoscalerInformer interface { Informer() cache.SharedIndexInformer Lister() autoscalingv1.HorizontalPodAutoscalerLister } +// TypedHorizontalPodAutoscalerInformer provides access to a shared informer and lister for +// HorizontalPodAutoscalers, including the type-safe TypedInformer variant. +// It is a superset of HorizontalPodAutoscalerInformer. +type TypedHorizontalPodAutoscalerInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() HorizontalPodAutoscalerIndexInformer + Lister() autoscalingv1.HorizontalPodAutoscalerLister +} + +// HorizontalPodAutoscalerIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type HorizontalPodAutoscalerIndexInformer cache.TypedSharedIndexInformer[*apiautoscalingv1.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiautoscalingv1.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiautoscalingv1.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiautoscalingv1.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerIndexers is a specialization of [cache.TypedIndexers] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerIndexers = cache.TypedIndexers[*apiautoscalingv1.HorizontalPodAutoscaler] + +// DeletedHorizontalPodAutoscaler is a specialization of [cache.DeletedObject] for HorizontalPodAutoscaler. +type DeletedHorizontalPodAutoscaler = cache.DeletedObject[*apiautoscalingv1.HorizontalPodAutoscaler] + type horizontalPodAutoscalerInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type horizontalPodAutoscalerInformer struct { // NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedHorizontalPodAutoscalerInformer]). func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers HorizontalPodAutoscalerIndexers) HorizontalPodAutoscalerIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredHorizontalPodAutoscalerInformer]). func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers HorizontalPodAutoscalerIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) HorizontalPodAutoscalerIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewHorizontalPodAutoscalerInformerWithOptions constructs a new informer for HorizontalPodAutoscaler type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedHorizontalPodAutoscalerInformerWithOptions]). func NewHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, options) +} + +// NewTypedHorizontalPodAutoscalerInformerWithOptions constructs a new informer for HorizontalPodAutoscaler type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) HorizontalPodAutoscalerIndexInformer { gvr := schema.GroupVersionResource{Group: "autoscaling", Version: "v1", Resource: "horizontalpodautoscalers"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiautoscalingv1.HorizontalPodAutoscaler](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewHorizontalPodAutoscalerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiautoscalingv1.HorizontalPodAutoscaler{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *horizontalPodAutoscalerInformer) TypedInformer() HorizontalPodAutoscalerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiautoscalingv1.HorizontalPodAutoscaler](f.factory.InformerFor(&apiautoscalingv1.HorizontalPodAutoscaler{}, f.defaultInformer)) } func (f *horizontalPodAutoscalerInformer) Lister() autoscalingv1.HorizontalPodAutoscalerLister { return autoscalingv1.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer()) } + +// ToTypedHorizontalPodAutoscalerInformer converts an untyped informer into a TypedHorizontalPodAutoscalerInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *HorizontalPodAutoscaler. If that is not the case, calling type-safe methods of the returned +// TypedHorizontalPodAutoscalerInformer leads to runtime panics. A safer alternative is to pass +// around a TypedHorizontalPodAutoscalerInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedHorizontalPodAutoscalerInformer(informer HorizontalPodAutoscalerInformer) TypedHorizontalPodAutoscalerInformer { + if informer, ok := informer.(TypedHorizontalPodAutoscalerInformer); ok { + return informer + } + return &horizontalPodAutoscalerTypedInformerAdapter{informer} +} + +type horizontalPodAutoscalerTypedInformerAdapter struct { + HorizontalPodAutoscalerInformer +} + +func (a *horizontalPodAutoscalerTypedInformerAdapter) TypedInformer() HorizontalPodAutoscalerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiautoscalingv1.HorizontalPodAutoscaler](a.Informer()) +} + +// ToHorizontalPodAutoscalerIndexInformer converts an untyped informer into a HorizontalPodAutoscalerIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *HorizontalPodAutoscaler. If that is not the case, calling type-safe methods of the returned +// HorizontalPodAutoscalerIndexInformer leads to runtime panics. A safer alternative is to pass +// around a HorizontalPodAutoscalerIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToHorizontalPodAutoscalerIndexInformer(informer cache.SharedIndexInformer) HorizontalPodAutoscalerIndexInformer { + if informer, ok := informer.(HorizontalPodAutoscalerIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiautoscalingv1.HorizontalPodAutoscaler](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/interface.go index 601d0f77f..730ca89c2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer. - HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer + HorizontalPodAutoscalers() TypedHorizontalPodAutoscalerInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer. -func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer { +// HorizontalPodAutoscalers returns a TypedHorizontalPodAutoscalerInformer. +func (v *version) HorizontalPodAutoscalers() TypedHorizontalPodAutoscalerInformer { return &horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go index 3605718d0..dbdac3f6d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go +++ b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go @@ -34,12 +34,40 @@ import ( ) // HorizontalPodAutoscalerInformer provides access to a shared informer and lister for -// HorizontalPodAutoscalers. +// HorizontalPodAutoscalers. Prefer using the type-safe variant (see [TypedHorizontalPodAutoscalerInformer]). type HorizontalPodAutoscalerInformer interface { Informer() cache.SharedIndexInformer Lister() autoscalingv2.HorizontalPodAutoscalerLister } +// TypedHorizontalPodAutoscalerInformer provides access to a shared informer and lister for +// HorizontalPodAutoscalers, including the type-safe TypedInformer variant. +// It is a superset of HorizontalPodAutoscalerInformer. +type TypedHorizontalPodAutoscalerInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() HorizontalPodAutoscalerIndexInformer + Lister() autoscalingv2.HorizontalPodAutoscalerLister +} + +// HorizontalPodAutoscalerIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type HorizontalPodAutoscalerIndexInformer cache.TypedSharedIndexInformer[*apiautoscalingv2.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiautoscalingv2.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiautoscalingv2.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiautoscalingv2.HorizontalPodAutoscaler] + +// HorizontalPodAutoscalerIndexers is a specialization of [cache.TypedIndexers] for HorizontalPodAutoscaler. +type HorizontalPodAutoscalerIndexers = cache.TypedIndexers[*apiautoscalingv2.HorizontalPodAutoscaler] + +// DeletedHorizontalPodAutoscaler is a specialization of [cache.DeletedObject] for HorizontalPodAutoscaler. +type DeletedHorizontalPodAutoscaler = cache.DeletedObject[*apiautoscalingv2.HorizontalPodAutoscaler] + type horizontalPodAutoscalerInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type horizontalPodAutoscalerInformer struct { // NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedHorizontalPodAutoscalerInformer]). func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers HorizontalPodAutoscalerIndexers) HorizontalPodAutoscalerIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredHorizontalPodAutoscalerInformer]). func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers HorizontalPodAutoscalerIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) HorizontalPodAutoscalerIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewHorizontalPodAutoscalerInformerWithOptions constructs a new informer for HorizontalPodAutoscaler type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedHorizontalPodAutoscalerInformerWithOptions]). func NewHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, namespace, options) +} + +// NewTypedHorizontalPodAutoscalerInformerWithOptions constructs a new informer for HorizontalPodAutoscaler type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) HorizontalPodAutoscalerIndexInformer { gvr := schema.GroupVersionResource{Group: "autoscaling", Version: "v2", Resource: "horizontalpodautoscalers"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiautoscalingv2.HorizontalPodAutoscaler](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewHorizontalPodAutoscalerInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewHorizontalPodAutoscalerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedHorizontalPodAutoscalerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiautoscalingv2.HorizontalPodAutoscaler{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *horizontalPodAutoscalerInformer) TypedInformer() HorizontalPodAutoscalerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiautoscalingv2.HorizontalPodAutoscaler](f.factory.InformerFor(&apiautoscalingv2.HorizontalPodAutoscaler{}, f.defaultInformer)) } func (f *horizontalPodAutoscalerInformer) Lister() autoscalingv2.HorizontalPodAutoscalerLister { return autoscalingv2.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer()) } + +// ToTypedHorizontalPodAutoscalerInformer converts an untyped informer into a TypedHorizontalPodAutoscalerInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *HorizontalPodAutoscaler. If that is not the case, calling type-safe methods of the returned +// TypedHorizontalPodAutoscalerInformer leads to runtime panics. A safer alternative is to pass +// around a TypedHorizontalPodAutoscalerInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedHorizontalPodAutoscalerInformer(informer HorizontalPodAutoscalerInformer) TypedHorizontalPodAutoscalerInformer { + if informer, ok := informer.(TypedHorizontalPodAutoscalerInformer); ok { + return informer + } + return &horizontalPodAutoscalerTypedInformerAdapter{informer} +} + +type horizontalPodAutoscalerTypedInformerAdapter struct { + HorizontalPodAutoscalerInformer +} + +func (a *horizontalPodAutoscalerTypedInformerAdapter) TypedInformer() HorizontalPodAutoscalerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiautoscalingv2.HorizontalPodAutoscaler](a.Informer()) +} + +// ToHorizontalPodAutoscalerIndexInformer converts an untyped informer into a HorizontalPodAutoscalerIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *HorizontalPodAutoscaler. If that is not the case, calling type-safe methods of the returned +// HorizontalPodAutoscalerIndexInformer leads to runtime panics. A safer alternative is to pass +// around a HorizontalPodAutoscalerIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToHorizontalPodAutoscalerIndexInformer(informer cache.SharedIndexInformer) HorizontalPodAutoscalerIndexInformer { + if informer, ok := informer.(HorizontalPodAutoscalerIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiautoscalingv2.HorizontalPodAutoscaler](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/interface.go b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/interface.go index 2c71908e4..e8b2d1493 100644 --- a/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/autoscaling/v2/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer. - HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer + HorizontalPodAutoscalers() TypedHorizontalPodAutoscalerInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer. -func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer { +// HorizontalPodAutoscalers returns a TypedHorizontalPodAutoscalerInformer. +func (v *version) HorizontalPodAutoscalers() TypedHorizontalPodAutoscalerInformer { return &horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/batch/v1/cronjob.go b/constraint/vendor/k8s.io/client-go/informers/batch/v1/cronjob.go index 022710011..bbd8ebf64 100644 --- a/constraint/vendor/k8s.io/client-go/informers/batch/v1/cronjob.go +++ b/constraint/vendor/k8s.io/client-go/informers/batch/v1/cronjob.go @@ -34,12 +34,40 @@ import ( ) // CronJobInformer provides access to a shared informer and lister for -// CronJobs. +// CronJobs. Prefer using the type-safe variant (see [TypedCronJobInformer]). type CronJobInformer interface { Informer() cache.SharedIndexInformer Lister() batchv1.CronJobLister } +// TypedCronJobInformer provides access to a shared informer and lister for +// CronJobs, including the type-safe TypedInformer variant. +// It is a superset of CronJobInformer. +type TypedCronJobInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CronJobIndexInformer + Lister() batchv1.CronJobLister +} + +// CronJobIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CronJobIndexInformer cache.TypedSharedIndexInformer[*apibatchv1.CronJob] + +// CronJobHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CronJob. +type CronJobHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apibatchv1.CronJob] + +// CronJobDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CronJob. +type CronJobDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apibatchv1.CronJob] + +// CronJobFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CronJob. +type CronJobFilteringHandler = cache.TypedFilteringResourceEventHandler[*apibatchv1.CronJob] + +// CronJobIndexers is a specialization of [cache.TypedIndexers] for CronJob. +type CronJobIndexers = cache.TypedIndexers[*apibatchv1.CronJob] + +// DeletedCronJob is a specialization of [cache.DeletedObject] for CronJob. +type DeletedCronJob = cache.DeletedObject[*apibatchv1.CronJob] + type cronJobInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type cronJobInformer struct { // NewCronJobInformer constructs a new informer for CronJob type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCronJobInformer]). func NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCronJobInformer constructs a new informer for CronJob type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CronJobIndexers) CronJobIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCronJobInformer constructs a new informer for CronJob type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCronJobInformer]). func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCronJobInformer constructs a new informer for CronJob type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CronJobIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CronJobIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCronJobInformerWithOptions constructs a new informer for CronJob type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCronJobInformerWithOptions]). func NewCronJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, options) +} + +// NewTypedCronJobInformerWithOptions constructs a new informer for CronJob type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCronJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CronJobIndexInformer { gvr := schema.GroupVersionResource{Group: "batch", Version: "v1", Resource: "cronjobs"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apibatchv1.CronJob](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewCronJobInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCronJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCronJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cronJobInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apibatchv1.CronJob{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cronJobInformer) TypedInformer() CronJobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1.CronJob](f.factory.InformerFor(&apibatchv1.CronJob{}, f.defaultInformer)) } func (f *cronJobInformer) Lister() batchv1.CronJobLister { return batchv1.NewCronJobLister(f.Informer().GetIndexer()) } + +// ToTypedCronJobInformer converts an untyped informer into a TypedCronJobInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CronJob. If that is not the case, calling type-safe methods of the returned +// TypedCronJobInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCronJobInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCronJobInformer(informer CronJobInformer) TypedCronJobInformer { + if informer, ok := informer.(TypedCronJobInformer); ok { + return informer + } + return &cronJobTypedInformerAdapter{informer} +} + +type cronJobTypedInformerAdapter struct { + CronJobInformer +} + +func (a *cronJobTypedInformerAdapter) TypedInformer() CronJobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1.CronJob](a.Informer()) +} + +// ToCronJobIndexInformer converts an untyped informer into a CronJobIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CronJob. If that is not the case, calling type-safe methods of the returned +// CronJobIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CronJobIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCronJobIndexInformer(informer cache.SharedIndexInformer) CronJobIndexInformer { + if informer, ok := informer.(CronJobIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apibatchv1.CronJob](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/batch/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/batch/v1/interface.go index 84567fb59..4308f08cb 100644 --- a/constraint/vendor/k8s.io/client-go/informers/batch/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/batch/v1/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CronJobs returns a CronJobInformer. - CronJobs() CronJobInformer + CronJobs() TypedCronJobInformer // Jobs returns a JobInformer. - Jobs() JobInformer + Jobs() TypedJobInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CronJobs returns a CronJobInformer. -func (v *version) CronJobs() CronJobInformer { +// CronJobs returns a TypedCronJobInformer. +func (v *version) CronJobs() TypedCronJobInformer { return &cronJobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Jobs returns a JobInformer. -func (v *version) Jobs() JobInformer { +// Jobs returns a TypedJobInformer. +func (v *version) Jobs() TypedJobInformer { return &jobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/batch/v1/job.go b/constraint/vendor/k8s.io/client-go/informers/batch/v1/job.go index 97e88927b..31d9244c1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/batch/v1/job.go +++ b/constraint/vendor/k8s.io/client-go/informers/batch/v1/job.go @@ -34,12 +34,40 @@ import ( ) // JobInformer provides access to a shared informer and lister for -// Jobs. +// Jobs. Prefer using the type-safe variant (see [TypedJobInformer]). type JobInformer interface { Informer() cache.SharedIndexInformer Lister() batchv1.JobLister } +// TypedJobInformer provides access to a shared informer and lister for +// Jobs, including the type-safe TypedInformer variant. +// It is a superset of JobInformer. +type TypedJobInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() JobIndexInformer + Lister() batchv1.JobLister +} + +// JobIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type JobIndexInformer cache.TypedSharedIndexInformer[*apibatchv1.Job] + +// JobHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Job. +type JobHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apibatchv1.Job] + +// JobDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Job. +type JobDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apibatchv1.Job] + +// JobFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Job. +type JobFilteringHandler = cache.TypedFilteringResourceEventHandler[*apibatchv1.Job] + +// JobIndexers is a specialization of [cache.TypedIndexers] for Job. +type JobIndexers = cache.TypedIndexers[*apibatchv1.Job] + +// DeletedJob is a specialization of [cache.DeletedObject] for Job. +type DeletedJob = cache.DeletedObject[*apibatchv1.Job] + type jobInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type jobInformer struct { // NewJobInformer constructs a new informer for Job type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedJobInformer]). func NewJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedJobInformer constructs a new informer for Job type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers JobIndexers) JobIndexInformer { + return NewTypedJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredJobInformer constructs a new informer for Job type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredJobInformer]). func NewFilteredJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredJobInformer constructs a new informer for Job type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers JobIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) JobIndexInformer { + return NewTypedJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewJobInformerWithOptions constructs a new informer for Job type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedJobInformerWithOptions]). func NewJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedJobInformerWithOptions(client, namespace, options) +} + +// NewTypedJobInformerWithOptions constructs a new informer for Job type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) JobIndexInformer { gvr := schema.GroupVersionResource{Group: "batch", Version: "v1", Resource: "jobs"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apibatchv1.Job](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewJobInformerWithOptions(client kubernetes.Interface, namespace string, op Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *jobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *jobInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apibatchv1.Job{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *jobInformer) TypedInformer() JobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1.Job](f.factory.InformerFor(&apibatchv1.Job{}, f.defaultInformer)) } func (f *jobInformer) Lister() batchv1.JobLister { return batchv1.NewJobLister(f.Informer().GetIndexer()) } + +// ToTypedJobInformer converts an untyped informer into a TypedJobInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Job. If that is not the case, calling type-safe methods of the returned +// TypedJobInformer leads to runtime panics. A safer alternative is to pass +// around a TypedJobInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedJobInformer(informer JobInformer) TypedJobInformer { + if informer, ok := informer.(TypedJobInformer); ok { + return informer + } + return &jobTypedInformerAdapter{informer} +} + +type jobTypedInformerAdapter struct { + JobInformer +} + +func (a *jobTypedInformerAdapter) TypedInformer() JobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1.Job](a.Informer()) +} + +// ToJobIndexInformer converts an untyped informer into a JobIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Job. If that is not the case, calling type-safe methods of the returned +// JobIndexInformer leads to runtime panics. A safer alternative is to pass +// around a JobIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToJobIndexInformer(informer cache.SharedIndexInformer) JobIndexInformer { + if informer, ok := informer.(JobIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apibatchv1.Job](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/cronjob.go b/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/cronjob.go index 5d2129323..9043856ab 100644 --- a/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/cronjob.go +++ b/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/cronjob.go @@ -34,12 +34,40 @@ import ( ) // CronJobInformer provides access to a shared informer and lister for -// CronJobs. +// CronJobs. Prefer using the type-safe variant (see [TypedCronJobInformer]). type CronJobInformer interface { Informer() cache.SharedIndexInformer Lister() batchv1beta1.CronJobLister } +// TypedCronJobInformer provides access to a shared informer and lister for +// CronJobs, including the type-safe TypedInformer variant. +// It is a superset of CronJobInformer. +type TypedCronJobInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CronJobIndexInformer + Lister() batchv1beta1.CronJobLister +} + +// CronJobIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CronJobIndexInformer cache.TypedSharedIndexInformer[*apibatchv1beta1.CronJob] + +// CronJobHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CronJob. +type CronJobHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apibatchv1beta1.CronJob] + +// CronJobDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CronJob. +type CronJobDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apibatchv1beta1.CronJob] + +// CronJobFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CronJob. +type CronJobFilteringHandler = cache.TypedFilteringResourceEventHandler[*apibatchv1beta1.CronJob] + +// CronJobIndexers is a specialization of [cache.TypedIndexers] for CronJob. +type CronJobIndexers = cache.TypedIndexers[*apibatchv1beta1.CronJob] + +// DeletedCronJob is a specialization of [cache.DeletedObject] for CronJob. +type DeletedCronJob = cache.DeletedObject[*apibatchv1beta1.CronJob] + type cronJobInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type cronJobInformer struct { // NewCronJobInformer constructs a new informer for CronJob type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCronJobInformer]). func NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCronJobInformer constructs a new informer for CronJob type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CronJobIndexers) CronJobIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCronJobInformer constructs a new informer for CronJob type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCronJobInformer]). func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCronJobInformer constructs a new informer for CronJob type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CronJobIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CronJobIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCronJobInformerWithOptions constructs a new informer for CronJob type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCronJobInformerWithOptions]). func NewCronJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCronJobInformerWithOptions(client, namespace, options) +} + +// NewTypedCronJobInformerWithOptions constructs a new informer for CronJob type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCronJobInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CronJobIndexInformer { gvr := schema.GroupVersionResource{Group: "batch", Version: "v1beta1", Resource: "cronjobs"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apibatchv1beta1.CronJob](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewCronJobInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCronJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCronJobInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cronJobInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apibatchv1beta1.CronJob{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cronJobInformer) TypedInformer() CronJobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1beta1.CronJob](f.factory.InformerFor(&apibatchv1beta1.CronJob{}, f.defaultInformer)) } func (f *cronJobInformer) Lister() batchv1beta1.CronJobLister { return batchv1beta1.NewCronJobLister(f.Informer().GetIndexer()) } + +// ToTypedCronJobInformer converts an untyped informer into a TypedCronJobInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CronJob. If that is not the case, calling type-safe methods of the returned +// TypedCronJobInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCronJobInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCronJobInformer(informer CronJobInformer) TypedCronJobInformer { + if informer, ok := informer.(TypedCronJobInformer); ok { + return informer + } + return &cronJobTypedInformerAdapter{informer} +} + +type cronJobTypedInformerAdapter struct { + CronJobInformer +} + +func (a *cronJobTypedInformerAdapter) TypedInformer() CronJobIndexInformer { + return cache.NewTypedSharedIndexInformer[*apibatchv1beta1.CronJob](a.Informer()) +} + +// ToCronJobIndexInformer converts an untyped informer into a CronJobIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CronJob. If that is not the case, calling type-safe methods of the returned +// CronJobIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CronJobIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCronJobIndexInformer(informer cache.SharedIndexInformer) CronJobIndexInformer { + if informer, ok := informer.(CronJobIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apibatchv1beta1.CronJob](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/interface.go index 76cae22d6..bfe75d8a1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/batch/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CronJobs returns a CronJobInformer. - CronJobs() CronJobInformer + CronJobs() TypedCronJobInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CronJobs returns a CronJobInformer. -func (v *version) CronJobs() CronJobInformer { +// CronJobs returns a TypedCronJobInformer. +func (v *version) CronJobs() TypedCronJobInformer { return &cronJobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go index 0e0706893..4aa2b549e 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go @@ -34,12 +34,40 @@ import ( ) // CertificateSigningRequestInformer provides access to a shared informer and lister for -// CertificateSigningRequests. +// CertificateSigningRequests. Prefer using the type-safe variant (see [TypedCertificateSigningRequestInformer]). type CertificateSigningRequestInformer interface { Informer() cache.SharedIndexInformer Lister() certificatesv1.CertificateSigningRequestLister } +// TypedCertificateSigningRequestInformer provides access to a shared informer and lister for +// CertificateSigningRequests, including the type-safe TypedInformer variant. +// It is a superset of CertificateSigningRequestInformer. +type TypedCertificateSigningRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CertificateSigningRequestIndexInformer + Lister() certificatesv1.CertificateSigningRequestLister +} + +// CertificateSigningRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CertificateSigningRequestIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1.CertificateSigningRequest] + +// CertificateSigningRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CertificateSigningRequest. +type CertificateSigningRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1.CertificateSigningRequest] + +// CertificateSigningRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CertificateSigningRequest. +type CertificateSigningRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1.CertificateSigningRequest] + +// CertificateSigningRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CertificateSigningRequest. +type CertificateSigningRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1.CertificateSigningRequest] + +// CertificateSigningRequestIndexers is a specialization of [cache.TypedIndexers] for CertificateSigningRequest. +type CertificateSigningRequestIndexers = cache.TypedIndexers[*apicertificatesv1.CertificateSigningRequest] + +// DeletedCertificateSigningRequest is a specialization of [cache.DeletedObject] for CertificateSigningRequest. +type DeletedCertificateSigningRequest = cache.DeletedObject[*apicertificatesv1.CertificateSigningRequest] + type certificateSigningRequestInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type certificateSigningRequestInformer struct { // NewCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCertificateSigningRequestInformer]). func NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CertificateSigningRequestIndexers) CertificateSigningRequestIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCertificateSigningRequestInformer]). func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CertificateSigningRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CertificateSigningRequestIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCertificateSigningRequestInformerWithOptions constructs a new informer for CertificateSigningRequest type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCertificateSigningRequestInformerWithOptions]). func NewCertificateSigningRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, options) +} + +// NewTypedCertificateSigningRequestInformerWithOptions constructs a new informer for CertificateSigningRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCertificateSigningRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CertificateSigningRequestIndexInformer { gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1", Resource: "certificatesigningrequests"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.CertificateSigningRequest](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCertificateSigningRequestInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicertificatesv1.CertificateSigningRequest{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *certificateSigningRequestInformer) TypedInformer() CertificateSigningRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.CertificateSigningRequest](f.factory.InformerFor(&apicertificatesv1.CertificateSigningRequest{}, f.defaultInformer)) } func (f *certificateSigningRequestInformer) Lister() certificatesv1.CertificateSigningRequestLister { return certificatesv1.NewCertificateSigningRequestLister(f.Informer().GetIndexer()) } + +// ToTypedCertificateSigningRequestInformer converts an untyped informer into a TypedCertificateSigningRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CertificateSigningRequest. If that is not the case, calling type-safe methods of the returned +// TypedCertificateSigningRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCertificateSigningRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCertificateSigningRequestInformer(informer CertificateSigningRequestInformer) TypedCertificateSigningRequestInformer { + if informer, ok := informer.(TypedCertificateSigningRequestInformer); ok { + return informer + } + return &certificateSigningRequestTypedInformerAdapter{informer} +} + +type certificateSigningRequestTypedInformerAdapter struct { + CertificateSigningRequestInformer +} + +func (a *certificateSigningRequestTypedInformerAdapter) TypedInformer() CertificateSigningRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.CertificateSigningRequest](a.Informer()) +} + +// ToCertificateSigningRequestIndexInformer converts an untyped informer into a CertificateSigningRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CertificateSigningRequest. If that is not the case, calling type-safe methods of the returned +// CertificateSigningRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CertificateSigningRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCertificateSigningRequestIndexInformer(informer cache.SharedIndexInformer) CertificateSigningRequestIndexInformer { + if informer, ok := informer.(CertificateSigningRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.CertificateSigningRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/clustertrustbundle.go new file mode 100644 index 000000000..e24a1aed5 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/clustertrustbundle.go @@ -0,0 +1,207 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apicertificatesv1 "k8s.io/api/certificates/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + certificatesv1 "k8s.io/client-go/listers/certificates/v1" + cache "k8s.io/client-go/tools/cache" +) + +// ClusterTrustBundleInformer provides access to a shared informer and lister for +// ClusterTrustBundles. Prefer using the type-safe variant (see [TypedClusterTrustBundleInformer]). +type ClusterTrustBundleInformer interface { + Informer() cache.SharedIndexInformer + Lister() certificatesv1.ClusterTrustBundleLister +} + +// TypedClusterTrustBundleInformer provides access to a shared informer and lister for +// ClusterTrustBundles, including the type-safe TypedInformer variant. +// It is a superset of ClusterTrustBundleInformer. +type TypedClusterTrustBundleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterTrustBundleIndexInformer + Lister() certificatesv1.ClusterTrustBundleLister +} + +// ClusterTrustBundleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterTrustBundleIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1.ClusterTrustBundle] + +// ClusterTrustBundleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterTrustBundle. +type ClusterTrustBundleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1.ClusterTrustBundle] + +// ClusterTrustBundleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterTrustBundle. +type ClusterTrustBundleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1.ClusterTrustBundle] + +// ClusterTrustBundleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterTrustBundle. +type ClusterTrustBundleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1.ClusterTrustBundle] + +// ClusterTrustBundleIndexers is a specialization of [cache.TypedIndexers] for ClusterTrustBundle. +type ClusterTrustBundleIndexers = cache.TypedIndexers[*apicertificatesv1.ClusterTrustBundle] + +// DeletedClusterTrustBundle is a specialization of [cache.DeletedObject] for ClusterTrustBundle. +type DeletedClusterTrustBundle = cache.DeletedObject[*apicertificatesv1.ClusterTrustBundle] + +type clusterTrustBundleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformer]). +func NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterTrustBundleInformer]). +func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformerWithOptions]). +func NewClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, options) +} + +// NewTypedClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterTrustBundleIndexInformer { + gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1", Resource: "clustertrustbundles"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.ClusterTrustBundle](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().ClusterTrustBundles().List(context.Background(), opts) + }, + WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().ClusterTrustBundles().Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().ClusterTrustBundles().List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().ClusterTrustBundles().Watch(ctx, opts) + }, + }, client), + &apicertificatesv1.ClusterTrustBundle{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *clusterTrustBundleInformer) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.ClusterTrustBundle](f.factory.InformerFor(&apicertificatesv1.ClusterTrustBundle{}, f.defaultInformer)) +} + +func (f *clusterTrustBundleInformer) Lister() certificatesv1.ClusterTrustBundleLister { + return certificatesv1.NewClusterTrustBundleLister(f.Informer().GetIndexer()) +} + +// ToTypedClusterTrustBundleInformer converts an untyped informer into a TypedClusterTrustBundleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// TypedClusterTrustBundleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterTrustBundleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterTrustBundleInformer(informer ClusterTrustBundleInformer) TypedClusterTrustBundleInformer { + if informer, ok := informer.(TypedClusterTrustBundleInformer); ok { + return informer + } + return &clusterTrustBundleTypedInformerAdapter{informer} +} + +type clusterTrustBundleTypedInformerAdapter struct { + ClusterTrustBundleInformer +} + +func (a *clusterTrustBundleTypedInformerAdapter) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.ClusterTrustBundle](a.Informer()) +} + +// ToClusterTrustBundleIndexInformer converts an untyped informer into a ClusterTrustBundleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// ClusterTrustBundleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterTrustBundleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterTrustBundleIndexInformer(informer cache.SharedIndexInformer) ClusterTrustBundleIndexInformer { + if informer, ok := informer.(ClusterTrustBundleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.ClusterTrustBundle](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/interface.go index 91ccfb715..b0e1ecc60 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/interface.go @@ -25,7 +25,11 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CertificateSigningRequests returns a CertificateSigningRequestInformer. - CertificateSigningRequests() CertificateSigningRequestInformer + CertificateSigningRequests() TypedCertificateSigningRequestInformer + // ClusterTrustBundles returns a ClusterTrustBundleInformer. + ClusterTrustBundles() TypedClusterTrustBundleInformer + // PodCertificateRequests returns a PodCertificateRequestInformer. + PodCertificateRequests() TypedPodCertificateRequestInformer } type version struct { @@ -39,7 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CertificateSigningRequests returns a CertificateSigningRequestInformer. -func (v *version) CertificateSigningRequests() CertificateSigningRequestInformer { +// CertificateSigningRequests returns a TypedCertificateSigningRequestInformer. +func (v *version) CertificateSigningRequests() TypedCertificateSigningRequestInformer { return &certificateSigningRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } + +// ClusterTrustBundles returns a TypedClusterTrustBundleInformer. +func (v *version) ClusterTrustBundles() TypedClusterTrustBundleInformer { + return &clusterTrustBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + +// PodCertificateRequests returns a TypedPodCertificateRequestInformer. +func (v *version) PodCertificateRequests() TypedPodCertificateRequestInformer { + return &podCertificateRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/podcertificaterequest.go new file mode 100644 index 000000000..364740b0d --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1/podcertificaterequest.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apicertificatesv1 "k8s.io/api/certificates/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + certificatesv1 "k8s.io/client-go/listers/certificates/v1" + cache "k8s.io/client-go/tools/cache" +) + +// PodCertificateRequestInformer provides access to a shared informer and lister for +// PodCertificateRequests. Prefer using the type-safe variant (see [TypedPodCertificateRequestInformer]). +type PodCertificateRequestInformer interface { + Informer() cache.SharedIndexInformer + Lister() certificatesv1.PodCertificateRequestLister +} + +// TypedPodCertificateRequestInformer provides access to a shared informer and lister for +// PodCertificateRequests, including the type-safe TypedInformer variant. +// It is a superset of PodCertificateRequestInformer. +type TypedPodCertificateRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodCertificateRequestIndexInformer + Lister() certificatesv1.PodCertificateRequestLister +} + +// PodCertificateRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodCertificateRequestIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1.PodCertificateRequest] + +// PodCertificateRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodCertificateRequest. +type PodCertificateRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1.PodCertificateRequest] + +// PodCertificateRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodCertificateRequest. +type PodCertificateRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1.PodCertificateRequest] + +// PodCertificateRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodCertificateRequest. +type PodCertificateRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1.PodCertificateRequest] + +// PodCertificateRequestIndexers is a specialization of [cache.TypedIndexers] for PodCertificateRequest. +type PodCertificateRequestIndexers = cache.TypedIndexers[*apicertificatesv1.PodCertificateRequest] + +// DeletedPodCertificateRequest is a specialization of [cache.DeletedObject] for PodCertificateRequest. +type DeletedPodCertificateRequest = cache.DeletedObject[*apicertificatesv1.PodCertificateRequest] + +type podCertificateRequestInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodCertificateRequestInformer]). +func NewPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodCertificateRequestIndexers) PodCertificateRequestIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodCertificateRequestInformer]). +func NewFilteredPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodCertificateRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodCertificateRequestIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewPodCertificateRequestInformerWithOptions constructs a new informer for PodCertificateRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodCertificateRequestInformerWithOptions]). +func NewPodCertificateRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, options) +} + +// NewTypedPodCertificateRequestInformerWithOptions constructs a new informer for PodCertificateRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodCertificateRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodCertificateRequestIndexInformer { + gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1", Resource: "podcertificaterequests"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.PodCertificateRequest](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().PodCertificateRequests(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().PodCertificateRequests(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().PodCertificateRequests(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.CertificatesV1().PodCertificateRequests(namespace).Watch(ctx, opts) + }, + }, client), + &apicertificatesv1.PodCertificateRequest{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *podCertificateRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *podCertificateRequestInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *podCertificateRequestInformer) TypedInformer() PodCertificateRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.PodCertificateRequest](f.factory.InformerFor(&apicertificatesv1.PodCertificateRequest{}, f.defaultInformer)) +} + +func (f *podCertificateRequestInformer) Lister() certificatesv1.PodCertificateRequestLister { + return certificatesv1.NewPodCertificateRequestLister(f.Informer().GetIndexer()) +} + +// ToTypedPodCertificateRequestInformer converts an untyped informer into a TypedPodCertificateRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodCertificateRequest. If that is not the case, calling type-safe methods of the returned +// TypedPodCertificateRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodCertificateRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodCertificateRequestInformer(informer PodCertificateRequestInformer) TypedPodCertificateRequestInformer { + if informer, ok := informer.(TypedPodCertificateRequestInformer); ok { + return informer + } + return &podCertificateRequestTypedInformerAdapter{informer} +} + +type podCertificateRequestTypedInformerAdapter struct { + PodCertificateRequestInformer +} + +func (a *podCertificateRequestTypedInformerAdapter) TypedInformer() PodCertificateRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.PodCertificateRequest](a.Informer()) +} + +// ToPodCertificateRequestIndexInformer converts an untyped informer into a PodCertificateRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodCertificateRequest. If that is not the case, calling type-safe methods of the returned +// PodCertificateRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodCertificateRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodCertificateRequestIndexInformer(informer cache.SharedIndexInformer) PodCertificateRequestIndexInformer { + if informer, ok := informer.(PodCertificateRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1.PodCertificateRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go index 637cfd71d..da71ca3ba 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go @@ -34,12 +34,40 @@ import ( ) // ClusterTrustBundleInformer provides access to a shared informer and lister for -// ClusterTrustBundles. +// ClusterTrustBundles. Prefer using the type-safe variant (see [TypedClusterTrustBundleInformer]). type ClusterTrustBundleInformer interface { Informer() cache.SharedIndexInformer Lister() certificatesv1alpha1.ClusterTrustBundleLister } +// TypedClusterTrustBundleInformer provides access to a shared informer and lister for +// ClusterTrustBundles, including the type-safe TypedInformer variant. +// It is a superset of ClusterTrustBundleInformer. +type TypedClusterTrustBundleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterTrustBundleIndexInformer + Lister() certificatesv1alpha1.ClusterTrustBundleLister +} + +// ClusterTrustBundleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterTrustBundleIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1alpha1.ClusterTrustBundle] + +// ClusterTrustBundleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterTrustBundle. +type ClusterTrustBundleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1alpha1.ClusterTrustBundle] + +// ClusterTrustBundleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterTrustBundle. +type ClusterTrustBundleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1alpha1.ClusterTrustBundle] + +// ClusterTrustBundleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterTrustBundle. +type ClusterTrustBundleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1alpha1.ClusterTrustBundle] + +// ClusterTrustBundleIndexers is a specialization of [cache.TypedIndexers] for ClusterTrustBundle. +type ClusterTrustBundleIndexers = cache.TypedIndexers[*apicertificatesv1alpha1.ClusterTrustBundle] + +// DeletedClusterTrustBundle is a specialization of [cache.DeletedObject] for ClusterTrustBundle. +type DeletedClusterTrustBundle = cache.DeletedObject[*apicertificatesv1alpha1.ClusterTrustBundle] + type clusterTrustBundleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterTrustBundleInformer struct { // NewClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformer]). func NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterTrustBundleInformer]). func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformerWithOptions]). func NewClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, options) +} + +// NewTypedClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterTrustBundleIndexInformer { gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1alpha1", Resource: "clustertrustbundles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicertificatesv1alpha1.ClusterTrustBundle](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterTrustBundleInformerWithOptions(client kubernetes.Interface, optio Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicertificatesv1alpha1.ClusterTrustBundle{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterTrustBundleInformer) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1alpha1.ClusterTrustBundle](f.factory.InformerFor(&apicertificatesv1alpha1.ClusterTrustBundle{}, f.defaultInformer)) } func (f *clusterTrustBundleInformer) Lister() certificatesv1alpha1.ClusterTrustBundleLister { return certificatesv1alpha1.NewClusterTrustBundleLister(f.Informer().GetIndexer()) } + +// ToTypedClusterTrustBundleInformer converts an untyped informer into a TypedClusterTrustBundleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// TypedClusterTrustBundleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterTrustBundleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterTrustBundleInformer(informer ClusterTrustBundleInformer) TypedClusterTrustBundleInformer { + if informer, ok := informer.(TypedClusterTrustBundleInformer); ok { + return informer + } + return &clusterTrustBundleTypedInformerAdapter{informer} +} + +type clusterTrustBundleTypedInformerAdapter struct { + ClusterTrustBundleInformer +} + +func (a *clusterTrustBundleTypedInformerAdapter) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1alpha1.ClusterTrustBundle](a.Informer()) +} + +// ToClusterTrustBundleIndexInformer converts an untyped informer into a ClusterTrustBundleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// ClusterTrustBundleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterTrustBundleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterTrustBundleIndexInformer(informer cache.SharedIndexInformer) ClusterTrustBundleIndexInformer { + if informer, ok := informer.(ClusterTrustBundleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1alpha1.ClusterTrustBundle](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/interface.go index 40ce8f42d..8741155be 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1alpha1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ClusterTrustBundles returns a ClusterTrustBundleInformer. - ClusterTrustBundles() ClusterTrustBundleInformer + ClusterTrustBundles() TypedClusterTrustBundleInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterTrustBundles returns a ClusterTrustBundleInformer. -func (v *version) ClusterTrustBundles() ClusterTrustBundleInformer { +// ClusterTrustBundles returns a TypedClusterTrustBundleInformer. +func (v *version) ClusterTrustBundles() TypedClusterTrustBundleInformer { return &clusterTrustBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go index 4d4408d90..bac26740b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go @@ -34,12 +34,40 @@ import ( ) // CertificateSigningRequestInformer provides access to a shared informer and lister for -// CertificateSigningRequests. +// CertificateSigningRequests. Prefer using the type-safe variant (see [TypedCertificateSigningRequestInformer]). type CertificateSigningRequestInformer interface { Informer() cache.SharedIndexInformer Lister() certificatesv1beta1.CertificateSigningRequestLister } +// TypedCertificateSigningRequestInformer provides access to a shared informer and lister for +// CertificateSigningRequests, including the type-safe TypedInformer variant. +// It is a superset of CertificateSigningRequestInformer. +type TypedCertificateSigningRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CertificateSigningRequestIndexInformer + Lister() certificatesv1beta1.CertificateSigningRequestLister +} + +// CertificateSigningRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CertificateSigningRequestIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1beta1.CertificateSigningRequest] + +// CertificateSigningRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CertificateSigningRequest. +type CertificateSigningRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1beta1.CertificateSigningRequest] + +// CertificateSigningRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CertificateSigningRequest. +type CertificateSigningRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1beta1.CertificateSigningRequest] + +// CertificateSigningRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CertificateSigningRequest. +type CertificateSigningRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1beta1.CertificateSigningRequest] + +// CertificateSigningRequestIndexers is a specialization of [cache.TypedIndexers] for CertificateSigningRequest. +type CertificateSigningRequestIndexers = cache.TypedIndexers[*apicertificatesv1beta1.CertificateSigningRequest] + +// DeletedCertificateSigningRequest is a specialization of [cache.DeletedObject] for CertificateSigningRequest. +type DeletedCertificateSigningRequest = cache.DeletedObject[*apicertificatesv1beta1.CertificateSigningRequest] + type certificateSigningRequestInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type certificateSigningRequestInformer struct { // NewCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCertificateSigningRequestInformer]). func NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CertificateSigningRequestIndexers) CertificateSigningRequestIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCertificateSigningRequestInformer]). func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CertificateSigningRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CertificateSigningRequestIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCertificateSigningRequestInformerWithOptions constructs a new informer for CertificateSigningRequest type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCertificateSigningRequestInformerWithOptions]). func NewCertificateSigningRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCertificateSigningRequestInformerWithOptions(client, options) +} + +// NewTypedCertificateSigningRequestInformerWithOptions constructs a new informer for CertificateSigningRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCertificateSigningRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CertificateSigningRequestIndexInformer { gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "certificatesigningrequests"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.CertificateSigningRequest](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCertificateSigningRequestInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCertificateSigningRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicertificatesv1beta1.CertificateSigningRequest{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *certificateSigningRequestInformer) TypedInformer() CertificateSigningRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.CertificateSigningRequest](f.factory.InformerFor(&apicertificatesv1beta1.CertificateSigningRequest{}, f.defaultInformer)) } func (f *certificateSigningRequestInformer) Lister() certificatesv1beta1.CertificateSigningRequestLister { return certificatesv1beta1.NewCertificateSigningRequestLister(f.Informer().GetIndexer()) } + +// ToTypedCertificateSigningRequestInformer converts an untyped informer into a TypedCertificateSigningRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CertificateSigningRequest. If that is not the case, calling type-safe methods of the returned +// TypedCertificateSigningRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCertificateSigningRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCertificateSigningRequestInformer(informer CertificateSigningRequestInformer) TypedCertificateSigningRequestInformer { + if informer, ok := informer.(TypedCertificateSigningRequestInformer); ok { + return informer + } + return &certificateSigningRequestTypedInformerAdapter{informer} +} + +type certificateSigningRequestTypedInformerAdapter struct { + CertificateSigningRequestInformer +} + +func (a *certificateSigningRequestTypedInformerAdapter) TypedInformer() CertificateSigningRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.CertificateSigningRequest](a.Informer()) +} + +// ToCertificateSigningRequestIndexInformer converts an untyped informer into a CertificateSigningRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CertificateSigningRequest. If that is not the case, calling type-safe methods of the returned +// CertificateSigningRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CertificateSigningRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCertificateSigningRequestIndexInformer(informer cache.SharedIndexInformer) CertificateSigningRequestIndexInformer { + if informer, ok := informer.(CertificateSigningRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.CertificateSigningRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/clustertrustbundle.go index f665d0b73..4415e589a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/clustertrustbundle.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/clustertrustbundle.go @@ -34,12 +34,40 @@ import ( ) // ClusterTrustBundleInformer provides access to a shared informer and lister for -// ClusterTrustBundles. +// ClusterTrustBundles. Prefer using the type-safe variant (see [TypedClusterTrustBundleInformer]). type ClusterTrustBundleInformer interface { Informer() cache.SharedIndexInformer Lister() certificatesv1beta1.ClusterTrustBundleLister } +// TypedClusterTrustBundleInformer provides access to a shared informer and lister for +// ClusterTrustBundles, including the type-safe TypedInformer variant. +// It is a superset of ClusterTrustBundleInformer. +type TypedClusterTrustBundleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterTrustBundleIndexInformer + Lister() certificatesv1beta1.ClusterTrustBundleLister +} + +// ClusterTrustBundleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterTrustBundleIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1beta1.ClusterTrustBundle] + +// ClusterTrustBundleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterTrustBundle. +type ClusterTrustBundleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1beta1.ClusterTrustBundle] + +// ClusterTrustBundleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterTrustBundle. +type ClusterTrustBundleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1beta1.ClusterTrustBundle] + +// ClusterTrustBundleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterTrustBundle. +type ClusterTrustBundleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1beta1.ClusterTrustBundle] + +// ClusterTrustBundleIndexers is a specialization of [cache.TypedIndexers] for ClusterTrustBundle. +type ClusterTrustBundleIndexers = cache.TypedIndexers[*apicertificatesv1beta1.ClusterTrustBundle] + +// DeletedClusterTrustBundle is a specialization of [cache.DeletedObject] for ClusterTrustBundle. +type DeletedClusterTrustBundle = cache.DeletedObject[*apicertificatesv1beta1.ClusterTrustBundle] + type clusterTrustBundleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterTrustBundleInformer struct { // NewClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformer]). func NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterTrustBundleInformer]). func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterTrustBundleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterTrustBundleIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterTrustBundleInformerWithOptions]). func NewClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterTrustBundleInformerWithOptions(client, options) +} + +// NewTypedClusterTrustBundleInformerWithOptions constructs a new informer for ClusterTrustBundle type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterTrustBundleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterTrustBundleIndexInformer { gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "clustertrustbundles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.ClusterTrustBundle](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterTrustBundleInformerWithOptions(client kubernetes.Interface, optio Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterTrustBundleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicertificatesv1beta1.ClusterTrustBundle{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterTrustBundleInformer) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.ClusterTrustBundle](f.factory.InformerFor(&apicertificatesv1beta1.ClusterTrustBundle{}, f.defaultInformer)) } func (f *clusterTrustBundleInformer) Lister() certificatesv1beta1.ClusterTrustBundleLister { return certificatesv1beta1.NewClusterTrustBundleLister(f.Informer().GetIndexer()) } + +// ToTypedClusterTrustBundleInformer converts an untyped informer into a TypedClusterTrustBundleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// TypedClusterTrustBundleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterTrustBundleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterTrustBundleInformer(informer ClusterTrustBundleInformer) TypedClusterTrustBundleInformer { + if informer, ok := informer.(TypedClusterTrustBundleInformer); ok { + return informer + } + return &clusterTrustBundleTypedInformerAdapter{informer} +} + +type clusterTrustBundleTypedInformerAdapter struct { + ClusterTrustBundleInformer +} + +func (a *clusterTrustBundleTypedInformerAdapter) TypedInformer() ClusterTrustBundleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.ClusterTrustBundle](a.Informer()) +} + +// ToClusterTrustBundleIndexInformer converts an untyped informer into a ClusterTrustBundleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterTrustBundle. If that is not the case, calling type-safe methods of the returned +// ClusterTrustBundleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterTrustBundleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterTrustBundleIndexInformer(informer cache.SharedIndexInformer) ClusterTrustBundleIndexInformer { + if informer, ok := informer.(ClusterTrustBundleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.ClusterTrustBundle](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/interface.go index b2d39e206..95bce3fa3 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/interface.go @@ -25,11 +25,11 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CertificateSigningRequests returns a CertificateSigningRequestInformer. - CertificateSigningRequests() CertificateSigningRequestInformer + CertificateSigningRequests() TypedCertificateSigningRequestInformer // ClusterTrustBundles returns a ClusterTrustBundleInformer. - ClusterTrustBundles() ClusterTrustBundleInformer + ClusterTrustBundles() TypedClusterTrustBundleInformer // PodCertificateRequests returns a PodCertificateRequestInformer. - PodCertificateRequests() PodCertificateRequestInformer + PodCertificateRequests() TypedPodCertificateRequestInformer } type version struct { @@ -43,17 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CertificateSigningRequests returns a CertificateSigningRequestInformer. -func (v *version) CertificateSigningRequests() CertificateSigningRequestInformer { +// CertificateSigningRequests returns a TypedCertificateSigningRequestInformer. +func (v *version) CertificateSigningRequests() TypedCertificateSigningRequestInformer { return &certificateSigningRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ClusterTrustBundles returns a ClusterTrustBundleInformer. -func (v *version) ClusterTrustBundles() ClusterTrustBundleInformer { +// ClusterTrustBundles returns a TypedClusterTrustBundleInformer. +func (v *version) ClusterTrustBundles() TypedClusterTrustBundleInformer { return &clusterTrustBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PodCertificateRequests returns a PodCertificateRequestInformer. -func (v *version) PodCertificateRequests() PodCertificateRequestInformer { +// PodCertificateRequests returns a TypedPodCertificateRequestInformer. +func (v *version) PodCertificateRequests() TypedPodCertificateRequestInformer { return &podCertificateRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/podcertificaterequest.go index 03f7816cf..546a8a3ea 100644 --- a/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/podcertificaterequest.go +++ b/constraint/vendor/k8s.io/client-go/informers/certificates/v1beta1/podcertificaterequest.go @@ -34,12 +34,40 @@ import ( ) // PodCertificateRequestInformer provides access to a shared informer and lister for -// PodCertificateRequests. +// PodCertificateRequests. Prefer using the type-safe variant (see [TypedPodCertificateRequestInformer]). type PodCertificateRequestInformer interface { Informer() cache.SharedIndexInformer Lister() certificatesv1beta1.PodCertificateRequestLister } +// TypedPodCertificateRequestInformer provides access to a shared informer and lister for +// PodCertificateRequests, including the type-safe TypedInformer variant. +// It is a superset of PodCertificateRequestInformer. +type TypedPodCertificateRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodCertificateRequestIndexInformer + Lister() certificatesv1beta1.PodCertificateRequestLister +} + +// PodCertificateRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodCertificateRequestIndexInformer cache.TypedSharedIndexInformer[*apicertificatesv1beta1.PodCertificateRequest] + +// PodCertificateRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodCertificateRequest. +type PodCertificateRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicertificatesv1beta1.PodCertificateRequest] + +// PodCertificateRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodCertificateRequest. +type PodCertificateRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicertificatesv1beta1.PodCertificateRequest] + +// PodCertificateRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodCertificateRequest. +type PodCertificateRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicertificatesv1beta1.PodCertificateRequest] + +// PodCertificateRequestIndexers is a specialization of [cache.TypedIndexers] for PodCertificateRequest. +type PodCertificateRequestIndexers = cache.TypedIndexers[*apicertificatesv1beta1.PodCertificateRequest] + +// DeletedPodCertificateRequest is a specialization of [cache.DeletedObject] for PodCertificateRequest. +type DeletedPodCertificateRequest = cache.DeletedObject[*apicertificatesv1beta1.PodCertificateRequest] + type podCertificateRequestInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type podCertificateRequestInformer struct { // NewPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodCertificateRequestInformer]). func NewPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodCertificateRequestIndexers) PodCertificateRequestIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodCertificateRequestInformer]). func NewFilteredPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodCertificateRequestInformer constructs a new informer for PodCertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodCertificateRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodCertificateRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodCertificateRequestIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPodCertificateRequestInformerWithOptions constructs a new informer for PodCertificateRequest type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodCertificateRequestInformerWithOptions]). func NewPodCertificateRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodCertificateRequestInformerWithOptions(client, namespace, options) +} + +// NewTypedPodCertificateRequestInformerWithOptions constructs a new informer for PodCertificateRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodCertificateRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodCertificateRequestIndexInformer { gvr := schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "podcertificaterequests"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.PodCertificateRequest](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPodCertificateRequestInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *podCertificateRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodCertificateRequestInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPodCertificateRequestInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *podCertificateRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicertificatesv1beta1.PodCertificateRequest{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *podCertificateRequestInformer) TypedInformer() PodCertificateRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.PodCertificateRequest](f.factory.InformerFor(&apicertificatesv1beta1.PodCertificateRequest{}, f.defaultInformer)) } func (f *podCertificateRequestInformer) Lister() certificatesv1beta1.PodCertificateRequestLister { return certificatesv1beta1.NewPodCertificateRequestLister(f.Informer().GetIndexer()) } + +// ToTypedPodCertificateRequestInformer converts an untyped informer into a TypedPodCertificateRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodCertificateRequest. If that is not the case, calling type-safe methods of the returned +// TypedPodCertificateRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodCertificateRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodCertificateRequestInformer(informer PodCertificateRequestInformer) TypedPodCertificateRequestInformer { + if informer, ok := informer.(TypedPodCertificateRequestInformer); ok { + return informer + } + return &podCertificateRequestTypedInformerAdapter{informer} +} + +type podCertificateRequestTypedInformerAdapter struct { + PodCertificateRequestInformer +} + +func (a *podCertificateRequestTypedInformerAdapter) TypedInformer() PodCertificateRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.PodCertificateRequest](a.Informer()) +} + +// ToPodCertificateRequestIndexInformer converts an untyped informer into a PodCertificateRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodCertificateRequest. If that is not the case, calling type-safe methods of the returned +// PodCertificateRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodCertificateRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodCertificateRequestIndexInformer(informer cache.SharedIndexInformer) PodCertificateRequestIndexInformer { + if informer, ok := informer.(PodCertificateRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicertificatesv1beta1.PodCertificateRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1/interface.go index 05c4acbef..9451e7125 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // Leases returns a LeaseInformer. - Leases() LeaseInformer + Leases() TypedLeaseInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// Leases returns a LeaseInformer. -func (v *version) Leases() LeaseInformer { +// Leases returns a TypedLeaseInformer. +func (v *version) Leases() TypedLeaseInformer { return &leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1/lease.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1/lease.go index cce8ab4d1..feec29044 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1/lease.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1/lease.go @@ -34,12 +34,40 @@ import ( ) // LeaseInformer provides access to a shared informer and lister for -// Leases. +// Leases. Prefer using the type-safe variant (see [TypedLeaseInformer]). type LeaseInformer interface { Informer() cache.SharedIndexInformer Lister() coordinationv1.LeaseLister } +// TypedLeaseInformer provides access to a shared informer and lister for +// Leases, including the type-safe TypedInformer variant. +// It is a superset of LeaseInformer. +type TypedLeaseInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() LeaseIndexInformer + Lister() coordinationv1.LeaseLister +} + +// LeaseIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type LeaseIndexInformer cache.TypedSharedIndexInformer[*apicoordinationv1.Lease] + +// LeaseHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Lease. +type LeaseHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicoordinationv1.Lease] + +// LeaseDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Lease. +type LeaseDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicoordinationv1.Lease] + +// LeaseFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Lease. +type LeaseFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicoordinationv1.Lease] + +// LeaseIndexers is a specialization of [cache.TypedIndexers] for Lease. +type LeaseIndexers = cache.TypedIndexers[*apicoordinationv1.Lease] + +// DeletedLease is a specialization of [cache.DeletedObject] for Lease. +type DeletedLease = cache.DeletedObject[*apicoordinationv1.Lease] + type leaseInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type leaseInformer struct { // NewLeaseInformer constructs a new informer for Lease type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseInformer]). func NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedLeaseInformer constructs a new informer for Lease type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseIndexers) LeaseIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredLeaseInformer constructs a new informer for Lease type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredLeaseInformer]). func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredLeaseInformer constructs a new informer for Lease type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) LeaseIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewLeaseInformerWithOptions constructs a new informer for Lease type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseInformerWithOptions]). func NewLeaseInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, options) +} + +// NewTypedLeaseInformerWithOptions constructs a new informer for Lease type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) LeaseIndexInformer { gvr := schema.GroupVersionResource{Group: "coordination.k8s.io", Version: "v1", Resource: "leases"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicoordinationv1.Lease](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewLeaseInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewLeaseInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedLeaseInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *leaseInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicoordinationv1.Lease{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *leaseInformer) TypedInformer() LeaseIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1.Lease](f.factory.InformerFor(&apicoordinationv1.Lease{}, f.defaultInformer)) } func (f *leaseInformer) Lister() coordinationv1.LeaseLister { return coordinationv1.NewLeaseLister(f.Informer().GetIndexer()) } + +// ToTypedLeaseInformer converts an untyped informer into a TypedLeaseInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Lease. If that is not the case, calling type-safe methods of the returned +// TypedLeaseInformer leads to runtime panics. A safer alternative is to pass +// around a TypedLeaseInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedLeaseInformer(informer LeaseInformer) TypedLeaseInformer { + if informer, ok := informer.(TypedLeaseInformer); ok { + return informer + } + return &leaseTypedInformerAdapter{informer} +} + +type leaseTypedInformerAdapter struct { + LeaseInformer +} + +func (a *leaseTypedInformerAdapter) TypedInformer() LeaseIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1.Lease](a.Informer()) +} + +// ToLeaseIndexInformer converts an untyped informer into a LeaseIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Lease. If that is not the case, calling type-safe methods of the returned +// LeaseIndexInformer leads to runtime panics. A safer alternative is to pass +// around a LeaseIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToLeaseIndexInformer(informer cache.SharedIndexInformer) LeaseIndexInformer { + if informer, ok := informer.(LeaseIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicoordinationv1.Lease](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/interface.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/interface.go index ba83768ad..13aea61e7 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // LeaseCandidates returns a LeaseCandidateInformer. - LeaseCandidates() LeaseCandidateInformer + LeaseCandidates() TypedLeaseCandidateInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// LeaseCandidates returns a LeaseCandidateInformer. -func (v *version) LeaseCandidates() LeaseCandidateInformer { +// LeaseCandidates returns a TypedLeaseCandidateInformer. +func (v *version) LeaseCandidates() TypedLeaseCandidateInformer { return &leaseCandidateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/leasecandidate.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/leasecandidate.go index 5aa0ff3ae..55071de0f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/leasecandidate.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1alpha2/leasecandidate.go @@ -34,12 +34,40 @@ import ( ) // LeaseCandidateInformer provides access to a shared informer and lister for -// LeaseCandidates. +// LeaseCandidates. Prefer using the type-safe variant (see [TypedLeaseCandidateInformer]). type LeaseCandidateInformer interface { Informer() cache.SharedIndexInformer Lister() coordinationv1alpha2.LeaseCandidateLister } +// TypedLeaseCandidateInformer provides access to a shared informer and lister for +// LeaseCandidates, including the type-safe TypedInformer variant. +// It is a superset of LeaseCandidateInformer. +type TypedLeaseCandidateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() LeaseCandidateIndexInformer + Lister() coordinationv1alpha2.LeaseCandidateLister +} + +// LeaseCandidateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type LeaseCandidateIndexInformer cache.TypedSharedIndexInformer[*apicoordinationv1alpha2.LeaseCandidate] + +// LeaseCandidateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for LeaseCandidate. +type LeaseCandidateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicoordinationv1alpha2.LeaseCandidate] + +// LeaseCandidateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for LeaseCandidate. +type LeaseCandidateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicoordinationv1alpha2.LeaseCandidate] + +// LeaseCandidateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for LeaseCandidate. +type LeaseCandidateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicoordinationv1alpha2.LeaseCandidate] + +// LeaseCandidateIndexers is a specialization of [cache.TypedIndexers] for LeaseCandidate. +type LeaseCandidateIndexers = cache.TypedIndexers[*apicoordinationv1alpha2.LeaseCandidate] + +// DeletedLeaseCandidate is a specialization of [cache.DeletedObject] for LeaseCandidate. +type DeletedLeaseCandidate = cache.DeletedObject[*apicoordinationv1alpha2.LeaseCandidate] + type leaseCandidateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type leaseCandidateInformer struct { // NewLeaseCandidateInformer constructs a new informer for LeaseCandidate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseCandidateInformer]). func NewLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseCandidateIndexers) LeaseCandidateIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredLeaseCandidateInformer constructs a new informer for LeaseCandidate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredLeaseCandidateInformer]). func NewFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseCandidateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) LeaseCandidateIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewLeaseCandidateInformerWithOptions constructs a new informer for LeaseCandidate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseCandidateInformerWithOptions]). func NewLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, options) +} + +// NewTypedLeaseCandidateInformerWithOptions constructs a new informer for LeaseCandidate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) LeaseCandidateIndexInformer { gvr := schema.GroupVersionResource{Group: "coordination.k8s.io", Version: "v1alpha2", Resource: "leasecandidates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicoordinationv1alpha2.LeaseCandidate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *leaseCandidateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewLeaseCandidateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedLeaseCandidateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *leaseCandidateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicoordinationv1alpha2.LeaseCandidate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *leaseCandidateInformer) TypedInformer() LeaseCandidateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1alpha2.LeaseCandidate](f.factory.InformerFor(&apicoordinationv1alpha2.LeaseCandidate{}, f.defaultInformer)) } func (f *leaseCandidateInformer) Lister() coordinationv1alpha2.LeaseCandidateLister { return coordinationv1alpha2.NewLeaseCandidateLister(f.Informer().GetIndexer()) } + +// ToTypedLeaseCandidateInformer converts an untyped informer into a TypedLeaseCandidateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LeaseCandidate. If that is not the case, calling type-safe methods of the returned +// TypedLeaseCandidateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedLeaseCandidateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedLeaseCandidateInformer(informer LeaseCandidateInformer) TypedLeaseCandidateInformer { + if informer, ok := informer.(TypedLeaseCandidateInformer); ok { + return informer + } + return &leaseCandidateTypedInformerAdapter{informer} +} + +type leaseCandidateTypedInformerAdapter struct { + LeaseCandidateInformer +} + +func (a *leaseCandidateTypedInformerAdapter) TypedInformer() LeaseCandidateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1alpha2.LeaseCandidate](a.Informer()) +} + +// ToLeaseCandidateIndexInformer converts an untyped informer into a LeaseCandidateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LeaseCandidate. If that is not the case, calling type-safe methods of the returned +// LeaseCandidateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a LeaseCandidateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToLeaseCandidateIndexInformer(informer cache.SharedIndexInformer) LeaseCandidateIndexInformer { + if informer, ok := informer.(LeaseCandidateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicoordinationv1alpha2.LeaseCandidate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/interface.go index 707e51086..41af12591 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // Leases returns a LeaseInformer. - Leases() LeaseInformer + Leases() TypedLeaseInformer // LeaseCandidates returns a LeaseCandidateInformer. - LeaseCandidates() LeaseCandidateInformer + LeaseCandidates() TypedLeaseCandidateInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// Leases returns a LeaseInformer. -func (v *version) Leases() LeaseInformer { +// Leases returns a TypedLeaseInformer. +func (v *version) Leases() TypedLeaseInformer { return &leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// LeaseCandidates returns a LeaseCandidateInformer. -func (v *version) LeaseCandidates() LeaseCandidateInformer { +// LeaseCandidates returns a TypedLeaseCandidateInformer. +func (v *version) LeaseCandidates() TypedLeaseCandidateInformer { return &leaseCandidateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/lease.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/lease.go index 66802fd94..458e2ce48 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/lease.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/lease.go @@ -34,12 +34,40 @@ import ( ) // LeaseInformer provides access to a shared informer and lister for -// Leases. +// Leases. Prefer using the type-safe variant (see [TypedLeaseInformer]). type LeaseInformer interface { Informer() cache.SharedIndexInformer Lister() coordinationv1beta1.LeaseLister } +// TypedLeaseInformer provides access to a shared informer and lister for +// Leases, including the type-safe TypedInformer variant. +// It is a superset of LeaseInformer. +type TypedLeaseInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() LeaseIndexInformer + Lister() coordinationv1beta1.LeaseLister +} + +// LeaseIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type LeaseIndexInformer cache.TypedSharedIndexInformer[*apicoordinationv1beta1.Lease] + +// LeaseHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Lease. +type LeaseHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicoordinationv1beta1.Lease] + +// LeaseDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Lease. +type LeaseDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicoordinationv1beta1.Lease] + +// LeaseFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Lease. +type LeaseFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicoordinationv1beta1.Lease] + +// LeaseIndexers is a specialization of [cache.TypedIndexers] for Lease. +type LeaseIndexers = cache.TypedIndexers[*apicoordinationv1beta1.Lease] + +// DeletedLease is a specialization of [cache.DeletedObject] for Lease. +type DeletedLease = cache.DeletedObject[*apicoordinationv1beta1.Lease] + type leaseInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type leaseInformer struct { // NewLeaseInformer constructs a new informer for Lease type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseInformer]). func NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedLeaseInformer constructs a new informer for Lease type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseIndexers) LeaseIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredLeaseInformer constructs a new informer for Lease type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredLeaseInformer]). func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredLeaseInformer constructs a new informer for Lease type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) LeaseIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewLeaseInformerWithOptions constructs a new informer for Lease type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseInformerWithOptions]). func NewLeaseInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedLeaseInformerWithOptions(client, namespace, options) +} + +// NewTypedLeaseInformerWithOptions constructs a new informer for Lease type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) LeaseIndexInformer { gvr := schema.GroupVersionResource{Group: "coordination.k8s.io", Version: "v1beta1", Resource: "leases"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.Lease](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewLeaseInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewLeaseInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedLeaseInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *leaseInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicoordinationv1beta1.Lease{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *leaseInformer) TypedInformer() LeaseIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.Lease](f.factory.InformerFor(&apicoordinationv1beta1.Lease{}, f.defaultInformer)) } func (f *leaseInformer) Lister() coordinationv1beta1.LeaseLister { return coordinationv1beta1.NewLeaseLister(f.Informer().GetIndexer()) } + +// ToTypedLeaseInformer converts an untyped informer into a TypedLeaseInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Lease. If that is not the case, calling type-safe methods of the returned +// TypedLeaseInformer leads to runtime panics. A safer alternative is to pass +// around a TypedLeaseInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedLeaseInformer(informer LeaseInformer) TypedLeaseInformer { + if informer, ok := informer.(TypedLeaseInformer); ok { + return informer + } + return &leaseTypedInformerAdapter{informer} +} + +type leaseTypedInformerAdapter struct { + LeaseInformer +} + +func (a *leaseTypedInformerAdapter) TypedInformer() LeaseIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.Lease](a.Informer()) +} + +// ToLeaseIndexInformer converts an untyped informer into a LeaseIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Lease. If that is not the case, calling type-safe methods of the returned +// LeaseIndexInformer leads to runtime panics. A safer alternative is to pass +// around a LeaseIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToLeaseIndexInformer(informer cache.SharedIndexInformer) LeaseIndexInformer { + if informer, ok := informer.(LeaseIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.Lease](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/leasecandidate.go b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/leasecandidate.go index ee83397f4..05cdf9a82 100644 --- a/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/leasecandidate.go +++ b/constraint/vendor/k8s.io/client-go/informers/coordination/v1beta1/leasecandidate.go @@ -34,12 +34,40 @@ import ( ) // LeaseCandidateInformer provides access to a shared informer and lister for -// LeaseCandidates. +// LeaseCandidates. Prefer using the type-safe variant (see [TypedLeaseCandidateInformer]). type LeaseCandidateInformer interface { Informer() cache.SharedIndexInformer Lister() coordinationv1beta1.LeaseCandidateLister } +// TypedLeaseCandidateInformer provides access to a shared informer and lister for +// LeaseCandidates, including the type-safe TypedInformer variant. +// It is a superset of LeaseCandidateInformer. +type TypedLeaseCandidateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() LeaseCandidateIndexInformer + Lister() coordinationv1beta1.LeaseCandidateLister +} + +// LeaseCandidateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type LeaseCandidateIndexInformer cache.TypedSharedIndexInformer[*apicoordinationv1beta1.LeaseCandidate] + +// LeaseCandidateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for LeaseCandidate. +type LeaseCandidateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicoordinationv1beta1.LeaseCandidate] + +// LeaseCandidateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for LeaseCandidate. +type LeaseCandidateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicoordinationv1beta1.LeaseCandidate] + +// LeaseCandidateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for LeaseCandidate. +type LeaseCandidateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicoordinationv1beta1.LeaseCandidate] + +// LeaseCandidateIndexers is a specialization of [cache.TypedIndexers] for LeaseCandidate. +type LeaseCandidateIndexers = cache.TypedIndexers[*apicoordinationv1beta1.LeaseCandidate] + +// DeletedLeaseCandidate is a specialization of [cache.DeletedObject] for LeaseCandidate. +type DeletedLeaseCandidate = cache.DeletedObject[*apicoordinationv1beta1.LeaseCandidate] + type leaseCandidateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type leaseCandidateInformer struct { // NewLeaseCandidateInformer constructs a new informer for LeaseCandidate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseCandidateInformer]). func NewLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseCandidateIndexers) LeaseCandidateIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredLeaseCandidateInformer constructs a new informer for LeaseCandidate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredLeaseCandidateInformer]). func NewFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredLeaseCandidateInformer constructs a new informer for LeaseCandidate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredLeaseCandidateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LeaseCandidateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) LeaseCandidateIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewLeaseCandidateInformerWithOptions constructs a new informer for LeaseCandidate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLeaseCandidateInformerWithOptions]). func NewLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedLeaseCandidateInformerWithOptions(client, namespace, options) +} + +// NewTypedLeaseCandidateInformerWithOptions constructs a new informer for LeaseCandidate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) LeaseCandidateIndexInformer { gvr := schema.GroupVersionResource{Group: "coordination.k8s.io", Version: "v1beta1", Resource: "leasecandidates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.LeaseCandidate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewLeaseCandidateInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *leaseCandidateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewLeaseCandidateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedLeaseCandidateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *leaseCandidateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicoordinationv1beta1.LeaseCandidate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *leaseCandidateInformer) TypedInformer() LeaseCandidateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.LeaseCandidate](f.factory.InformerFor(&apicoordinationv1beta1.LeaseCandidate{}, f.defaultInformer)) } func (f *leaseCandidateInformer) Lister() coordinationv1beta1.LeaseCandidateLister { return coordinationv1beta1.NewLeaseCandidateLister(f.Informer().GetIndexer()) } + +// ToTypedLeaseCandidateInformer converts an untyped informer into a TypedLeaseCandidateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LeaseCandidate. If that is not the case, calling type-safe methods of the returned +// TypedLeaseCandidateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedLeaseCandidateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedLeaseCandidateInformer(informer LeaseCandidateInformer) TypedLeaseCandidateInformer { + if informer, ok := informer.(TypedLeaseCandidateInformer); ok { + return informer + } + return &leaseCandidateTypedInformerAdapter{informer} +} + +type leaseCandidateTypedInformerAdapter struct { + LeaseCandidateInformer +} + +func (a *leaseCandidateTypedInformerAdapter) TypedInformer() LeaseCandidateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.LeaseCandidate](a.Informer()) +} + +// ToLeaseCandidateIndexInformer converts an untyped informer into a LeaseCandidateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LeaseCandidate. If that is not the case, calling type-safe methods of the returned +// LeaseCandidateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a LeaseCandidateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToLeaseCandidateIndexInformer(informer cache.SharedIndexInformer) LeaseCandidateIndexInformer { + if informer, ok := informer.(LeaseCandidateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicoordinationv1beta1.LeaseCandidate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/componentstatus.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/componentstatus.go index 5b6f6556c..97dbda2b4 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/componentstatus.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/componentstatus.go @@ -34,12 +34,40 @@ import ( ) // ComponentStatusInformer provides access to a shared informer and lister for -// ComponentStatuses. +// ComponentStatuses. Prefer using the type-safe variant (see [TypedComponentStatusInformer]). type ComponentStatusInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ComponentStatusLister } +// TypedComponentStatusInformer provides access to a shared informer and lister for +// ComponentStatuses, including the type-safe TypedInformer variant. +// It is a superset of ComponentStatusInformer. +type TypedComponentStatusInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ComponentStatusIndexInformer + Lister() corev1.ComponentStatusLister +} + +// ComponentStatusIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ComponentStatusIndexInformer cache.TypedSharedIndexInformer[*apicorev1.ComponentStatus] + +// ComponentStatusHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ComponentStatus. +type ComponentStatusHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.ComponentStatus] + +// ComponentStatusDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ComponentStatus. +type ComponentStatusDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.ComponentStatus] + +// ComponentStatusFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ComponentStatus. +type ComponentStatusFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.ComponentStatus] + +// ComponentStatusIndexers is a specialization of [cache.TypedIndexers] for ComponentStatus. +type ComponentStatusIndexers = cache.TypedIndexers[*apicorev1.ComponentStatus] + +// DeletedComponentStatus is a specialization of [cache.DeletedObject] for ComponentStatus. +type DeletedComponentStatus = cache.DeletedObject[*apicorev1.ComponentStatus] + type componentStatusInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type componentStatusInformer struct { // NewComponentStatusInformer constructs a new informer for ComponentStatus type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedComponentStatusInformer]). func NewComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedComponentStatusInformer constructs a new informer for ComponentStatus type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ComponentStatusIndexers) ComponentStatusIndexInformer { + return NewTypedComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredComponentStatusInformer constructs a new informer for ComponentStatus type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredComponentStatusInformer]). func NewFilteredComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredComponentStatusInformer constructs a new informer for ComponentStatus type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ComponentStatusIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ComponentStatusIndexInformer { + return NewTypedComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewComponentStatusInformerWithOptions constructs a new informer for ComponentStatus type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedComponentStatusInformerWithOptions]). func NewComponentStatusInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedComponentStatusInformerWithOptions(client, options) +} + +// NewTypedComponentStatusInformerWithOptions constructs a new informer for ComponentStatus type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedComponentStatusInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ComponentStatusIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "componentstatuss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.ComponentStatus](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewComponentStatusInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *componentStatusInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedComponentStatusInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *componentStatusInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.ComponentStatus{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *componentStatusInformer) TypedInformer() ComponentStatusIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ComponentStatus](f.factory.InformerFor(&apicorev1.ComponentStatus{}, f.defaultInformer)) } func (f *componentStatusInformer) Lister() corev1.ComponentStatusLister { return corev1.NewComponentStatusLister(f.Informer().GetIndexer()) } + +// ToTypedComponentStatusInformer converts an untyped informer into a TypedComponentStatusInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ComponentStatus. If that is not the case, calling type-safe methods of the returned +// TypedComponentStatusInformer leads to runtime panics. A safer alternative is to pass +// around a TypedComponentStatusInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedComponentStatusInformer(informer ComponentStatusInformer) TypedComponentStatusInformer { + if informer, ok := informer.(TypedComponentStatusInformer); ok { + return informer + } + return &componentStatusTypedInformerAdapter{informer} +} + +type componentStatusTypedInformerAdapter struct { + ComponentStatusInformer +} + +func (a *componentStatusTypedInformerAdapter) TypedInformer() ComponentStatusIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ComponentStatus](a.Informer()) +} + +// ToComponentStatusIndexInformer converts an untyped informer into a ComponentStatusIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ComponentStatus. If that is not the case, calling type-safe methods of the returned +// ComponentStatusIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ComponentStatusIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToComponentStatusIndexInformer(informer cache.SharedIndexInformer) ComponentStatusIndexInformer { + if informer, ok := informer.(ComponentStatusIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.ComponentStatus](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/configmap.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/configmap.go index 5b6389884..db84d2973 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/configmap.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/configmap.go @@ -34,12 +34,40 @@ import ( ) // ConfigMapInformer provides access to a shared informer and lister for -// ConfigMaps. +// ConfigMaps. Prefer using the type-safe variant (see [TypedConfigMapInformer]). type ConfigMapInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ConfigMapLister } +// TypedConfigMapInformer provides access to a shared informer and lister for +// ConfigMaps, including the type-safe TypedInformer variant. +// It is a superset of ConfigMapInformer. +type TypedConfigMapInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ConfigMapIndexInformer + Lister() corev1.ConfigMapLister +} + +// ConfigMapIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ConfigMapIndexInformer cache.TypedSharedIndexInformer[*apicorev1.ConfigMap] + +// ConfigMapHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ConfigMap. +type ConfigMapHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.ConfigMap] + +// ConfigMapDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ConfigMap. +type ConfigMapDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.ConfigMap] + +// ConfigMapFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ConfigMap. +type ConfigMapFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.ConfigMap] + +// ConfigMapIndexers is a specialization of [cache.TypedIndexers] for ConfigMap. +type ConfigMapIndexers = cache.TypedIndexers[*apicorev1.ConfigMap] + +// DeletedConfigMap is a specialization of [cache.DeletedObject] for ConfigMap. +type DeletedConfigMap = cache.DeletedObject[*apicorev1.ConfigMap] + type configMapInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type configMapInformer struct { // NewConfigMapInformer constructs a new informer for ConfigMap type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedConfigMapInformer]). func NewConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewConfigMapInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ConfigMapIndexers) ConfigMapIndexInformer { + return NewTypedConfigMapInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredConfigMapInformer constructs a new informer for ConfigMap type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredConfigMapInformer]). func NewFilteredConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewConfigMapInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedConfigMapInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredConfigMapInformer constructs a new informer for ConfigMap type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ConfigMapIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ConfigMapIndexInformer { + return NewTypedConfigMapInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewConfigMapInformerWithOptions constructs a new informer for ConfigMap type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedConfigMapInformerWithOptions]). func NewConfigMapInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedConfigMapInformerWithOptions(client, namespace, options) +} + +// NewTypedConfigMapInformerWithOptions constructs a new informer for ConfigMap type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedConfigMapInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ConfigMapIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "configmaps"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.ConfigMap](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewConfigMapInformerWithOptions(client kubernetes.Interface, namespace stri Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *configMapInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewConfigMapInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedConfigMapInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *configMapInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.ConfigMap{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *configMapInformer) TypedInformer() ConfigMapIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ConfigMap](f.factory.InformerFor(&apicorev1.ConfigMap{}, f.defaultInformer)) } func (f *configMapInformer) Lister() corev1.ConfigMapLister { return corev1.NewConfigMapLister(f.Informer().GetIndexer()) } + +// ToTypedConfigMapInformer converts an untyped informer into a TypedConfigMapInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ConfigMap. If that is not the case, calling type-safe methods of the returned +// TypedConfigMapInformer leads to runtime panics. A safer alternative is to pass +// around a TypedConfigMapInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedConfigMapInformer(informer ConfigMapInformer) TypedConfigMapInformer { + if informer, ok := informer.(TypedConfigMapInformer); ok { + return informer + } + return &configMapTypedInformerAdapter{informer} +} + +type configMapTypedInformerAdapter struct { + ConfigMapInformer +} + +func (a *configMapTypedInformerAdapter) TypedInformer() ConfigMapIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ConfigMap](a.Informer()) +} + +// ToConfigMapIndexInformer converts an untyped informer into a ConfigMapIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ConfigMap. If that is not the case, calling type-safe methods of the returned +// ConfigMapIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ConfigMapIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToConfigMapIndexInformer(informer cache.SharedIndexInformer) ConfigMapIndexInformer { + if informer, ok := informer.(ConfigMapIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.ConfigMap](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/endpoints.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/endpoints.go index 1609ce7f7..240967c3e 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/endpoints.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/endpoints.go @@ -34,12 +34,40 @@ import ( ) // EndpointsInformer provides access to a shared informer and lister for -// Endpoints. +// Endpoints. Prefer using the type-safe variant (see [TypedEndpointsInformer]). type EndpointsInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.EndpointsLister } +// TypedEndpointsInformer provides access to a shared informer and lister for +// Endpoints, including the type-safe TypedInformer variant. +// It is a superset of EndpointsInformer. +type TypedEndpointsInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EndpointsIndexInformer + Lister() corev1.EndpointsLister +} + +// EndpointsIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EndpointsIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Endpoints] + +// EndpointsHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Endpoints. +type EndpointsHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Endpoints] + +// EndpointsDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Endpoints. +type EndpointsDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Endpoints] + +// EndpointsFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Endpoints. +type EndpointsFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Endpoints] + +// EndpointsIndexers is a specialization of [cache.TypedIndexers] for Endpoints. +type EndpointsIndexers = cache.TypedIndexers[*apicorev1.Endpoints] + +// DeletedEndpoints is a specialization of [cache.DeletedObject] for Endpoints. +type DeletedEndpoints = cache.DeletedObject[*apicorev1.Endpoints] + type endpointsInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type endpointsInformer struct { // NewEndpointsInformer constructs a new informer for Endpoints type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointsInformer]). func NewEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEndpointsInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEndpointsInformer constructs a new informer for Endpoints type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointsIndexers) EndpointsIndexInformer { + return NewTypedEndpointsInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEndpointsInformer constructs a new informer for Endpoints type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEndpointsInformer]). func NewFilteredEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEndpointsInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEndpointsInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEndpointsInformer constructs a new informer for Endpoints type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointsIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EndpointsIndexInformer { + return NewTypedEndpointsInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEndpointsInformerWithOptions constructs a new informer for Endpoints type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointsInformerWithOptions]). func NewEndpointsInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEndpointsInformerWithOptions(client, namespace, options) +} + +// NewTypedEndpointsInformerWithOptions constructs a new informer for Endpoints type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointsInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EndpointsIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "endpointss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Endpoints](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEndpointsInformerWithOptions(client kubernetes.Interface, namespace stri Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *endpointsInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEndpointsInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEndpointsInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *endpointsInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Endpoints{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *endpointsInformer) TypedInformer() EndpointsIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Endpoints](f.factory.InformerFor(&apicorev1.Endpoints{}, f.defaultInformer)) } func (f *endpointsInformer) Lister() corev1.EndpointsLister { return corev1.NewEndpointsLister(f.Informer().GetIndexer()) } + +// ToTypedEndpointsInformer converts an untyped informer into a TypedEndpointsInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Endpoints. If that is not the case, calling type-safe methods of the returned +// TypedEndpointsInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEndpointsInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEndpointsInformer(informer EndpointsInformer) TypedEndpointsInformer { + if informer, ok := informer.(TypedEndpointsInformer); ok { + return informer + } + return &endpointsTypedInformerAdapter{informer} +} + +type endpointsTypedInformerAdapter struct { + EndpointsInformer +} + +func (a *endpointsTypedInformerAdapter) TypedInformer() EndpointsIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Endpoints](a.Informer()) +} + +// ToEndpointsIndexInformer converts an untyped informer into a EndpointsIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Endpoints. If that is not the case, calling type-safe methods of the returned +// EndpointsIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EndpointsIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEndpointsIndexInformer(informer cache.SharedIndexInformer) EndpointsIndexInformer { + if informer, ok := informer.(EndpointsIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Endpoints](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/event.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/event.go index ff9c3c584..65c078565 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/event.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/event.go @@ -34,12 +34,40 @@ import ( ) // EventInformer provides access to a shared informer and lister for -// Events. +// Events. Prefer using the type-safe variant (see [TypedEventInformer]). type EventInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.EventLister } +// TypedEventInformer provides access to a shared informer and lister for +// Events, including the type-safe TypedInformer variant. +// It is a superset of EventInformer. +type TypedEventInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EventIndexInformer + Lister() corev1.EventLister +} + +// EventIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EventIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Event] + +// EventHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Event. +type EventHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Event] + +// EventDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Event. +type EventDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Event] + +// EventFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Event. +type EventFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Event] + +// EventIndexers is a specialization of [cache.TypedIndexers] for Event. +type EventIndexers = cache.TypedIndexers[*apicorev1.Event] + +// DeletedEvent is a specialization of [cache.DeletedObject] for Event. +type DeletedEvent = cache.DeletedObject[*apicorev1.Event] + type eventInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type eventInformer struct { // NewEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformer]). func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEventInformer]). func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEventInformerWithOptions constructs a new informer for Event type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformerWithOptions]). func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, options) +} + +// NewTypedEventInformerWithOptions constructs a new informer for Event type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EventIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "events"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Event](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *eventInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Event{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *eventInformer) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Event](f.factory.InformerFor(&apicorev1.Event{}, f.defaultInformer)) } func (f *eventInformer) Lister() corev1.EventLister { return corev1.NewEventLister(f.Informer().GetIndexer()) } + +// ToTypedEventInformer converts an untyped informer into a TypedEventInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// TypedEventInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEventInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEventInformer(informer EventInformer) TypedEventInformer { + if informer, ok := informer.(TypedEventInformer); ok { + return informer + } + return &eventTypedInformerAdapter{informer} +} + +type eventTypedInformerAdapter struct { + EventInformer +} + +func (a *eventTypedInformerAdapter) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Event](a.Informer()) +} + +// ToEventIndexInformer converts an untyped informer into a EventIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// EventIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EventIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEventIndexInformer(informer cache.SharedIndexInformer) EventIndexInformer { + if informer, ok := informer.(EventIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Event](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/interface.go index b2216a05c..a951b30bd 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/interface.go @@ -25,37 +25,37 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ComponentStatuses returns a ComponentStatusInformer. - ComponentStatuses() ComponentStatusInformer + ComponentStatuses() TypedComponentStatusInformer // ConfigMaps returns a ConfigMapInformer. - ConfigMaps() ConfigMapInformer + ConfigMaps() TypedConfigMapInformer // Endpoints returns a EndpointsInformer. - Endpoints() EndpointsInformer + Endpoints() TypedEndpointsInformer // Events returns a EventInformer. - Events() EventInformer + Events() TypedEventInformer // LimitRanges returns a LimitRangeInformer. - LimitRanges() LimitRangeInformer + LimitRanges() TypedLimitRangeInformer // Namespaces returns a NamespaceInformer. - Namespaces() NamespaceInformer + Namespaces() TypedNamespaceInformer // Nodes returns a NodeInformer. - Nodes() NodeInformer + Nodes() TypedNodeInformer // PersistentVolumes returns a PersistentVolumeInformer. - PersistentVolumes() PersistentVolumeInformer + PersistentVolumes() TypedPersistentVolumeInformer // PersistentVolumeClaims returns a PersistentVolumeClaimInformer. - PersistentVolumeClaims() PersistentVolumeClaimInformer + PersistentVolumeClaims() TypedPersistentVolumeClaimInformer // Pods returns a PodInformer. - Pods() PodInformer + Pods() TypedPodInformer // PodTemplates returns a PodTemplateInformer. - PodTemplates() PodTemplateInformer + PodTemplates() TypedPodTemplateInformer // ReplicationControllers returns a ReplicationControllerInformer. - ReplicationControllers() ReplicationControllerInformer + ReplicationControllers() TypedReplicationControllerInformer // ResourceQuotas returns a ResourceQuotaInformer. - ResourceQuotas() ResourceQuotaInformer + ResourceQuotas() TypedResourceQuotaInformer // Secrets returns a SecretInformer. - Secrets() SecretInformer + Secrets() TypedSecretInformer // Services returns a ServiceInformer. - Services() ServiceInformer + Services() TypedServiceInformer // ServiceAccounts returns a ServiceAccountInformer. - ServiceAccounts() ServiceAccountInformer + ServiceAccounts() TypedServiceAccountInformer } type version struct { @@ -69,82 +69,82 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ComponentStatuses returns a ComponentStatusInformer. -func (v *version) ComponentStatuses() ComponentStatusInformer { +// ComponentStatuses returns a TypedComponentStatusInformer. +func (v *version) ComponentStatuses() TypedComponentStatusInformer { return &componentStatusInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ConfigMaps returns a ConfigMapInformer. -func (v *version) ConfigMaps() ConfigMapInformer { +// ConfigMaps returns a TypedConfigMapInformer. +func (v *version) ConfigMaps() TypedConfigMapInformer { return &configMapInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Endpoints returns a EndpointsInformer. -func (v *version) Endpoints() EndpointsInformer { +// Endpoints returns a TypedEndpointsInformer. +func (v *version) Endpoints() TypedEndpointsInformer { return &endpointsInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Events returns a EventInformer. -func (v *version) Events() EventInformer { +// Events returns a TypedEventInformer. +func (v *version) Events() TypedEventInformer { return &eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// LimitRanges returns a LimitRangeInformer. -func (v *version) LimitRanges() LimitRangeInformer { +// LimitRanges returns a TypedLimitRangeInformer. +func (v *version) LimitRanges() TypedLimitRangeInformer { return &limitRangeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Namespaces returns a NamespaceInformer. -func (v *version) Namespaces() NamespaceInformer { +// Namespaces returns a TypedNamespaceInformer. +func (v *version) Namespaces() TypedNamespaceInformer { return &namespaceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Nodes returns a NodeInformer. -func (v *version) Nodes() NodeInformer { +// Nodes returns a TypedNodeInformer. +func (v *version) Nodes() TypedNodeInformer { return &nodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PersistentVolumes returns a PersistentVolumeInformer. -func (v *version) PersistentVolumes() PersistentVolumeInformer { +// PersistentVolumes returns a TypedPersistentVolumeInformer. +func (v *version) PersistentVolumes() TypedPersistentVolumeInformer { return &persistentVolumeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PersistentVolumeClaims returns a PersistentVolumeClaimInformer. -func (v *version) PersistentVolumeClaims() PersistentVolumeClaimInformer { +// PersistentVolumeClaims returns a TypedPersistentVolumeClaimInformer. +func (v *version) PersistentVolumeClaims() TypedPersistentVolumeClaimInformer { return &persistentVolumeClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Pods returns a PodInformer. -func (v *version) Pods() PodInformer { +// Pods returns a TypedPodInformer. +func (v *version) Pods() TypedPodInformer { return &podInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// PodTemplates returns a PodTemplateInformer. -func (v *version) PodTemplates() PodTemplateInformer { +// PodTemplates returns a TypedPodTemplateInformer. +func (v *version) PodTemplates() TypedPodTemplateInformer { return &podTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ReplicationControllers returns a ReplicationControllerInformer. -func (v *version) ReplicationControllers() ReplicationControllerInformer { +// ReplicationControllers returns a TypedReplicationControllerInformer. +func (v *version) ReplicationControllers() TypedReplicationControllerInformer { return &replicationControllerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceQuotas returns a ResourceQuotaInformer. -func (v *version) ResourceQuotas() ResourceQuotaInformer { +// ResourceQuotas returns a TypedResourceQuotaInformer. +func (v *version) ResourceQuotas() TypedResourceQuotaInformer { return &resourceQuotaInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Secrets returns a SecretInformer. -func (v *version) Secrets() SecretInformer { +// Secrets returns a TypedSecretInformer. +func (v *version) Secrets() TypedSecretInformer { return &secretInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Services returns a ServiceInformer. -func (v *version) Services() ServiceInformer { +// Services returns a TypedServiceInformer. +func (v *version) Services() TypedServiceInformer { return &serviceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ServiceAccounts returns a ServiceAccountInformer. -func (v *version) ServiceAccounts() ServiceAccountInformer { +// ServiceAccounts returns a TypedServiceAccountInformer. +func (v *version) ServiceAccounts() TypedServiceAccountInformer { return &serviceAccountInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/limitrange.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/limitrange.go index a3a01de6d..a71e4496b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/limitrange.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/limitrange.go @@ -34,12 +34,40 @@ import ( ) // LimitRangeInformer provides access to a shared informer and lister for -// LimitRanges. +// LimitRanges. Prefer using the type-safe variant (see [TypedLimitRangeInformer]). type LimitRangeInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.LimitRangeLister } +// TypedLimitRangeInformer provides access to a shared informer and lister for +// LimitRanges, including the type-safe TypedInformer variant. +// It is a superset of LimitRangeInformer. +type TypedLimitRangeInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() LimitRangeIndexInformer + Lister() corev1.LimitRangeLister +} + +// LimitRangeIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type LimitRangeIndexInformer cache.TypedSharedIndexInformer[*apicorev1.LimitRange] + +// LimitRangeHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for LimitRange. +type LimitRangeHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.LimitRange] + +// LimitRangeDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for LimitRange. +type LimitRangeDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.LimitRange] + +// LimitRangeFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for LimitRange. +type LimitRangeFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.LimitRange] + +// LimitRangeIndexers is a specialization of [cache.TypedIndexers] for LimitRange. +type LimitRangeIndexers = cache.TypedIndexers[*apicorev1.LimitRange] + +// DeletedLimitRange is a specialization of [cache.DeletedObject] for LimitRange. +type DeletedLimitRange = cache.DeletedObject[*apicorev1.LimitRange] + type limitRangeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type limitRangeInformer struct { // NewLimitRangeInformer constructs a new informer for LimitRange type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLimitRangeInformer]). func NewLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewLimitRangeInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedLimitRangeInformer constructs a new informer for LimitRange type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LimitRangeIndexers) LimitRangeIndexInformer { + return NewTypedLimitRangeInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredLimitRangeInformer constructs a new informer for LimitRange type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredLimitRangeInformer]). func NewFilteredLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewLimitRangeInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedLimitRangeInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredLimitRangeInformer constructs a new informer for LimitRange type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers LimitRangeIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) LimitRangeIndexInformer { + return NewTypedLimitRangeInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewLimitRangeInformerWithOptions constructs a new informer for LimitRange type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedLimitRangeInformerWithOptions]). func NewLimitRangeInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedLimitRangeInformerWithOptions(client, namespace, options) +} + +// NewTypedLimitRangeInformerWithOptions constructs a new informer for LimitRange type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedLimitRangeInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) LimitRangeIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "limitranges"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.LimitRange](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewLimitRangeInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *limitRangeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewLimitRangeInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedLimitRangeInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *limitRangeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.LimitRange{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *limitRangeInformer) TypedInformer() LimitRangeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.LimitRange](f.factory.InformerFor(&apicorev1.LimitRange{}, f.defaultInformer)) } func (f *limitRangeInformer) Lister() corev1.LimitRangeLister { return corev1.NewLimitRangeLister(f.Informer().GetIndexer()) } + +// ToTypedLimitRangeInformer converts an untyped informer into a TypedLimitRangeInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LimitRange. If that is not the case, calling type-safe methods of the returned +// TypedLimitRangeInformer leads to runtime panics. A safer alternative is to pass +// around a TypedLimitRangeInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedLimitRangeInformer(informer LimitRangeInformer) TypedLimitRangeInformer { + if informer, ok := informer.(TypedLimitRangeInformer); ok { + return informer + } + return &limitRangeTypedInformerAdapter{informer} +} + +type limitRangeTypedInformerAdapter struct { + LimitRangeInformer +} + +func (a *limitRangeTypedInformerAdapter) TypedInformer() LimitRangeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.LimitRange](a.Informer()) +} + +// ToLimitRangeIndexInformer converts an untyped informer into a LimitRangeIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *LimitRange. If that is not the case, calling type-safe methods of the returned +// LimitRangeIndexInformer leads to runtime panics. A safer alternative is to pass +// around a LimitRangeIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToLimitRangeIndexInformer(informer cache.SharedIndexInformer) LimitRangeIndexInformer { + if informer, ok := informer.(LimitRangeIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.LimitRange](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/namespace.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/namespace.go index c2a989441..38d12c9b3 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/namespace.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/namespace.go @@ -34,12 +34,40 @@ import ( ) // NamespaceInformer provides access to a shared informer and lister for -// Namespaces. +// Namespaces. Prefer using the type-safe variant (see [TypedNamespaceInformer]). type NamespaceInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.NamespaceLister } +// TypedNamespaceInformer provides access to a shared informer and lister for +// Namespaces, including the type-safe TypedInformer variant. +// It is a superset of NamespaceInformer. +type TypedNamespaceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() NamespaceIndexInformer + Lister() corev1.NamespaceLister +} + +// NamespaceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type NamespaceIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Namespace] + +// NamespaceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Namespace. +type NamespaceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Namespace] + +// NamespaceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Namespace. +type NamespaceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Namespace] + +// NamespaceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Namespace. +type NamespaceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Namespace] + +// NamespaceIndexers is a specialization of [cache.TypedIndexers] for Namespace. +type NamespaceIndexers = cache.TypedIndexers[*apicorev1.Namespace] + +// DeletedNamespace is a specialization of [cache.DeletedObject] for Namespace. +type DeletedNamespace = cache.DeletedObject[*apicorev1.Namespace] + type namespaceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type namespaceInformer struct { // NewNamespaceInformer constructs a new informer for Namespace type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNamespaceInformer]). func NewNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedNamespaceInformer constructs a new informer for Namespace type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers NamespaceIndexers) NamespaceIndexInformer { + return NewTypedNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredNamespaceInformer constructs a new informer for Namespace type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredNamespaceInformer]). func NewFilteredNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredNamespaceInformer constructs a new informer for Namespace type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers NamespaceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) NamespaceIndexInformer { + return NewTypedNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewNamespaceInformerWithOptions constructs a new informer for Namespace type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNamespaceInformerWithOptions]). func NewNamespaceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedNamespaceInformerWithOptions(client, options) +} + +// NewTypedNamespaceInformerWithOptions constructs a new informer for Namespace type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNamespaceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) NamespaceIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Namespace](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewNamespaceInformerWithOptions(client kubernetes.Interface, options intern Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *namespaceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedNamespaceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *namespaceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Namespace{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *namespaceInformer) TypedInformer() NamespaceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Namespace](f.factory.InformerFor(&apicorev1.Namespace{}, f.defaultInformer)) } func (f *namespaceInformer) Lister() corev1.NamespaceLister { return corev1.NewNamespaceLister(f.Informer().GetIndexer()) } + +// ToTypedNamespaceInformer converts an untyped informer into a TypedNamespaceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Namespace. If that is not the case, calling type-safe methods of the returned +// TypedNamespaceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedNamespaceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedNamespaceInformer(informer NamespaceInformer) TypedNamespaceInformer { + if informer, ok := informer.(TypedNamespaceInformer); ok { + return informer + } + return &namespaceTypedInformerAdapter{informer} +} + +type namespaceTypedInformerAdapter struct { + NamespaceInformer +} + +func (a *namespaceTypedInformerAdapter) TypedInformer() NamespaceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Namespace](a.Informer()) +} + +// ToNamespaceIndexInformer converts an untyped informer into a NamespaceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Namespace. If that is not the case, calling type-safe methods of the returned +// NamespaceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a NamespaceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToNamespaceIndexInformer(informer cache.SharedIndexInformer) NamespaceIndexInformer { + if informer, ok := informer.(NamespaceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Namespace](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/node.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/node.go index 48e8d7d6a..9e706202f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/node.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/node.go @@ -34,12 +34,40 @@ import ( ) // NodeInformer provides access to a shared informer and lister for -// Nodes. +// Nodes. Prefer using the type-safe variant (see [TypedNodeInformer]). type NodeInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.NodeLister } +// TypedNodeInformer provides access to a shared informer and lister for +// Nodes, including the type-safe TypedInformer variant. +// It is a superset of NodeInformer. +type TypedNodeInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() NodeIndexInformer + Lister() corev1.NodeLister +} + +// NodeIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type NodeIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Node] + +// NodeHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Node. +type NodeHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Node] + +// NodeDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Node. +type NodeDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Node] + +// NodeFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Node. +type NodeFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Node] + +// NodeIndexers is a specialization of [cache.TypedIndexers] for Node. +type NodeIndexers = cache.TypedIndexers[*apicorev1.Node] + +// DeletedNode is a specialization of [cache.DeletedObject] for Node. +type DeletedNode = cache.DeletedObject[*apicorev1.Node] + type nodeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type nodeInformer struct { // NewNodeInformer constructs a new informer for Node type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNodeInformer]). func NewNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedNodeInformer constructs a new informer for Node type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers NodeIndexers) NodeIndexInformer { + return NewTypedNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredNodeInformer constructs a new informer for Node type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredNodeInformer]). func NewFilteredNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredNodeInformer constructs a new informer for Node type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers NodeIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) NodeIndexInformer { + return NewTypedNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewNodeInformerWithOptions constructs a new informer for Node type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNodeInformerWithOptions]). func NewNodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedNodeInformerWithOptions(client, options) +} + +// NewTypedNodeInformerWithOptions constructs a new informer for Node type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) NodeIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "nodes"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Node](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewNodeInformerWithOptions(client kubernetes.Interface, options internalint Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *nodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedNodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *nodeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Node{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *nodeInformer) TypedInformer() NodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Node](f.factory.InformerFor(&apicorev1.Node{}, f.defaultInformer)) } func (f *nodeInformer) Lister() corev1.NodeLister { return corev1.NewNodeLister(f.Informer().GetIndexer()) } + +// ToTypedNodeInformer converts an untyped informer into a TypedNodeInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Node. If that is not the case, calling type-safe methods of the returned +// TypedNodeInformer leads to runtime panics. A safer alternative is to pass +// around a TypedNodeInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedNodeInformer(informer NodeInformer) TypedNodeInformer { + if informer, ok := informer.(TypedNodeInformer); ok { + return informer + } + return &nodeTypedInformerAdapter{informer} +} + +type nodeTypedInformerAdapter struct { + NodeInformer +} + +func (a *nodeTypedInformerAdapter) TypedInformer() NodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Node](a.Informer()) +} + +// ToNodeIndexInformer converts an untyped informer into a NodeIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Node. If that is not the case, calling type-safe methods of the returned +// NodeIndexInformer leads to runtime panics. A safer alternative is to pass +// around a NodeIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToNodeIndexInformer(informer cache.SharedIndexInformer) NodeIndexInformer { + if informer, ok := informer.(NodeIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Node](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolume.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolume.go index aebe7ffa8..d55333ce8 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolume.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolume.go @@ -34,12 +34,40 @@ import ( ) // PersistentVolumeInformer provides access to a shared informer and lister for -// PersistentVolumes. +// PersistentVolumes. Prefer using the type-safe variant (see [TypedPersistentVolumeInformer]). type PersistentVolumeInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.PersistentVolumeLister } +// TypedPersistentVolumeInformer provides access to a shared informer and lister for +// PersistentVolumes, including the type-safe TypedInformer variant. +// It is a superset of PersistentVolumeInformer. +type TypedPersistentVolumeInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PersistentVolumeIndexInformer + Lister() corev1.PersistentVolumeLister +} + +// PersistentVolumeIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PersistentVolumeIndexInformer cache.TypedSharedIndexInformer[*apicorev1.PersistentVolume] + +// PersistentVolumeHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PersistentVolume. +type PersistentVolumeHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.PersistentVolume] + +// PersistentVolumeDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PersistentVolume. +type PersistentVolumeDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.PersistentVolume] + +// PersistentVolumeFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PersistentVolume. +type PersistentVolumeFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.PersistentVolume] + +// PersistentVolumeIndexers is a specialization of [cache.TypedIndexers] for PersistentVolume. +type PersistentVolumeIndexers = cache.TypedIndexers[*apicorev1.PersistentVolume] + +// DeletedPersistentVolume is a specialization of [cache.DeletedObject] for PersistentVolume. +type DeletedPersistentVolume = cache.DeletedObject[*apicorev1.PersistentVolume] + type persistentVolumeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type persistentVolumeInformer struct { // NewPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPersistentVolumeInformer]). func NewPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPersistentVolumeInformer constructs a new informer for PersistentVolume type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PersistentVolumeIndexers) PersistentVolumeIndexInformer { + return NewTypedPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPersistentVolumeInformer]). func NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPersistentVolumeInformer constructs a new informer for PersistentVolume type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PersistentVolumeIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PersistentVolumeIndexInformer { + return NewTypedPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPersistentVolumeInformerWithOptions constructs a new informer for PersistentVolume type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPersistentVolumeInformerWithOptions]). func NewPersistentVolumeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPersistentVolumeInformerWithOptions(client, options) +} + +// NewTypedPersistentVolumeInformerWithOptions constructs a new informer for PersistentVolume type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPersistentVolumeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PersistentVolumeIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "persistentvolumes"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolume](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPersistentVolumeInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *persistentVolumeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPersistentVolumeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *persistentVolumeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.PersistentVolume{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *persistentVolumeInformer) TypedInformer() PersistentVolumeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolume](f.factory.InformerFor(&apicorev1.PersistentVolume{}, f.defaultInformer)) } func (f *persistentVolumeInformer) Lister() corev1.PersistentVolumeLister { return corev1.NewPersistentVolumeLister(f.Informer().GetIndexer()) } + +// ToTypedPersistentVolumeInformer converts an untyped informer into a TypedPersistentVolumeInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PersistentVolume. If that is not the case, calling type-safe methods of the returned +// TypedPersistentVolumeInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPersistentVolumeInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPersistentVolumeInformer(informer PersistentVolumeInformer) TypedPersistentVolumeInformer { + if informer, ok := informer.(TypedPersistentVolumeInformer); ok { + return informer + } + return &persistentVolumeTypedInformerAdapter{informer} +} + +type persistentVolumeTypedInformerAdapter struct { + PersistentVolumeInformer +} + +func (a *persistentVolumeTypedInformerAdapter) TypedInformer() PersistentVolumeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolume](a.Informer()) +} + +// ToPersistentVolumeIndexInformer converts an untyped informer into a PersistentVolumeIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PersistentVolume. If that is not the case, calling type-safe methods of the returned +// PersistentVolumeIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PersistentVolumeIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPersistentVolumeIndexInformer(informer cache.SharedIndexInformer) PersistentVolumeIndexInformer { + if informer, ok := informer.(PersistentVolumeIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolume](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go index 973b5571e..c14ab0d8e 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go @@ -34,12 +34,40 @@ import ( ) // PersistentVolumeClaimInformer provides access to a shared informer and lister for -// PersistentVolumeClaims. +// PersistentVolumeClaims. Prefer using the type-safe variant (see [TypedPersistentVolumeClaimInformer]). type PersistentVolumeClaimInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.PersistentVolumeClaimLister } +// TypedPersistentVolumeClaimInformer provides access to a shared informer and lister for +// PersistentVolumeClaims, including the type-safe TypedInformer variant. +// It is a superset of PersistentVolumeClaimInformer. +type TypedPersistentVolumeClaimInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PersistentVolumeClaimIndexInformer + Lister() corev1.PersistentVolumeClaimLister +} + +// PersistentVolumeClaimIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PersistentVolumeClaimIndexInformer cache.TypedSharedIndexInformer[*apicorev1.PersistentVolumeClaim] + +// PersistentVolumeClaimHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PersistentVolumeClaim. +type PersistentVolumeClaimHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.PersistentVolumeClaim] + +// PersistentVolumeClaimDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PersistentVolumeClaim. +type PersistentVolumeClaimDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.PersistentVolumeClaim] + +// PersistentVolumeClaimFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PersistentVolumeClaim. +type PersistentVolumeClaimFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.PersistentVolumeClaim] + +// PersistentVolumeClaimIndexers is a specialization of [cache.TypedIndexers] for PersistentVolumeClaim. +type PersistentVolumeClaimIndexers = cache.TypedIndexers[*apicorev1.PersistentVolumeClaim] + +// DeletedPersistentVolumeClaim is a specialization of [cache.DeletedObject] for PersistentVolumeClaim. +type DeletedPersistentVolumeClaim = cache.DeletedObject[*apicorev1.PersistentVolumeClaim] + type persistentVolumeClaimInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type persistentVolumeClaimInformer struct { // NewPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPersistentVolumeClaimInformer]). func NewPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPersistentVolumeClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PersistentVolumeClaimIndexers) PersistentVolumeClaimIndexInformer { + return NewTypedPersistentVolumeClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPersistentVolumeClaimInformer]). func NewFilteredPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPersistentVolumeClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPersistentVolumeClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PersistentVolumeClaimIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PersistentVolumeClaimIndexInformer { + return NewTypedPersistentVolumeClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPersistentVolumeClaimInformerWithOptions constructs a new informer for PersistentVolumeClaim type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPersistentVolumeClaimInformerWithOptions]). func NewPersistentVolumeClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPersistentVolumeClaimInformerWithOptions(client, namespace, options) +} + +// NewTypedPersistentVolumeClaimInformerWithOptions constructs a new informer for PersistentVolumeClaim type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPersistentVolumeClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PersistentVolumeClaimIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "persistentvolumeclaims"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolumeClaim](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPersistentVolumeClaimInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *persistentVolumeClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPersistentVolumeClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPersistentVolumeClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *persistentVolumeClaimInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.PersistentVolumeClaim{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *persistentVolumeClaimInformer) TypedInformer() PersistentVolumeClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolumeClaim](f.factory.InformerFor(&apicorev1.PersistentVolumeClaim{}, f.defaultInformer)) } func (f *persistentVolumeClaimInformer) Lister() corev1.PersistentVolumeClaimLister { return corev1.NewPersistentVolumeClaimLister(f.Informer().GetIndexer()) } + +// ToTypedPersistentVolumeClaimInformer converts an untyped informer into a TypedPersistentVolumeClaimInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PersistentVolumeClaim. If that is not the case, calling type-safe methods of the returned +// TypedPersistentVolumeClaimInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPersistentVolumeClaimInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPersistentVolumeClaimInformer(informer PersistentVolumeClaimInformer) TypedPersistentVolumeClaimInformer { + if informer, ok := informer.(TypedPersistentVolumeClaimInformer); ok { + return informer + } + return &persistentVolumeClaimTypedInformerAdapter{informer} +} + +type persistentVolumeClaimTypedInformerAdapter struct { + PersistentVolumeClaimInformer +} + +func (a *persistentVolumeClaimTypedInformerAdapter) TypedInformer() PersistentVolumeClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolumeClaim](a.Informer()) +} + +// ToPersistentVolumeClaimIndexInformer converts an untyped informer into a PersistentVolumeClaimIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PersistentVolumeClaim. If that is not the case, calling type-safe methods of the returned +// PersistentVolumeClaimIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PersistentVolumeClaimIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPersistentVolumeClaimIndexInformer(informer cache.SharedIndexInformer) PersistentVolumeClaimIndexInformer { + if informer, ok := informer.(PersistentVolumeClaimIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.PersistentVolumeClaim](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/pod.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/pod.go index f49dee3de..dac8c6d0c 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/pod.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/pod.go @@ -34,12 +34,40 @@ import ( ) // PodInformer provides access to a shared informer and lister for -// Pods. +// Pods. Prefer using the type-safe variant (see [TypedPodInformer]). type PodInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.PodLister } +// TypedPodInformer provides access to a shared informer and lister for +// Pods, including the type-safe TypedInformer variant. +// It is a superset of PodInformer. +type TypedPodInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodIndexInformer + Lister() corev1.PodLister +} + +// PodIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Pod] + +// PodHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Pod. +type PodHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Pod] + +// PodDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Pod. +type PodDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Pod] + +// PodFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Pod. +type PodFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Pod] + +// PodIndexers is a specialization of [cache.TypedIndexers] for Pod. +type PodIndexers = cache.TypedIndexers[*apicorev1.Pod] + +// DeletedPod is a specialization of [cache.DeletedObject] for Pod. +type DeletedPod = cache.DeletedObject[*apicorev1.Pod] + type podInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type podInformer struct { // NewPodInformer constructs a new informer for Pod type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodInformer]). func NewPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPodInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPodInformer constructs a new informer for Pod type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodIndexers) PodIndexInformer { + return NewTypedPodInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPodInformer constructs a new informer for Pod type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodInformer]). func NewFilteredPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPodInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodInformer constructs a new informer for Pod type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodIndexInformer { + return NewTypedPodInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPodInformerWithOptions constructs a new informer for Pod type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodInformerWithOptions]). func NewPodInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodInformerWithOptions(client, namespace, options) +} + +// NewTypedPodInformerWithOptions constructs a new informer for Pod type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Pod](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPodInformerWithOptions(client kubernetes.Interface, namespace string, op Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *podInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPodInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *podInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Pod{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *podInformer) TypedInformer() PodIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Pod](f.factory.InformerFor(&apicorev1.Pod{}, f.defaultInformer)) } func (f *podInformer) Lister() corev1.PodLister { return corev1.NewPodLister(f.Informer().GetIndexer()) } + +// ToTypedPodInformer converts an untyped informer into a TypedPodInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Pod. If that is not the case, calling type-safe methods of the returned +// TypedPodInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodInformer(informer PodInformer) TypedPodInformer { + if informer, ok := informer.(TypedPodInformer); ok { + return informer + } + return &podTypedInformerAdapter{informer} +} + +type podTypedInformerAdapter struct { + PodInformer +} + +func (a *podTypedInformerAdapter) TypedInformer() PodIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Pod](a.Informer()) +} + +// ToPodIndexInformer converts an untyped informer into a PodIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Pod. If that is not the case, calling type-safe methods of the returned +// PodIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodIndexInformer(informer cache.SharedIndexInformer) PodIndexInformer { + if informer, ok := informer.(PodIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Pod](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/podtemplate.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/podtemplate.go index 940ae2599..4b705902a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/podtemplate.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/podtemplate.go @@ -34,12 +34,40 @@ import ( ) // PodTemplateInformer provides access to a shared informer and lister for -// PodTemplates. +// PodTemplates. Prefer using the type-safe variant (see [TypedPodTemplateInformer]). type PodTemplateInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.PodTemplateLister } +// TypedPodTemplateInformer provides access to a shared informer and lister for +// PodTemplates, including the type-safe TypedInformer variant. +// It is a superset of PodTemplateInformer. +type TypedPodTemplateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodTemplateIndexInformer + Lister() corev1.PodTemplateLister +} + +// PodTemplateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodTemplateIndexInformer cache.TypedSharedIndexInformer[*apicorev1.PodTemplate] + +// PodTemplateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodTemplate. +type PodTemplateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.PodTemplate] + +// PodTemplateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodTemplate. +type PodTemplateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.PodTemplate] + +// PodTemplateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodTemplate. +type PodTemplateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.PodTemplate] + +// PodTemplateIndexers is a specialization of [cache.TypedIndexers] for PodTemplate. +type PodTemplateIndexers = cache.TypedIndexers[*apicorev1.PodTemplate] + +// DeletedPodTemplate is a specialization of [cache.DeletedObject] for PodTemplate. +type DeletedPodTemplate = cache.DeletedObject[*apicorev1.PodTemplate] + type podTemplateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type podTemplateInformer struct { // NewPodTemplateInformer constructs a new informer for PodTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodTemplateInformer]). func NewPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPodTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPodTemplateInformer constructs a new informer for PodTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodTemplateIndexers) PodTemplateIndexInformer { + return NewTypedPodTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPodTemplateInformer constructs a new informer for PodTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodTemplateInformer]). func NewFilteredPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPodTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodTemplateInformer constructs a new informer for PodTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodTemplateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodTemplateIndexInformer { + return NewTypedPodTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPodTemplateInformerWithOptions constructs a new informer for PodTemplate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodTemplateInformerWithOptions]). func NewPodTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodTemplateInformerWithOptions(client, namespace, options) +} + +// NewTypedPodTemplateInformerWithOptions constructs a new informer for PodTemplate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodTemplateIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "podtemplates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.PodTemplate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPodTemplateInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *podTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPodTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *podTemplateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.PodTemplate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *podTemplateInformer) TypedInformer() PodTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PodTemplate](f.factory.InformerFor(&apicorev1.PodTemplate{}, f.defaultInformer)) } func (f *podTemplateInformer) Lister() corev1.PodTemplateLister { return corev1.NewPodTemplateLister(f.Informer().GetIndexer()) } + +// ToTypedPodTemplateInformer converts an untyped informer into a TypedPodTemplateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodTemplate. If that is not the case, calling type-safe methods of the returned +// TypedPodTemplateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodTemplateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodTemplateInformer(informer PodTemplateInformer) TypedPodTemplateInformer { + if informer, ok := informer.(TypedPodTemplateInformer); ok { + return informer + } + return &podTemplateTypedInformerAdapter{informer} +} + +type podTemplateTypedInformerAdapter struct { + PodTemplateInformer +} + +func (a *podTemplateTypedInformerAdapter) TypedInformer() PodTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.PodTemplate](a.Informer()) +} + +// ToPodTemplateIndexInformer converts an untyped informer into a PodTemplateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodTemplate. If that is not the case, calling type-safe methods of the returned +// PodTemplateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodTemplateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodTemplateIndexInformer(informer cache.SharedIndexInformer) PodTemplateIndexInformer { + if informer, ok := informer.(PodTemplateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.PodTemplate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/replicationcontroller.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/replicationcontroller.go index ec323d3c6..8612653d1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/replicationcontroller.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/replicationcontroller.go @@ -34,12 +34,40 @@ import ( ) // ReplicationControllerInformer provides access to a shared informer and lister for -// ReplicationControllers. +// ReplicationControllers. Prefer using the type-safe variant (see [TypedReplicationControllerInformer]). type ReplicationControllerInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ReplicationControllerLister } +// TypedReplicationControllerInformer provides access to a shared informer and lister for +// ReplicationControllers, including the type-safe TypedInformer variant. +// It is a superset of ReplicationControllerInformer. +type TypedReplicationControllerInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ReplicationControllerIndexInformer + Lister() corev1.ReplicationControllerLister +} + +// ReplicationControllerIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ReplicationControllerIndexInformer cache.TypedSharedIndexInformer[*apicorev1.ReplicationController] + +// ReplicationControllerHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ReplicationController. +type ReplicationControllerHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.ReplicationController] + +// ReplicationControllerDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ReplicationController. +type ReplicationControllerDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.ReplicationController] + +// ReplicationControllerFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ReplicationController. +type ReplicationControllerFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.ReplicationController] + +// ReplicationControllerIndexers is a specialization of [cache.TypedIndexers] for ReplicationController. +type ReplicationControllerIndexers = cache.TypedIndexers[*apicorev1.ReplicationController] + +// DeletedReplicationController is a specialization of [cache.DeletedObject] for ReplicationController. +type DeletedReplicationController = cache.DeletedObject[*apicorev1.ReplicationController] + type replicationControllerInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type replicationControllerInformer struct { // NewReplicationControllerInformer constructs a new informer for ReplicationController type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicationControllerInformer]). func NewReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewReplicationControllerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedReplicationControllerInformer constructs a new informer for ReplicationController type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicationControllerIndexers) ReplicationControllerIndexInformer { + return NewTypedReplicationControllerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredReplicationControllerInformer constructs a new informer for ReplicationController type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredReplicationControllerInformer]). func NewFilteredReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewReplicationControllerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedReplicationControllerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredReplicationControllerInformer constructs a new informer for ReplicationController type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicationControllerIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ReplicationControllerIndexInformer { + return NewTypedReplicationControllerInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewReplicationControllerInformerWithOptions constructs a new informer for ReplicationController type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicationControllerInformerWithOptions]). func NewReplicationControllerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedReplicationControllerInformerWithOptions(client, namespace, options) +} + +// NewTypedReplicationControllerInformerWithOptions constructs a new informer for ReplicationController type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicationControllerInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ReplicationControllerIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "replicationcontrollers"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.ReplicationController](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewReplicationControllerInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *replicationControllerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewReplicationControllerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedReplicationControllerInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *replicationControllerInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.ReplicationController{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *replicationControllerInformer) TypedInformer() ReplicationControllerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ReplicationController](f.factory.InformerFor(&apicorev1.ReplicationController{}, f.defaultInformer)) } func (f *replicationControllerInformer) Lister() corev1.ReplicationControllerLister { return corev1.NewReplicationControllerLister(f.Informer().GetIndexer()) } + +// ToTypedReplicationControllerInformer converts an untyped informer into a TypedReplicationControllerInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicationController. If that is not the case, calling type-safe methods of the returned +// TypedReplicationControllerInformer leads to runtime panics. A safer alternative is to pass +// around a TypedReplicationControllerInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedReplicationControllerInformer(informer ReplicationControllerInformer) TypedReplicationControllerInformer { + if informer, ok := informer.(TypedReplicationControllerInformer); ok { + return informer + } + return &replicationControllerTypedInformerAdapter{informer} +} + +type replicationControllerTypedInformerAdapter struct { + ReplicationControllerInformer +} + +func (a *replicationControllerTypedInformerAdapter) TypedInformer() ReplicationControllerIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ReplicationController](a.Informer()) +} + +// ToReplicationControllerIndexInformer converts an untyped informer into a ReplicationControllerIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicationController. If that is not the case, calling type-safe methods of the returned +// ReplicationControllerIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ReplicationControllerIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToReplicationControllerIndexInformer(informer cache.SharedIndexInformer) ReplicationControllerIndexInformer { + if informer, ok := informer.(ReplicationControllerIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.ReplicationController](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/resourcequota.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/resourcequota.go index 490a31212..5726e484c 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/resourcequota.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/resourcequota.go @@ -34,12 +34,40 @@ import ( ) // ResourceQuotaInformer provides access to a shared informer and lister for -// ResourceQuotas. +// ResourceQuotas. Prefer using the type-safe variant (see [TypedResourceQuotaInformer]). type ResourceQuotaInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ResourceQuotaLister } +// TypedResourceQuotaInformer provides access to a shared informer and lister for +// ResourceQuotas, including the type-safe TypedInformer variant. +// It is a superset of ResourceQuotaInformer. +type TypedResourceQuotaInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceQuotaIndexInformer + Lister() corev1.ResourceQuotaLister +} + +// ResourceQuotaIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceQuotaIndexInformer cache.TypedSharedIndexInformer[*apicorev1.ResourceQuota] + +// ResourceQuotaHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceQuota. +type ResourceQuotaHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.ResourceQuota] + +// ResourceQuotaDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceQuota. +type ResourceQuotaDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.ResourceQuota] + +// ResourceQuotaFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceQuota. +type ResourceQuotaFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.ResourceQuota] + +// ResourceQuotaIndexers is a specialization of [cache.TypedIndexers] for ResourceQuota. +type ResourceQuotaIndexers = cache.TypedIndexers[*apicorev1.ResourceQuota] + +// DeletedResourceQuota is a specialization of [cache.DeletedObject] for ResourceQuota. +type DeletedResourceQuota = cache.DeletedObject[*apicorev1.ResourceQuota] + type resourceQuotaInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceQuotaInformer struct { // NewResourceQuotaInformer constructs a new informer for ResourceQuota type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceQuotaInformer]). func NewResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceQuotaInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceQuotaInformer constructs a new informer for ResourceQuota type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceQuotaIndexers) ResourceQuotaIndexInformer { + return NewTypedResourceQuotaInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceQuotaInformer constructs a new informer for ResourceQuota type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceQuotaInformer]). func NewFilteredResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceQuotaInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceQuotaInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceQuotaInformer constructs a new informer for ResourceQuota type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceQuotaIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceQuotaIndexInformer { + return NewTypedResourceQuotaInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceQuotaInformerWithOptions constructs a new informer for ResourceQuota type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceQuotaInformerWithOptions]). func NewResourceQuotaInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceQuotaInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceQuotaInformerWithOptions constructs a new informer for ResourceQuota type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceQuotaInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceQuotaIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "resourcequotas"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.ResourceQuota](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceQuotaInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceQuotaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceQuotaInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceQuotaInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceQuotaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.ResourceQuota{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceQuotaInformer) TypedInformer() ResourceQuotaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ResourceQuota](f.factory.InformerFor(&apicorev1.ResourceQuota{}, f.defaultInformer)) } func (f *resourceQuotaInformer) Lister() corev1.ResourceQuotaLister { return corev1.NewResourceQuotaLister(f.Informer().GetIndexer()) } + +// ToTypedResourceQuotaInformer converts an untyped informer into a TypedResourceQuotaInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceQuota. If that is not the case, calling type-safe methods of the returned +// TypedResourceQuotaInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceQuotaInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceQuotaInformer(informer ResourceQuotaInformer) TypedResourceQuotaInformer { + if informer, ok := informer.(TypedResourceQuotaInformer); ok { + return informer + } + return &resourceQuotaTypedInformerAdapter{informer} +} + +type resourceQuotaTypedInformerAdapter struct { + ResourceQuotaInformer +} + +func (a *resourceQuotaTypedInformerAdapter) TypedInformer() ResourceQuotaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ResourceQuota](a.Informer()) +} + +// ToResourceQuotaIndexInformer converts an untyped informer into a ResourceQuotaIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceQuota. If that is not the case, calling type-safe methods of the returned +// ResourceQuotaIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceQuotaIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceQuotaIndexInformer(informer cache.SharedIndexInformer) ResourceQuotaIndexInformer { + if informer, ok := informer.(ResourceQuotaIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.ResourceQuota](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/secret.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/secret.go index 86458285d..ae75b7d22 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/secret.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/secret.go @@ -34,12 +34,40 @@ import ( ) // SecretInformer provides access to a shared informer and lister for -// Secrets. +// Secrets. Prefer using the type-safe variant (see [TypedSecretInformer]). type SecretInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.SecretLister } +// TypedSecretInformer provides access to a shared informer and lister for +// Secrets, including the type-safe TypedInformer variant. +// It is a superset of SecretInformer. +type TypedSecretInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() SecretIndexInformer + Lister() corev1.SecretLister +} + +// SecretIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type SecretIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Secret] + +// SecretHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Secret. +type SecretHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Secret] + +// SecretDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Secret. +type SecretDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Secret] + +// SecretFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Secret. +type SecretFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Secret] + +// SecretIndexers is a specialization of [cache.TypedIndexers] for Secret. +type SecretIndexers = cache.TypedIndexers[*apicorev1.Secret] + +// DeletedSecret is a specialization of [cache.DeletedObject] for Secret. +type DeletedSecret = cache.DeletedObject[*apicorev1.Secret] + type secretInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type secretInformer struct { // NewSecretInformer constructs a new informer for Secret type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedSecretInformer]). func NewSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewSecretInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedSecretInformer constructs a new informer for Secret type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers SecretIndexers) SecretIndexInformer { + return NewTypedSecretInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredSecretInformer constructs a new informer for Secret type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredSecretInformer]). func NewFilteredSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewSecretInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedSecretInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredSecretInformer constructs a new informer for Secret type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers SecretIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) SecretIndexInformer { + return NewTypedSecretInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewSecretInformerWithOptions constructs a new informer for Secret type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedSecretInformerWithOptions]). func NewSecretInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedSecretInformerWithOptions(client, namespace, options) +} + +// NewTypedSecretInformerWithOptions constructs a new informer for Secret type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedSecretInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) SecretIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "secrets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Secret](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewSecretInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *secretInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewSecretInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedSecretInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *secretInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Secret{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *secretInformer) TypedInformer() SecretIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Secret](f.factory.InformerFor(&apicorev1.Secret{}, f.defaultInformer)) } func (f *secretInformer) Lister() corev1.SecretLister { return corev1.NewSecretLister(f.Informer().GetIndexer()) } + +// ToTypedSecretInformer converts an untyped informer into a TypedSecretInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Secret. If that is not the case, calling type-safe methods of the returned +// TypedSecretInformer leads to runtime panics. A safer alternative is to pass +// around a TypedSecretInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedSecretInformer(informer SecretInformer) TypedSecretInformer { + if informer, ok := informer.(TypedSecretInformer); ok { + return informer + } + return &secretTypedInformerAdapter{informer} +} + +type secretTypedInformerAdapter struct { + SecretInformer +} + +func (a *secretTypedInformerAdapter) TypedInformer() SecretIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Secret](a.Informer()) +} + +// ToSecretIndexInformer converts an untyped informer into a SecretIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Secret. If that is not the case, calling type-safe methods of the returned +// SecretIndexInformer leads to runtime panics. A safer alternative is to pass +// around a SecretIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToSecretIndexInformer(informer cache.SharedIndexInformer) SecretIndexInformer { + if informer, ok := informer.(SecretIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Secret](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/service.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/service.go index 4ec10b322..0c804c022 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/service.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/service.go @@ -34,12 +34,40 @@ import ( ) // ServiceInformer provides access to a shared informer and lister for -// Services. +// Services. Prefer using the type-safe variant (see [TypedServiceInformer]). type ServiceInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ServiceLister } +// TypedServiceInformer provides access to a shared informer and lister for +// Services, including the type-safe TypedInformer variant. +// It is a superset of ServiceInformer. +type TypedServiceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ServiceIndexInformer + Lister() corev1.ServiceLister +} + +// ServiceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ServiceIndexInformer cache.TypedSharedIndexInformer[*apicorev1.Service] + +// ServiceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Service. +type ServiceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.Service] + +// ServiceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Service. +type ServiceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.Service] + +// ServiceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Service. +type ServiceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.Service] + +// ServiceIndexers is a specialization of [cache.TypedIndexers] for Service. +type ServiceIndexers = cache.TypedIndexers[*apicorev1.Service] + +// DeletedService is a specialization of [cache.DeletedObject] for Service. +type DeletedService = cache.DeletedObject[*apicorev1.Service] + type serviceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type serviceInformer struct { // NewServiceInformer constructs a new informer for Service type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceInformer]). func NewServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewServiceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedServiceInformer constructs a new informer for Service type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ServiceIndexers) ServiceIndexInformer { + return NewTypedServiceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredServiceInformer constructs a new informer for Service type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredServiceInformer]). func NewFilteredServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewServiceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedServiceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredServiceInformer constructs a new informer for Service type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ServiceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ServiceIndexInformer { + return NewTypedServiceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewServiceInformerWithOptions constructs a new informer for Service type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceInformerWithOptions]). func NewServiceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedServiceInformerWithOptions(client, namespace, options) +} + +// NewTypedServiceInformerWithOptions constructs a new informer for Service type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ServiceIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "services"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.Service](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewServiceInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *serviceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewServiceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedServiceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *serviceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.Service{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *serviceInformer) TypedInformer() ServiceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Service](f.factory.InformerFor(&apicorev1.Service{}, f.defaultInformer)) } func (f *serviceInformer) Lister() corev1.ServiceLister { return corev1.NewServiceLister(f.Informer().GetIndexer()) } + +// ToTypedServiceInformer converts an untyped informer into a TypedServiceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Service. If that is not the case, calling type-safe methods of the returned +// TypedServiceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedServiceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedServiceInformer(informer ServiceInformer) TypedServiceInformer { + if informer, ok := informer.(TypedServiceInformer); ok { + return informer + } + return &serviceTypedInformerAdapter{informer} +} + +type serviceTypedInformerAdapter struct { + ServiceInformer +} + +func (a *serviceTypedInformerAdapter) TypedInformer() ServiceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.Service](a.Informer()) +} + +// ToServiceIndexInformer converts an untyped informer into a ServiceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Service. If that is not the case, calling type-safe methods of the returned +// ServiceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ServiceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToServiceIndexInformer(informer cache.SharedIndexInformer) ServiceIndexInformer { + if informer, ok := informer.(ServiceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.Service](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/core/v1/serviceaccount.go b/constraint/vendor/k8s.io/client-go/informers/core/v1/serviceaccount.go index 32751b6a3..6ca3cf685 100644 --- a/constraint/vendor/k8s.io/client-go/informers/core/v1/serviceaccount.go +++ b/constraint/vendor/k8s.io/client-go/informers/core/v1/serviceaccount.go @@ -34,12 +34,40 @@ import ( ) // ServiceAccountInformer provides access to a shared informer and lister for -// ServiceAccounts. +// ServiceAccounts. Prefer using the type-safe variant (see [TypedServiceAccountInformer]). type ServiceAccountInformer interface { Informer() cache.SharedIndexInformer Lister() corev1.ServiceAccountLister } +// TypedServiceAccountInformer provides access to a shared informer and lister for +// ServiceAccounts, including the type-safe TypedInformer variant. +// It is a superset of ServiceAccountInformer. +type TypedServiceAccountInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ServiceAccountIndexInformer + Lister() corev1.ServiceAccountLister +} + +// ServiceAccountIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ServiceAccountIndexInformer cache.TypedSharedIndexInformer[*apicorev1.ServiceAccount] + +// ServiceAccountHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ServiceAccount. +type ServiceAccountHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apicorev1.ServiceAccount] + +// ServiceAccountDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ServiceAccount. +type ServiceAccountDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apicorev1.ServiceAccount] + +// ServiceAccountFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ServiceAccount. +type ServiceAccountFilteringHandler = cache.TypedFilteringResourceEventHandler[*apicorev1.ServiceAccount] + +// ServiceAccountIndexers is a specialization of [cache.TypedIndexers] for ServiceAccount. +type ServiceAccountIndexers = cache.TypedIndexers[*apicorev1.ServiceAccount] + +// DeletedServiceAccount is a specialization of [cache.DeletedObject] for ServiceAccount. +type DeletedServiceAccount = cache.DeletedObject[*apicorev1.ServiceAccount] + type serviceAccountInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type serviceAccountInformer struct { // NewServiceAccountInformer constructs a new informer for ServiceAccount type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceAccountInformer]). func NewServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewServiceAccountInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedServiceAccountInformer constructs a new informer for ServiceAccount type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ServiceAccountIndexers) ServiceAccountIndexInformer { + return NewTypedServiceAccountInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredServiceAccountInformer constructs a new informer for ServiceAccount type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredServiceAccountInformer]). func NewFilteredServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewServiceAccountInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedServiceAccountInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredServiceAccountInformer constructs a new informer for ServiceAccount type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ServiceAccountIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ServiceAccountIndexInformer { + return NewTypedServiceAccountInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewServiceAccountInformerWithOptions constructs a new informer for ServiceAccount type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceAccountInformerWithOptions]). func NewServiceAccountInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedServiceAccountInformerWithOptions(client, namespace, options) +} + +// NewTypedServiceAccountInformerWithOptions constructs a new informer for ServiceAccount type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceAccountInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ServiceAccountIndexInformer { gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "serviceaccounts"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apicorev1.ServiceAccount](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewServiceAccountInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *serviceAccountInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewServiceAccountInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedServiceAccountInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *serviceAccountInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apicorev1.ServiceAccount{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *serviceAccountInformer) TypedInformer() ServiceAccountIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ServiceAccount](f.factory.InformerFor(&apicorev1.ServiceAccount{}, f.defaultInformer)) } func (f *serviceAccountInformer) Lister() corev1.ServiceAccountLister { return corev1.NewServiceAccountLister(f.Informer().GetIndexer()) } + +// ToTypedServiceAccountInformer converts an untyped informer into a TypedServiceAccountInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceAccount. If that is not the case, calling type-safe methods of the returned +// TypedServiceAccountInformer leads to runtime panics. A safer alternative is to pass +// around a TypedServiceAccountInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedServiceAccountInformer(informer ServiceAccountInformer) TypedServiceAccountInformer { + if informer, ok := informer.(TypedServiceAccountInformer); ok { + return informer + } + return &serviceAccountTypedInformerAdapter{informer} +} + +type serviceAccountTypedInformerAdapter struct { + ServiceAccountInformer +} + +func (a *serviceAccountTypedInformerAdapter) TypedInformer() ServiceAccountIndexInformer { + return cache.NewTypedSharedIndexInformer[*apicorev1.ServiceAccount](a.Informer()) +} + +// ToServiceAccountIndexInformer converts an untyped informer into a ServiceAccountIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceAccount. If that is not the case, calling type-safe methods of the returned +// ServiceAccountIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ServiceAccountIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToServiceAccountIndexInformer(informer cache.SharedIndexInformer) ServiceAccountIndexInformer { + if informer, ok := informer.(ServiceAccountIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apicorev1.ServiceAccount](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/discovery/v1/endpointslice.go b/constraint/vendor/k8s.io/client-go/informers/discovery/v1/endpointslice.go index 999d51459..f03777086 100644 --- a/constraint/vendor/k8s.io/client-go/informers/discovery/v1/endpointslice.go +++ b/constraint/vendor/k8s.io/client-go/informers/discovery/v1/endpointslice.go @@ -34,12 +34,40 @@ import ( ) // EndpointSliceInformer provides access to a shared informer and lister for -// EndpointSlices. +// EndpointSlices. Prefer using the type-safe variant (see [TypedEndpointSliceInformer]). type EndpointSliceInformer interface { Informer() cache.SharedIndexInformer Lister() discoveryv1.EndpointSliceLister } +// TypedEndpointSliceInformer provides access to a shared informer and lister for +// EndpointSlices, including the type-safe TypedInformer variant. +// It is a superset of EndpointSliceInformer. +type TypedEndpointSliceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EndpointSliceIndexInformer + Lister() discoveryv1.EndpointSliceLister +} + +// EndpointSliceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EndpointSliceIndexInformer cache.TypedSharedIndexInformer[*apidiscoveryv1.EndpointSlice] + +// EndpointSliceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for EndpointSlice. +type EndpointSliceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apidiscoveryv1.EndpointSlice] + +// EndpointSliceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for EndpointSlice. +type EndpointSliceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apidiscoveryv1.EndpointSlice] + +// EndpointSliceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for EndpointSlice. +type EndpointSliceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apidiscoveryv1.EndpointSlice] + +// EndpointSliceIndexers is a specialization of [cache.TypedIndexers] for EndpointSlice. +type EndpointSliceIndexers = cache.TypedIndexers[*apidiscoveryv1.EndpointSlice] + +// DeletedEndpointSlice is a specialization of [cache.DeletedObject] for EndpointSlice. +type DeletedEndpointSlice = cache.DeletedObject[*apidiscoveryv1.EndpointSlice] + type endpointSliceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type endpointSliceInformer struct { // NewEndpointSliceInformer constructs a new informer for EndpointSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointSliceInformer]). func NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEndpointSliceInformer constructs a new informer for EndpointSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointSliceIndexers) EndpointSliceIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEndpointSliceInformer]). func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointSliceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EndpointSliceIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEndpointSliceInformerWithOptions constructs a new informer for EndpointSlice type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointSliceInformerWithOptions]). func NewEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, options) +} + +// NewTypedEndpointSliceInformerWithOptions constructs a new informer for EndpointSlice type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EndpointSliceIndexInformer { gvr := schema.GroupVersionResource{Group: "discovery.k8s.io", Version: "v1", Resource: "endpointslices"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1.EndpointSlice](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEndpointSliceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEndpointSliceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apidiscoveryv1.EndpointSlice{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *endpointSliceInformer) TypedInformer() EndpointSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1.EndpointSlice](f.factory.InformerFor(&apidiscoveryv1.EndpointSlice{}, f.defaultInformer)) } func (f *endpointSliceInformer) Lister() discoveryv1.EndpointSliceLister { return discoveryv1.NewEndpointSliceLister(f.Informer().GetIndexer()) } + +// ToTypedEndpointSliceInformer converts an untyped informer into a TypedEndpointSliceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EndpointSlice. If that is not the case, calling type-safe methods of the returned +// TypedEndpointSliceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEndpointSliceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEndpointSliceInformer(informer EndpointSliceInformer) TypedEndpointSliceInformer { + if informer, ok := informer.(TypedEndpointSliceInformer); ok { + return informer + } + return &endpointSliceTypedInformerAdapter{informer} +} + +type endpointSliceTypedInformerAdapter struct { + EndpointSliceInformer +} + +func (a *endpointSliceTypedInformerAdapter) TypedInformer() EndpointSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1.EndpointSlice](a.Informer()) +} + +// ToEndpointSliceIndexInformer converts an untyped informer into a EndpointSliceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EndpointSlice. If that is not the case, calling type-safe methods of the returned +// EndpointSliceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EndpointSliceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEndpointSliceIndexInformer(informer cache.SharedIndexInformer) EndpointSliceIndexInformer { + if informer, ok := informer.(EndpointSliceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1.EndpointSlice](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/discovery/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/discovery/v1/interface.go index d90c63c0a..889b917e0 100644 --- a/constraint/vendor/k8s.io/client-go/informers/discovery/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/discovery/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // EndpointSlices returns a EndpointSliceInformer. - EndpointSlices() EndpointSliceInformer + EndpointSlices() TypedEndpointSliceInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// EndpointSlices returns a EndpointSliceInformer. -func (v *version) EndpointSlices() EndpointSliceInformer { +// EndpointSlices returns a TypedEndpointSliceInformer. +func (v *version) EndpointSlices() TypedEndpointSliceInformer { return &endpointSliceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go b/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go index 918e30485..5fa706878 100644 --- a/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go +++ b/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go @@ -34,12 +34,40 @@ import ( ) // EndpointSliceInformer provides access to a shared informer and lister for -// EndpointSlices. +// EndpointSlices. Prefer using the type-safe variant (see [TypedEndpointSliceInformer]). type EndpointSliceInformer interface { Informer() cache.SharedIndexInformer Lister() discoveryv1beta1.EndpointSliceLister } +// TypedEndpointSliceInformer provides access to a shared informer and lister for +// EndpointSlices, including the type-safe TypedInformer variant. +// It is a superset of EndpointSliceInformer. +type TypedEndpointSliceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EndpointSliceIndexInformer + Lister() discoveryv1beta1.EndpointSliceLister +} + +// EndpointSliceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EndpointSliceIndexInformer cache.TypedSharedIndexInformer[*apidiscoveryv1beta1.EndpointSlice] + +// EndpointSliceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for EndpointSlice. +type EndpointSliceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apidiscoveryv1beta1.EndpointSlice] + +// EndpointSliceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for EndpointSlice. +type EndpointSliceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apidiscoveryv1beta1.EndpointSlice] + +// EndpointSliceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for EndpointSlice. +type EndpointSliceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apidiscoveryv1beta1.EndpointSlice] + +// EndpointSliceIndexers is a specialization of [cache.TypedIndexers] for EndpointSlice. +type EndpointSliceIndexers = cache.TypedIndexers[*apidiscoveryv1beta1.EndpointSlice] + +// DeletedEndpointSlice is a specialization of [cache.DeletedObject] for EndpointSlice. +type DeletedEndpointSlice = cache.DeletedObject[*apidiscoveryv1beta1.EndpointSlice] + type endpointSliceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type endpointSliceInformer struct { // NewEndpointSliceInformer constructs a new informer for EndpointSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointSliceInformer]). func NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEndpointSliceInformer constructs a new informer for EndpointSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointSliceIndexers) EndpointSliceIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEndpointSliceInformer]). func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EndpointSliceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EndpointSliceIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEndpointSliceInformerWithOptions constructs a new informer for EndpointSlice type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEndpointSliceInformerWithOptions]). func NewEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEndpointSliceInformerWithOptions(client, namespace, options) +} + +// NewTypedEndpointSliceInformerWithOptions constructs a new informer for EndpointSlice type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EndpointSliceIndexInformer { gvr := schema.GroupVersionResource{Group: "discovery.k8s.io", Version: "v1beta1", Resource: "endpointslices"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1beta1.EndpointSlice](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEndpointSliceInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEndpointSliceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEndpointSliceInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apidiscoveryv1beta1.EndpointSlice{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *endpointSliceInformer) TypedInformer() EndpointSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1beta1.EndpointSlice](f.factory.InformerFor(&apidiscoveryv1beta1.EndpointSlice{}, f.defaultInformer)) } func (f *endpointSliceInformer) Lister() discoveryv1beta1.EndpointSliceLister { return discoveryv1beta1.NewEndpointSliceLister(f.Informer().GetIndexer()) } + +// ToTypedEndpointSliceInformer converts an untyped informer into a TypedEndpointSliceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EndpointSlice. If that is not the case, calling type-safe methods of the returned +// TypedEndpointSliceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEndpointSliceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEndpointSliceInformer(informer EndpointSliceInformer) TypedEndpointSliceInformer { + if informer, ok := informer.(TypedEndpointSliceInformer); ok { + return informer + } + return &endpointSliceTypedInformerAdapter{informer} +} + +type endpointSliceTypedInformerAdapter struct { + EndpointSliceInformer +} + +func (a *endpointSliceTypedInformerAdapter) TypedInformer() EndpointSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1beta1.EndpointSlice](a.Informer()) +} + +// ToEndpointSliceIndexInformer converts an untyped informer into a EndpointSliceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EndpointSlice. If that is not the case, calling type-safe methods of the returned +// EndpointSliceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EndpointSliceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEndpointSliceIndexInformer(informer cache.SharedIndexInformer) EndpointSliceIndexInformer { + if informer, ok := informer.(EndpointSliceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apidiscoveryv1beta1.EndpointSlice](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/interface.go index 4661646e0..f0866a4ff 100644 --- a/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/discovery/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // EndpointSlices returns a EndpointSliceInformer. - EndpointSlices() EndpointSliceInformer + EndpointSlices() TypedEndpointSliceInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// EndpointSlices returns a EndpointSliceInformer. -func (v *version) EndpointSlices() EndpointSliceInformer { +// EndpointSlices returns a TypedEndpointSliceInformer. +func (v *version) EndpointSlices() TypedEndpointSliceInformer { return &endpointSliceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/events/v1/event.go b/constraint/vendor/k8s.io/client-go/informers/events/v1/event.go index 23aaa6847..d0bd73b50 100644 --- a/constraint/vendor/k8s.io/client-go/informers/events/v1/event.go +++ b/constraint/vendor/k8s.io/client-go/informers/events/v1/event.go @@ -34,12 +34,40 @@ import ( ) // EventInformer provides access to a shared informer and lister for -// Events. +// Events. Prefer using the type-safe variant (see [TypedEventInformer]). type EventInformer interface { Informer() cache.SharedIndexInformer Lister() eventsv1.EventLister } +// TypedEventInformer provides access to a shared informer and lister for +// Events, including the type-safe TypedInformer variant. +// It is a superset of EventInformer. +type TypedEventInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EventIndexInformer + Lister() eventsv1.EventLister +} + +// EventIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EventIndexInformer cache.TypedSharedIndexInformer[*apieventsv1.Event] + +// EventHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Event. +type EventHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apieventsv1.Event] + +// EventDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Event. +type EventDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apieventsv1.Event] + +// EventFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Event. +type EventFilteringHandler = cache.TypedFilteringResourceEventHandler[*apieventsv1.Event] + +// EventIndexers is a specialization of [cache.TypedIndexers] for Event. +type EventIndexers = cache.TypedIndexers[*apieventsv1.Event] + +// DeletedEvent is a specialization of [cache.DeletedObject] for Event. +type DeletedEvent = cache.DeletedObject[*apieventsv1.Event] + type eventInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type eventInformer struct { // NewEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformer]). func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEventInformer]). func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEventInformerWithOptions constructs a new informer for Event type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformerWithOptions]). func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, options) +} + +// NewTypedEventInformerWithOptions constructs a new informer for Event type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EventIndexInformer { gvr := schema.GroupVersionResource{Group: "events.k8s.io", Version: "v1", Resource: "events"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apieventsv1.Event](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *eventInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apieventsv1.Event{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *eventInformer) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apieventsv1.Event](f.factory.InformerFor(&apieventsv1.Event{}, f.defaultInformer)) } func (f *eventInformer) Lister() eventsv1.EventLister { return eventsv1.NewEventLister(f.Informer().GetIndexer()) } + +// ToTypedEventInformer converts an untyped informer into a TypedEventInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// TypedEventInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEventInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEventInformer(informer EventInformer) TypedEventInformer { + if informer, ok := informer.(TypedEventInformer); ok { + return informer + } + return &eventTypedInformerAdapter{informer} +} + +type eventTypedInformerAdapter struct { + EventInformer +} + +func (a *eventTypedInformerAdapter) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apieventsv1.Event](a.Informer()) +} + +// ToEventIndexInformer converts an untyped informer into a EventIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// EventIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EventIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEventIndexInformer(informer cache.SharedIndexInformer) EventIndexInformer { + if informer, ok := informer.(EventIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apieventsv1.Event](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/events/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/events/v1/interface.go index cd06e2335..8b2571298 100644 --- a/constraint/vendor/k8s.io/client-go/informers/events/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/events/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // Events returns a EventInformer. - Events() EventInformer + Events() TypedEventInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// Events returns a EventInformer. -func (v *version) Events() EventInformer { +// Events returns a TypedEventInformer. +func (v *version) Events() TypedEventInformer { return &eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/event.go b/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/event.go index ea0117eac..fc3d7203d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/event.go +++ b/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/event.go @@ -34,12 +34,40 @@ import ( ) // EventInformer provides access to a shared informer and lister for -// Events. +// Events. Prefer using the type-safe variant (see [TypedEventInformer]). type EventInformer interface { Informer() cache.SharedIndexInformer Lister() eventsv1beta1.EventLister } +// TypedEventInformer provides access to a shared informer and lister for +// Events, including the type-safe TypedInformer variant. +// It is a superset of EventInformer. +type TypedEventInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EventIndexInformer + Lister() eventsv1beta1.EventLister +} + +// EventIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EventIndexInformer cache.TypedSharedIndexInformer[*apieventsv1beta1.Event] + +// EventHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Event. +type EventHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apieventsv1beta1.Event] + +// EventDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Event. +type EventDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apieventsv1beta1.Event] + +// EventFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Event. +type EventFilteringHandler = cache.TypedFilteringResourceEventHandler[*apieventsv1beta1.Event] + +// EventIndexers is a specialization of [cache.TypedIndexers] for Event. +type EventIndexers = cache.TypedIndexers[*apieventsv1beta1.Event] + +// DeletedEvent is a specialization of [cache.DeletedObject] for Event. +type DeletedEvent = cache.DeletedObject[*apieventsv1beta1.Event] + type eventInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type eventInformer struct { // NewEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformer]). func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredEventInformer constructs a new informer for Event type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEventInformer]). func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEventInformer constructs a new informer for Event type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EventIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EventIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewEventInformerWithOptions constructs a new informer for Event type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEventInformerWithOptions]). func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEventInformerWithOptions(client, namespace, options) +} + +// NewTypedEventInformerWithOptions constructs a new informer for Event type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEventInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EventIndexInformer { gvr := schema.GroupVersionResource{Group: "events.k8s.io", Version: "v1beta1", Resource: "events"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apieventsv1beta1.Event](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewEventInformerWithOptions(client kubernetes.Interface, namespace string, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedEventInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *eventInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apieventsv1beta1.Event{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *eventInformer) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apieventsv1beta1.Event](f.factory.InformerFor(&apieventsv1beta1.Event{}, f.defaultInformer)) } func (f *eventInformer) Lister() eventsv1beta1.EventLister { return eventsv1beta1.NewEventLister(f.Informer().GetIndexer()) } + +// ToTypedEventInformer converts an untyped informer into a TypedEventInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// TypedEventInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEventInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEventInformer(informer EventInformer) TypedEventInformer { + if informer, ok := informer.(TypedEventInformer); ok { + return informer + } + return &eventTypedInformerAdapter{informer} +} + +type eventTypedInformerAdapter struct { + EventInformer +} + +func (a *eventTypedInformerAdapter) TypedInformer() EventIndexInformer { + return cache.NewTypedSharedIndexInformer[*apieventsv1beta1.Event](a.Informer()) +} + +// ToEventIndexInformer converts an untyped informer into a EventIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Event. If that is not the case, calling type-safe methods of the returned +// EventIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EventIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEventIndexInformer(informer cache.SharedIndexInformer) EventIndexInformer { + if informer, ok := informer.(EventIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apieventsv1beta1.Event](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/interface.go index c71888c9a..9b69ebe28 100644 --- a/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/events/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // Events returns a EventInformer. - Events() EventInformer + Events() TypedEventInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// Events returns a EventInformer. -func (v *version) Events() EventInformer { +// Events returns a TypedEventInformer. +func (v *version) Events() TypedEventInformer { return &eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go index ed8b02303..1c3e4f7ac 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go @@ -34,12 +34,40 @@ import ( ) // DaemonSetInformer provides access to a shared informer and lister for -// DaemonSets. +// DaemonSets. Prefer using the type-safe variant (see [TypedDaemonSetInformer]). type DaemonSetInformer interface { Informer() cache.SharedIndexInformer Lister() extensionsv1beta1.DaemonSetLister } +// TypedDaemonSetInformer provides access to a shared informer and lister for +// DaemonSets, including the type-safe TypedInformer variant. +// It is a superset of DaemonSetInformer. +type TypedDaemonSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DaemonSetIndexInformer + Lister() extensionsv1beta1.DaemonSetLister +} + +// DaemonSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DaemonSetIndexInformer cache.TypedSharedIndexInformer[*apiextensionsv1beta1.DaemonSet] + +// DaemonSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DaemonSet. +type DaemonSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiextensionsv1beta1.DaemonSet] + +// DaemonSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DaemonSet. +type DaemonSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiextensionsv1beta1.DaemonSet] + +// DaemonSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DaemonSet. +type DaemonSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiextensionsv1beta1.DaemonSet] + +// DaemonSetIndexers is a specialization of [cache.TypedIndexers] for DaemonSet. +type DaemonSetIndexers = cache.TypedIndexers[*apiextensionsv1beta1.DaemonSet] + +// DeletedDaemonSet is a specialization of [cache.DeletedObject] for DaemonSet. +type DeletedDaemonSet = cache.DeletedObject[*apiextensionsv1beta1.DaemonSet] + type daemonSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type daemonSetInformer struct { // NewDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformer]). func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDaemonSetInformer]). func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDaemonSetInformer constructs a new informer for DaemonSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DaemonSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DaemonSetIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDaemonSetInformerWithOptions]). func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDaemonSetInformerWithOptions(client, namespace, options) +} + +// NewTypedDaemonSetInformerWithOptions constructs a new informer for DaemonSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDaemonSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DaemonSetIndexInformer { gvr := schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "daemonsets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.DaemonSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDaemonSetInformerWithOptions(client kubernetes.Interface, namespace stri Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDaemonSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *daemonSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiextensionsv1beta1.DaemonSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *daemonSetInformer) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.DaemonSet](f.factory.InformerFor(&apiextensionsv1beta1.DaemonSet{}, f.defaultInformer)) } func (f *daemonSetInformer) Lister() extensionsv1beta1.DaemonSetLister { return extensionsv1beta1.NewDaemonSetLister(f.Informer().GetIndexer()) } + +// ToTypedDaemonSetInformer converts an untyped informer into a TypedDaemonSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// TypedDaemonSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDaemonSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDaemonSetInformer(informer DaemonSetInformer) TypedDaemonSetInformer { + if informer, ok := informer.(TypedDaemonSetInformer); ok { + return informer + } + return &daemonSetTypedInformerAdapter{informer} +} + +type daemonSetTypedInformerAdapter struct { + DaemonSetInformer +} + +func (a *daemonSetTypedInformerAdapter) TypedInformer() DaemonSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.DaemonSet](a.Informer()) +} + +// ToDaemonSetIndexInformer converts an untyped informer into a DaemonSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DaemonSet. If that is not the case, calling type-safe methods of the returned +// DaemonSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DaemonSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDaemonSetIndexInformer(informer cache.SharedIndexInformer) DaemonSetIndexInformer { + if informer, ok := informer.(DaemonSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.DaemonSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/deployment.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/deployment.go index ee328bb51..331298be9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/deployment.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/deployment.go @@ -34,12 +34,40 @@ import ( ) // DeploymentInformer provides access to a shared informer and lister for -// Deployments. +// Deployments. Prefer using the type-safe variant (see [TypedDeploymentInformer]). type DeploymentInformer interface { Informer() cache.SharedIndexInformer Lister() extensionsv1beta1.DeploymentLister } +// TypedDeploymentInformer provides access to a shared informer and lister for +// Deployments, including the type-safe TypedInformer variant. +// It is a superset of DeploymentInformer. +type TypedDeploymentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeploymentIndexInformer + Lister() extensionsv1beta1.DeploymentLister +} + +// DeploymentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeploymentIndexInformer cache.TypedSharedIndexInformer[*apiextensionsv1beta1.Deployment] + +// DeploymentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Deployment. +type DeploymentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiextensionsv1beta1.Deployment] + +// DeploymentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Deployment. +type DeploymentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiextensionsv1beta1.Deployment] + +// DeploymentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Deployment. +type DeploymentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiextensionsv1beta1.Deployment] + +// DeploymentIndexers is a specialization of [cache.TypedIndexers] for Deployment. +type DeploymentIndexers = cache.TypedIndexers[*apiextensionsv1beta1.Deployment] + +// DeletedDeployment is a specialization of [cache.DeletedObject] for Deployment. +type DeletedDeployment = cache.DeletedObject[*apiextensionsv1beta1.Deployment] + type deploymentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type deploymentInformer struct { // NewDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformer]). func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeploymentInformer constructs a new informer for Deployment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeploymentInformer]). func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeploymentInformer constructs a new informer for Deployment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers DeploymentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeploymentIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeploymentInformerWithOptions]). func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeploymentInformerWithOptions(client, namespace, options) +} + +// NewTypedDeploymentInformerWithOptions constructs a new informer for Deployment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeploymentInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) DeploymentIndexInformer { gvr := schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "deployments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Deployment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewDeploymentInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeploymentInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deploymentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiextensionsv1beta1.Deployment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deploymentInformer) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Deployment](f.factory.InformerFor(&apiextensionsv1beta1.Deployment{}, f.defaultInformer)) } func (f *deploymentInformer) Lister() extensionsv1beta1.DeploymentLister { return extensionsv1beta1.NewDeploymentLister(f.Informer().GetIndexer()) } + +// ToTypedDeploymentInformer converts an untyped informer into a TypedDeploymentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// TypedDeploymentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeploymentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeploymentInformer(informer DeploymentInformer) TypedDeploymentInformer { + if informer, ok := informer.(TypedDeploymentInformer); ok { + return informer + } + return &deploymentTypedInformerAdapter{informer} +} + +type deploymentTypedInformerAdapter struct { + DeploymentInformer +} + +func (a *deploymentTypedInformerAdapter) TypedInformer() DeploymentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Deployment](a.Informer()) +} + +// ToDeploymentIndexInformer converts an untyped informer into a DeploymentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Deployment. If that is not the case, calling type-safe methods of the returned +// DeploymentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeploymentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeploymentIndexInformer(informer cache.SharedIndexInformer) DeploymentIndexInformer { + if informer, ok := informer.(DeploymentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Deployment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/ingress.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/ingress.go index 852238a48..31fa5723f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/ingress.go @@ -34,12 +34,40 @@ import ( ) // IngressInformer provides access to a shared informer and lister for -// Ingresses. +// Ingresses. Prefer using the type-safe variant (see [TypedIngressInformer]). type IngressInformer interface { Informer() cache.SharedIndexInformer Lister() extensionsv1beta1.IngressLister } +// TypedIngressInformer provides access to a shared informer and lister for +// Ingresses, including the type-safe TypedInformer variant. +// It is a superset of IngressInformer. +type TypedIngressInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IngressIndexInformer + Lister() extensionsv1beta1.IngressLister +} + +// IngressIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IngressIndexInformer cache.TypedSharedIndexInformer[*apiextensionsv1beta1.Ingress] + +// IngressHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Ingress. +type IngressHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiextensionsv1beta1.Ingress] + +// IngressDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Ingress. +type IngressDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiextensionsv1beta1.Ingress] + +// IngressFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Ingress. +type IngressFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiextensionsv1beta1.Ingress] + +// IngressIndexers is a specialization of [cache.TypedIndexers] for Ingress. +type IngressIndexers = cache.TypedIndexers[*apiextensionsv1beta1.Ingress] + +// DeletedIngress is a specialization of [cache.DeletedObject] for Ingress. +type DeletedIngress = cache.DeletedObject[*apiextensionsv1beta1.Ingress] + type ingressInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type ingressInformer struct { // NewIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformer]). func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIngressInformer]). func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIngressInformerWithOptions constructs a new informer for Ingress type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformerWithOptions]). func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, options) +} + +// NewTypedIngressInformerWithOptions constructs a new informer for Ingress type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) IngressIndexInformer { gvr := schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "ingresss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Ingress](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *ingressInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiextensionsv1beta1.Ingress{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *ingressInformer) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Ingress](f.factory.InformerFor(&apiextensionsv1beta1.Ingress{}, f.defaultInformer)) } func (f *ingressInformer) Lister() extensionsv1beta1.IngressLister { return extensionsv1beta1.NewIngressLister(f.Informer().GetIndexer()) } + +// ToTypedIngressInformer converts an untyped informer into a TypedIngressInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// TypedIngressInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIngressInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIngressInformer(informer IngressInformer) TypedIngressInformer { + if informer, ok := informer.(TypedIngressInformer); ok { + return informer + } + return &ingressTypedInformerAdapter{informer} +} + +type ingressTypedInformerAdapter struct { + IngressInformer +} + +func (a *ingressTypedInformerAdapter) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Ingress](a.Informer()) +} + +// ToIngressIndexInformer converts an untyped informer into a IngressIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// IngressIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IngressIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIngressIndexInformer(informer cache.SharedIndexInformer) IngressIndexInformer { + if informer, ok := informer.(IngressIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.Ingress](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/interface.go index 600741e3a..7c5636172 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/interface.go @@ -25,15 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // DaemonSets returns a DaemonSetInformer. - DaemonSets() DaemonSetInformer + DaemonSets() TypedDaemonSetInformer // Deployments returns a DeploymentInformer. - Deployments() DeploymentInformer + Deployments() TypedDeploymentInformer // Ingresses returns a IngressInformer. - Ingresses() IngressInformer + Ingresses() TypedIngressInformer // NetworkPolicies returns a NetworkPolicyInformer. - NetworkPolicies() NetworkPolicyInformer + NetworkPolicies() TypedNetworkPolicyInformer // ReplicaSets returns a ReplicaSetInformer. - ReplicaSets() ReplicaSetInformer + ReplicaSets() TypedReplicaSetInformer } type version struct { @@ -47,27 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// DaemonSets returns a DaemonSetInformer. -func (v *version) DaemonSets() DaemonSetInformer { +// DaemonSets returns a TypedDaemonSetInformer. +func (v *version) DaemonSets() TypedDaemonSetInformer { return &daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Deployments returns a DeploymentInformer. -func (v *version) Deployments() DeploymentInformer { +// Deployments returns a TypedDeploymentInformer. +func (v *version) Deployments() TypedDeploymentInformer { return &deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Ingresses returns a IngressInformer. -func (v *version) Ingresses() IngressInformer { +// Ingresses returns a TypedIngressInformer. +func (v *version) Ingresses() TypedIngressInformer { return &ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// NetworkPolicies returns a NetworkPolicyInformer. -func (v *version) NetworkPolicies() NetworkPolicyInformer { +// NetworkPolicies returns a TypedNetworkPolicyInformer. +func (v *version) NetworkPolicies() TypedNetworkPolicyInformer { return &networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ReplicaSets returns a ReplicaSetInformer. -func (v *version) ReplicaSets() ReplicaSetInformer { +// ReplicaSets returns a TypedReplicaSetInformer. +func (v *version) ReplicaSets() TypedReplicaSetInformer { return &replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go index fda46c1d9..2bec16ad2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go @@ -34,12 +34,40 @@ import ( ) // NetworkPolicyInformer provides access to a shared informer and lister for -// NetworkPolicies. +// NetworkPolicies. Prefer using the type-safe variant (see [TypedNetworkPolicyInformer]). type NetworkPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() extensionsv1beta1.NetworkPolicyLister } +// TypedNetworkPolicyInformer provides access to a shared informer and lister for +// NetworkPolicies, including the type-safe TypedInformer variant. +// It is a superset of NetworkPolicyInformer. +type TypedNetworkPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() NetworkPolicyIndexInformer + Lister() extensionsv1beta1.NetworkPolicyLister +} + +// NetworkPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type NetworkPolicyIndexInformer cache.TypedSharedIndexInformer[*apiextensionsv1beta1.NetworkPolicy] + +// NetworkPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for NetworkPolicy. +type NetworkPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiextensionsv1beta1.NetworkPolicy] + +// NetworkPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for NetworkPolicy. +type NetworkPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiextensionsv1beta1.NetworkPolicy] + +// NetworkPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for NetworkPolicy. +type NetworkPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiextensionsv1beta1.NetworkPolicy] + +// NetworkPolicyIndexers is a specialization of [cache.TypedIndexers] for NetworkPolicy. +type NetworkPolicyIndexers = cache.TypedIndexers[*apiextensionsv1beta1.NetworkPolicy] + +// DeletedNetworkPolicy is a specialization of [cache.DeletedObject] for NetworkPolicy. +type DeletedNetworkPolicy = cache.DeletedObject[*apiextensionsv1beta1.NetworkPolicy] + type networkPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type networkPolicyInformer struct { // NewNetworkPolicyInformer constructs a new informer for NetworkPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNetworkPolicyInformer]). func NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedNetworkPolicyInformer constructs a new informer for NetworkPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers NetworkPolicyIndexers) NetworkPolicyIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredNetworkPolicyInformer]). func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers NetworkPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) NetworkPolicyIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewNetworkPolicyInformerWithOptions constructs a new informer for NetworkPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNetworkPolicyInformerWithOptions]). func NewNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, options) +} + +// NewTypedNetworkPolicyInformerWithOptions constructs a new informer for NetworkPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) NetworkPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "networkpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.NetworkPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewNetworkPolicyInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedNetworkPolicyInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiextensionsv1beta1.NetworkPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *networkPolicyInformer) TypedInformer() NetworkPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.NetworkPolicy](f.factory.InformerFor(&apiextensionsv1beta1.NetworkPolicy{}, f.defaultInformer)) } func (f *networkPolicyInformer) Lister() extensionsv1beta1.NetworkPolicyLister { return extensionsv1beta1.NewNetworkPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedNetworkPolicyInformer converts an untyped informer into a TypedNetworkPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *NetworkPolicy. If that is not the case, calling type-safe methods of the returned +// TypedNetworkPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedNetworkPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedNetworkPolicyInformer(informer NetworkPolicyInformer) TypedNetworkPolicyInformer { + if informer, ok := informer.(TypedNetworkPolicyInformer); ok { + return informer + } + return &networkPolicyTypedInformerAdapter{informer} +} + +type networkPolicyTypedInformerAdapter struct { + NetworkPolicyInformer +} + +func (a *networkPolicyTypedInformerAdapter) TypedInformer() NetworkPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.NetworkPolicy](a.Informer()) +} + +// ToNetworkPolicyIndexInformer converts an untyped informer into a NetworkPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *NetworkPolicy. If that is not the case, calling type-safe methods of the returned +// NetworkPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a NetworkPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToNetworkPolicyIndexInformer(informer cache.SharedIndexInformer) NetworkPolicyIndexInformer { + if informer, ok := informer.(NetworkPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.NetworkPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go index eb0685147..cc8ba5c76 100644 --- a/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go +++ b/constraint/vendor/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go @@ -34,12 +34,40 @@ import ( ) // ReplicaSetInformer provides access to a shared informer and lister for -// ReplicaSets. +// ReplicaSets. Prefer using the type-safe variant (see [TypedReplicaSetInformer]). type ReplicaSetInformer interface { Informer() cache.SharedIndexInformer Lister() extensionsv1beta1.ReplicaSetLister } +// TypedReplicaSetInformer provides access to a shared informer and lister for +// ReplicaSets, including the type-safe TypedInformer variant. +// It is a superset of ReplicaSetInformer. +type TypedReplicaSetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ReplicaSetIndexInformer + Lister() extensionsv1beta1.ReplicaSetLister +} + +// ReplicaSetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ReplicaSetIndexInformer cache.TypedSharedIndexInformer[*apiextensionsv1beta1.ReplicaSet] + +// ReplicaSetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ReplicaSet. +type ReplicaSetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiextensionsv1beta1.ReplicaSet] + +// ReplicaSetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ReplicaSet. +type ReplicaSetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiextensionsv1beta1.ReplicaSet] + +// ReplicaSetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ReplicaSet. +type ReplicaSetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiextensionsv1beta1.ReplicaSet] + +// ReplicaSetIndexers is a specialization of [cache.TypedIndexers] for ReplicaSet. +type ReplicaSetIndexers = cache.TypedIndexers[*apiextensionsv1beta1.ReplicaSet] + +// DeletedReplicaSet is a specialization of [cache.DeletedObject] for ReplicaSet. +type DeletedReplicaSet = cache.DeletedObject[*apiextensionsv1beta1.ReplicaSet] + type replicaSetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type replicaSetInformer struct { // NewReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformer]). func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredReplicaSetInformer]). func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredReplicaSetInformer constructs a new informer for ReplicaSet type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ReplicaSetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ReplicaSetIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedReplicaSetInformerWithOptions]). func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedReplicaSetInformerWithOptions(client, namespace, options) +} + +// NewTypedReplicaSetInformerWithOptions constructs a new informer for ReplicaSet type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedReplicaSetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ReplicaSetIndexInformer { gvr := schema.GroupVersionResource{Group: "extensions", Version: "v1beta1", Resource: "replicasets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.ReplicaSet](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewReplicaSetInformerWithOptions(client kubernetes.Interface, namespace str Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedReplicaSetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *replicaSetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiextensionsv1beta1.ReplicaSet{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *replicaSetInformer) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.ReplicaSet](f.factory.InformerFor(&apiextensionsv1beta1.ReplicaSet{}, f.defaultInformer)) } func (f *replicaSetInformer) Lister() extensionsv1beta1.ReplicaSetLister { return extensionsv1beta1.NewReplicaSetLister(f.Informer().GetIndexer()) } + +// ToTypedReplicaSetInformer converts an untyped informer into a TypedReplicaSetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// TypedReplicaSetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedReplicaSetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedReplicaSetInformer(informer ReplicaSetInformer) TypedReplicaSetInformer { + if informer, ok := informer.(TypedReplicaSetInformer); ok { + return informer + } + return &replicaSetTypedInformerAdapter{informer} +} + +type replicaSetTypedInformerAdapter struct { + ReplicaSetInformer +} + +func (a *replicaSetTypedInformerAdapter) TypedInformer() ReplicaSetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.ReplicaSet](a.Informer()) +} + +// ToReplicaSetIndexInformer converts an untyped informer into a ReplicaSetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ReplicaSet. If that is not the case, calling type-safe methods of the returned +// ReplicaSetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ReplicaSetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToReplicaSetIndexInformer(informer cache.SharedIndexInformer) ReplicaSetIndexInformer { + if informer, ok := informer.(ReplicaSetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiextensionsv1beta1.ReplicaSet](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/factory.go b/constraint/vendor/k8s.io/client-go/informers/factory.go index 19901079f..4886f8465 100644 --- a/constraint/vendor/k8s.io/client-go/informers/factory.go +++ b/constraint/vendor/k8s.io/client-go/informers/factory.go @@ -41,6 +41,7 @@ import ( extensions "k8s.io/client-go/informers/extensions" flowcontrol "k8s.io/client-go/informers/flowcontrol" internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + lifecycle "k8s.io/client-go/informers/lifecycle" networking "k8s.io/client-go/informers/networking" node "k8s.io/client-go/informers/node" policy "k8s.io/client-go/informers/policy" @@ -272,7 +273,7 @@ func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internal // ctx, cancel := context.WithCancel(context.Background()) // defer cancel() // factory := NewSharedInformerFactory(client, resyncPeriod) -// defer factory.WaitForStop() // Returns immediately if nothing was started. +// defer factory.Shutdown() // Returns immediately if nothing was started. // genericInformer := factory.ForResource(resource) // typedInformer := factory.SomeAPIGroup().V1().SomeType() // handle, err := typeInformer.Informer().AddEventHandler(...) @@ -330,7 +331,7 @@ type SharedInformerFactory interface { // WaitForCacheSync blocks until all started informers' caches were synced // or the stop channel gets closed. // - // Contextual logging: WaitForCacheSync should be used instead of WaitForCacheSync in code which supports contextual logging. It also returns a more useful result. + // Contextual logging: WaitForCacheSyncWithContext should be used instead of WaitForCacheSync in code which supports contextual logging. It also returns a more useful result. WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool // WaitForCacheSyncWithContext blocks until all started informers' caches were synced @@ -356,6 +357,7 @@ type SharedInformerFactory interface { Events() events.Interface Extensions() extensions.Interface Flowcontrol() flowcontrol.Interface + Lifecycle() lifecycle.Interface Networking() networking.Interface Node() node.Interface Policy() policy.Interface @@ -414,6 +416,10 @@ func (f *sharedInformerFactory) Flowcontrol() flowcontrol.Interface { return flowcontrol.New(f, f.namespace, f.tweakListOptions) } +func (f *sharedInformerFactory) Lifecycle() lifecycle.Interface { + return lifecycle.New(f, f.namespace, f.tweakListOptions) +} + func (f *sharedInformerFactory) Networking() networking.Interface { return networking.New(f, f.namespace, f.tweakListOptions) } diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/flowschema.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/flowschema.go index 624c2f5d6..429ac3a9a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/flowschema.go @@ -34,12 +34,40 @@ import ( ) // FlowSchemaInformer provides access to a shared informer and lister for -// FlowSchemas. +// FlowSchemas. Prefer using the type-safe variant (see [TypedFlowSchemaInformer]). type FlowSchemaInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1.FlowSchemaLister } +// TypedFlowSchemaInformer provides access to a shared informer and lister for +// FlowSchemas, including the type-safe TypedInformer variant. +// It is a superset of FlowSchemaInformer. +type TypedFlowSchemaInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() FlowSchemaIndexInformer + Lister() flowcontrolv1.FlowSchemaLister +} + +// FlowSchemaIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type FlowSchemaIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1.FlowSchema] + +// FlowSchemaHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for FlowSchema. +type FlowSchemaHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1.FlowSchema] + +// FlowSchemaDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for FlowSchema. +type FlowSchemaDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1.FlowSchema] + +// FlowSchemaFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for FlowSchema. +type FlowSchemaFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1.FlowSchema] + +// FlowSchemaIndexers is a specialization of [cache.TypedIndexers] for FlowSchema. +type FlowSchemaIndexers = cache.TypedIndexers[*apiflowcontrolv1.FlowSchema] + +// DeletedFlowSchema is a specialization of [cache.DeletedObject] for FlowSchema. +type DeletedFlowSchema = cache.DeletedObject[*apiflowcontrolv1.FlowSchema] + type flowSchemaInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type flowSchemaInformer struct { // NewFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformer]). func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredFlowSchemaInformer]). func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformerWithOptions]). func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, options) +} + +// NewTypedFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) FlowSchemaIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1", Resource: "flowschemas"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.FlowSchema](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options inter Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1.FlowSchema{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *flowSchemaInformer) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.FlowSchema](f.factory.InformerFor(&apiflowcontrolv1.FlowSchema{}, f.defaultInformer)) } func (f *flowSchemaInformer) Lister() flowcontrolv1.FlowSchemaLister { return flowcontrolv1.NewFlowSchemaLister(f.Informer().GetIndexer()) } + +// ToTypedFlowSchemaInformer converts an untyped informer into a TypedFlowSchemaInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// TypedFlowSchemaInformer leads to runtime panics. A safer alternative is to pass +// around a TypedFlowSchemaInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedFlowSchemaInformer(informer FlowSchemaInformer) TypedFlowSchemaInformer { + if informer, ok := informer.(TypedFlowSchemaInformer); ok { + return informer + } + return &flowSchemaTypedInformerAdapter{informer} +} + +type flowSchemaTypedInformerAdapter struct { + FlowSchemaInformer +} + +func (a *flowSchemaTypedInformerAdapter) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.FlowSchema](a.Informer()) +} + +// ToFlowSchemaIndexInformer converts an untyped informer into a FlowSchemaIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// FlowSchemaIndexInformer leads to runtime panics. A safer alternative is to pass +// around a FlowSchemaIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToFlowSchemaIndexInformer(informer cache.SharedIndexInformer) FlowSchemaIndexInformer { + if informer, ok := informer.(FlowSchemaIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.FlowSchema](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/interface.go index 3de934900..2c4a8465c 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // FlowSchemas returns a FlowSchemaInformer. - FlowSchemas() FlowSchemaInformer + FlowSchemas() TypedFlowSchemaInformer // PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. - PriorityLevelConfigurations() PriorityLevelConfigurationInformer + PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// FlowSchemas returns a FlowSchemaInformer. -func (v *version) FlowSchemas() FlowSchemaInformer { +// FlowSchemas returns a TypedFlowSchemaInformer. +func (v *version) FlowSchemas() TypedFlowSchemaInformer { return &flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. -func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer { +// PriorityLevelConfigurations returns a TypedPriorityLevelConfigurationInformer. +func (v *version) PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer { return &priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/prioritylevelconfiguration.go index 5a4250955..7fd72aa9b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1/prioritylevelconfiguration.go @@ -34,12 +34,40 @@ import ( ) // PriorityLevelConfigurationInformer provides access to a shared informer and lister for -// PriorityLevelConfigurations. +// PriorityLevelConfigurations. Prefer using the type-safe variant (see [TypedPriorityLevelConfigurationInformer]). type PriorityLevelConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1.PriorityLevelConfigurationLister } +// TypedPriorityLevelConfigurationInformer provides access to a shared informer and lister for +// PriorityLevelConfigurations, including the type-safe TypedInformer variant. +// It is a superset of PriorityLevelConfigurationInformer. +type TypedPriorityLevelConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityLevelConfigurationIndexInformer + Lister() flowcontrolv1.PriorityLevelConfigurationLister +} + +// PriorityLevelConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityLevelConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityLevelConfiguration. +type PriorityLevelConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationIndexers is a specialization of [cache.TypedIndexers] for PriorityLevelConfiguration. +type PriorityLevelConfigurationIndexers = cache.TypedIndexers[*apiflowcontrolv1.PriorityLevelConfiguration] + +// DeletedPriorityLevelConfiguration is a specialization of [cache.DeletedObject] for PriorityLevelConfiguration. +type DeletedPriorityLevelConfiguration = cache.DeletedObject[*apiflowcontrolv1.PriorityLevelConfiguration] + type priorityLevelConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityLevelConfigurationInformer struct { // NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformer]). func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityLevelConfigurationInformer]). func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformerWithOptions]). func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, options) +} + +// NewTypedPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityLevelConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1", Resource: "prioritylevelconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.PriorityLevelConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interfac Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1.PriorityLevelConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityLevelConfigurationInformer) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.PriorityLevelConfiguration](f.factory.InformerFor(&apiflowcontrolv1.PriorityLevelConfiguration{}, f.defaultInformer)) } func (f *priorityLevelConfigurationInformer) Lister() flowcontrolv1.PriorityLevelConfigurationLister { return flowcontrolv1.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityLevelConfigurationInformer converts an untyped informer into a TypedPriorityLevelConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedPriorityLevelConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityLevelConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityLevelConfigurationInformer(informer PriorityLevelConfigurationInformer) TypedPriorityLevelConfigurationInformer { + if informer, ok := informer.(TypedPriorityLevelConfigurationInformer); ok { + return informer + } + return &priorityLevelConfigurationTypedInformerAdapter{informer} +} + +type priorityLevelConfigurationTypedInformerAdapter struct { + PriorityLevelConfigurationInformer +} + +func (a *priorityLevelConfigurationTypedInformerAdapter) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.PriorityLevelConfiguration](a.Informer()) +} + +// ToPriorityLevelConfigurationIndexInformer converts an untyped informer into a PriorityLevelConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// PriorityLevelConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityLevelConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityLevelConfigurationIndexInformer(informer cache.SharedIndexInformer) PriorityLevelConfigurationIndexInformer { + if informer, ok := informer.(PriorityLevelConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1.PriorityLevelConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go index 2e0098e66..d0d8778b3 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go @@ -34,12 +34,40 @@ import ( ) // FlowSchemaInformer provides access to a shared informer and lister for -// FlowSchemas. +// FlowSchemas. Prefer using the type-safe variant (see [TypedFlowSchemaInformer]). type FlowSchemaInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta1.FlowSchemaLister } +// TypedFlowSchemaInformer provides access to a shared informer and lister for +// FlowSchemas, including the type-safe TypedInformer variant. +// It is a superset of FlowSchemaInformer. +type TypedFlowSchemaInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() FlowSchemaIndexInformer + Lister() flowcontrolv1beta1.FlowSchemaLister +} + +// FlowSchemaIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type FlowSchemaIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta1.FlowSchema] + +// FlowSchemaHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for FlowSchema. +type FlowSchemaHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta1.FlowSchema] + +// FlowSchemaDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for FlowSchema. +type FlowSchemaDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta1.FlowSchema] + +// FlowSchemaFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for FlowSchema. +type FlowSchemaFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta1.FlowSchema] + +// FlowSchemaIndexers is a specialization of [cache.TypedIndexers] for FlowSchema. +type FlowSchemaIndexers = cache.TypedIndexers[*apiflowcontrolv1beta1.FlowSchema] + +// DeletedFlowSchema is a specialization of [cache.DeletedObject] for FlowSchema. +type DeletedFlowSchema = cache.DeletedObject[*apiflowcontrolv1beta1.FlowSchema] + type flowSchemaInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type flowSchemaInformer struct { // NewFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformer]). func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredFlowSchemaInformer]). func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformerWithOptions]). func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, options) +} + +// NewTypedFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) FlowSchemaIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta1", Resource: "flowschemas"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.FlowSchema](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options inter Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta1.FlowSchema{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *flowSchemaInformer) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.FlowSchema](f.factory.InformerFor(&apiflowcontrolv1beta1.FlowSchema{}, f.defaultInformer)) } func (f *flowSchemaInformer) Lister() flowcontrolv1beta1.FlowSchemaLister { return flowcontrolv1beta1.NewFlowSchemaLister(f.Informer().GetIndexer()) } + +// ToTypedFlowSchemaInformer converts an untyped informer into a TypedFlowSchemaInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// TypedFlowSchemaInformer leads to runtime panics. A safer alternative is to pass +// around a TypedFlowSchemaInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedFlowSchemaInformer(informer FlowSchemaInformer) TypedFlowSchemaInformer { + if informer, ok := informer.(TypedFlowSchemaInformer); ok { + return informer + } + return &flowSchemaTypedInformerAdapter{informer} +} + +type flowSchemaTypedInformerAdapter struct { + FlowSchemaInformer +} + +func (a *flowSchemaTypedInformerAdapter) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.FlowSchema](a.Informer()) +} + +// ToFlowSchemaIndexInformer converts an untyped informer into a FlowSchemaIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// FlowSchemaIndexInformer leads to runtime panics. A safer alternative is to pass +// around a FlowSchemaIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToFlowSchemaIndexInformer(informer cache.SharedIndexInformer) FlowSchemaIndexInformer { + if informer, ok := informer.(FlowSchemaIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.FlowSchema](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go index 50329bb0a..576d8de67 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // FlowSchemas returns a FlowSchemaInformer. - FlowSchemas() FlowSchemaInformer + FlowSchemas() TypedFlowSchemaInformer // PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. - PriorityLevelConfigurations() PriorityLevelConfigurationInformer + PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// FlowSchemas returns a FlowSchemaInformer. -func (v *version) FlowSchemas() FlowSchemaInformer { +// FlowSchemas returns a TypedFlowSchemaInformer. +func (v *version) FlowSchemas() TypedFlowSchemaInformer { return &flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. -func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer { +// PriorityLevelConfigurations returns a TypedPriorityLevelConfigurationInformer. +func (v *version) PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer { return &priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go index 9c94839a1..2b5cb8832 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go @@ -34,12 +34,40 @@ import ( ) // PriorityLevelConfigurationInformer provides access to a shared informer and lister for -// PriorityLevelConfigurations. +// PriorityLevelConfigurations. Prefer using the type-safe variant (see [TypedPriorityLevelConfigurationInformer]). type PriorityLevelConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta1.PriorityLevelConfigurationLister } +// TypedPriorityLevelConfigurationInformer provides access to a shared informer and lister for +// PriorityLevelConfigurations, including the type-safe TypedInformer variant. +// It is a superset of PriorityLevelConfigurationInformer. +type TypedPriorityLevelConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityLevelConfigurationIndexInformer + Lister() flowcontrolv1beta1.PriorityLevelConfigurationLister +} + +// PriorityLevelConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityLevelConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityLevelConfiguration. +type PriorityLevelConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + +// PriorityLevelConfigurationIndexers is a specialization of [cache.TypedIndexers] for PriorityLevelConfiguration. +type PriorityLevelConfigurationIndexers = cache.TypedIndexers[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + +// DeletedPriorityLevelConfiguration is a specialization of [cache.DeletedObject] for PriorityLevelConfiguration. +type DeletedPriorityLevelConfiguration = cache.DeletedObject[*apiflowcontrolv1beta1.PriorityLevelConfiguration] + type priorityLevelConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityLevelConfigurationInformer struct { // NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformer]). func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityLevelConfigurationInformer]). func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformerWithOptions]). func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, options) +} + +// NewTypedPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityLevelConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta1", Resource: "prioritylevelconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.PriorityLevelConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interfac Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta1.PriorityLevelConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityLevelConfigurationInformer) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.PriorityLevelConfiguration](f.factory.InformerFor(&apiflowcontrolv1beta1.PriorityLevelConfiguration{}, f.defaultInformer)) } func (f *priorityLevelConfigurationInformer) Lister() flowcontrolv1beta1.PriorityLevelConfigurationLister { return flowcontrolv1beta1.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityLevelConfigurationInformer converts an untyped informer into a TypedPriorityLevelConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedPriorityLevelConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityLevelConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityLevelConfigurationInformer(informer PriorityLevelConfigurationInformer) TypedPriorityLevelConfigurationInformer { + if informer, ok := informer.(TypedPriorityLevelConfigurationInformer); ok { + return informer + } + return &priorityLevelConfigurationTypedInformerAdapter{informer} +} + +type priorityLevelConfigurationTypedInformerAdapter struct { + PriorityLevelConfigurationInformer +} + +func (a *priorityLevelConfigurationTypedInformerAdapter) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.PriorityLevelConfiguration](a.Informer()) +} + +// ToPriorityLevelConfigurationIndexInformer converts an untyped informer into a PriorityLevelConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// PriorityLevelConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityLevelConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityLevelConfigurationIndexInformer(informer cache.SharedIndexInformer) PriorityLevelConfigurationIndexInformer { + if informer, ok := informer.(PriorityLevelConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta1.PriorityLevelConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go index aba4d712a..39cb1fbdf 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go @@ -34,12 +34,40 @@ import ( ) // FlowSchemaInformer provides access to a shared informer and lister for -// FlowSchemas. +// FlowSchemas. Prefer using the type-safe variant (see [TypedFlowSchemaInformer]). type FlowSchemaInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta2.FlowSchemaLister } +// TypedFlowSchemaInformer provides access to a shared informer and lister for +// FlowSchemas, including the type-safe TypedInformer variant. +// It is a superset of FlowSchemaInformer. +type TypedFlowSchemaInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() FlowSchemaIndexInformer + Lister() flowcontrolv1beta2.FlowSchemaLister +} + +// FlowSchemaIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type FlowSchemaIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta2.FlowSchema] + +// FlowSchemaHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for FlowSchema. +type FlowSchemaHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta2.FlowSchema] + +// FlowSchemaDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for FlowSchema. +type FlowSchemaDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta2.FlowSchema] + +// FlowSchemaFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for FlowSchema. +type FlowSchemaFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta2.FlowSchema] + +// FlowSchemaIndexers is a specialization of [cache.TypedIndexers] for FlowSchema. +type FlowSchemaIndexers = cache.TypedIndexers[*apiflowcontrolv1beta2.FlowSchema] + +// DeletedFlowSchema is a specialization of [cache.DeletedObject] for FlowSchema. +type DeletedFlowSchema = cache.DeletedObject[*apiflowcontrolv1beta2.FlowSchema] + type flowSchemaInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type flowSchemaInformer struct { // NewFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformer]). func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredFlowSchemaInformer]). func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformerWithOptions]). func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, options) +} + +// NewTypedFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) FlowSchemaIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta2", Resource: "flowschemas"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.FlowSchema](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options inter Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta2.FlowSchema{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *flowSchemaInformer) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.FlowSchema](f.factory.InformerFor(&apiflowcontrolv1beta2.FlowSchema{}, f.defaultInformer)) } func (f *flowSchemaInformer) Lister() flowcontrolv1beta2.FlowSchemaLister { return flowcontrolv1beta2.NewFlowSchemaLister(f.Informer().GetIndexer()) } + +// ToTypedFlowSchemaInformer converts an untyped informer into a TypedFlowSchemaInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// TypedFlowSchemaInformer leads to runtime panics. A safer alternative is to pass +// around a TypedFlowSchemaInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedFlowSchemaInformer(informer FlowSchemaInformer) TypedFlowSchemaInformer { + if informer, ok := informer.(TypedFlowSchemaInformer); ok { + return informer + } + return &flowSchemaTypedInformerAdapter{informer} +} + +type flowSchemaTypedInformerAdapter struct { + FlowSchemaInformer +} + +func (a *flowSchemaTypedInformerAdapter) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.FlowSchema](a.Informer()) +} + +// ToFlowSchemaIndexInformer converts an untyped informer into a FlowSchemaIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// FlowSchemaIndexInformer leads to runtime panics. A safer alternative is to pass +// around a FlowSchemaIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToFlowSchemaIndexInformer(informer cache.SharedIndexInformer) FlowSchemaIndexInformer { + if informer, ok := informer.(FlowSchemaIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.FlowSchema](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go index 142d55289..f362f533b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // FlowSchemas returns a FlowSchemaInformer. - FlowSchemas() FlowSchemaInformer + FlowSchemas() TypedFlowSchemaInformer // PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. - PriorityLevelConfigurations() PriorityLevelConfigurationInformer + PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// FlowSchemas returns a FlowSchemaInformer. -func (v *version) FlowSchemas() FlowSchemaInformer { +// FlowSchemas returns a TypedFlowSchemaInformer. +func (v *version) FlowSchemas() TypedFlowSchemaInformer { return &flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. -func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer { +// PriorityLevelConfigurations returns a TypedPriorityLevelConfigurationInformer. +func (v *version) PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer { return &priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go index 0ce811759..991527549 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go @@ -34,12 +34,40 @@ import ( ) // PriorityLevelConfigurationInformer provides access to a shared informer and lister for -// PriorityLevelConfigurations. +// PriorityLevelConfigurations. Prefer using the type-safe variant (see [TypedPriorityLevelConfigurationInformer]). type PriorityLevelConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta2.PriorityLevelConfigurationLister } +// TypedPriorityLevelConfigurationInformer provides access to a shared informer and lister for +// PriorityLevelConfigurations, including the type-safe TypedInformer variant. +// It is a superset of PriorityLevelConfigurationInformer. +type TypedPriorityLevelConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityLevelConfigurationIndexInformer + Lister() flowcontrolv1beta2.PriorityLevelConfigurationLister +} + +// PriorityLevelConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityLevelConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + +// PriorityLevelConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + +// PriorityLevelConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + +// PriorityLevelConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityLevelConfiguration. +type PriorityLevelConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + +// PriorityLevelConfigurationIndexers is a specialization of [cache.TypedIndexers] for PriorityLevelConfiguration. +type PriorityLevelConfigurationIndexers = cache.TypedIndexers[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + +// DeletedPriorityLevelConfiguration is a specialization of [cache.DeletedObject] for PriorityLevelConfiguration. +type DeletedPriorityLevelConfiguration = cache.DeletedObject[*apiflowcontrolv1beta2.PriorityLevelConfiguration] + type priorityLevelConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityLevelConfigurationInformer struct { // NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformer]). func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityLevelConfigurationInformer]). func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformerWithOptions]). func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, options) +} + +// NewTypedPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityLevelConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta2", Resource: "prioritylevelconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.PriorityLevelConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interfac Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta2.PriorityLevelConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityLevelConfigurationInformer) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.PriorityLevelConfiguration](f.factory.InformerFor(&apiflowcontrolv1beta2.PriorityLevelConfiguration{}, f.defaultInformer)) } func (f *priorityLevelConfigurationInformer) Lister() flowcontrolv1beta2.PriorityLevelConfigurationLister { return flowcontrolv1beta2.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityLevelConfigurationInformer converts an untyped informer into a TypedPriorityLevelConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedPriorityLevelConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityLevelConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityLevelConfigurationInformer(informer PriorityLevelConfigurationInformer) TypedPriorityLevelConfigurationInformer { + if informer, ok := informer.(TypedPriorityLevelConfigurationInformer); ok { + return informer + } + return &priorityLevelConfigurationTypedInformerAdapter{informer} +} + +type priorityLevelConfigurationTypedInformerAdapter struct { + PriorityLevelConfigurationInformer +} + +func (a *priorityLevelConfigurationTypedInformerAdapter) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.PriorityLevelConfiguration](a.Informer()) +} + +// ToPriorityLevelConfigurationIndexInformer converts an untyped informer into a PriorityLevelConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// PriorityLevelConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityLevelConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityLevelConfigurationIndexInformer(informer cache.SharedIndexInformer) PriorityLevelConfigurationIndexInformer { + if informer, ok := informer.(PriorityLevelConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta2.PriorityLevelConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go index 16ce2ba23..30bd5e341 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go @@ -34,12 +34,40 @@ import ( ) // FlowSchemaInformer provides access to a shared informer and lister for -// FlowSchemas. +// FlowSchemas. Prefer using the type-safe variant (see [TypedFlowSchemaInformer]). type FlowSchemaInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta3.FlowSchemaLister } +// TypedFlowSchemaInformer provides access to a shared informer and lister for +// FlowSchemas, including the type-safe TypedInformer variant. +// It is a superset of FlowSchemaInformer. +type TypedFlowSchemaInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() FlowSchemaIndexInformer + Lister() flowcontrolv1beta3.FlowSchemaLister +} + +// FlowSchemaIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type FlowSchemaIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta3.FlowSchema] + +// FlowSchemaHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for FlowSchema. +type FlowSchemaHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta3.FlowSchema] + +// FlowSchemaDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for FlowSchema. +type FlowSchemaDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta3.FlowSchema] + +// FlowSchemaFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for FlowSchema. +type FlowSchemaFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta3.FlowSchema] + +// FlowSchemaIndexers is a specialization of [cache.TypedIndexers] for FlowSchema. +type FlowSchemaIndexers = cache.TypedIndexers[*apiflowcontrolv1beta3.FlowSchema] + +// DeletedFlowSchema is a specialization of [cache.DeletedObject] for FlowSchema. +type DeletedFlowSchema = cache.DeletedObject[*apiflowcontrolv1beta3.FlowSchema] + type flowSchemaInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type flowSchemaInformer struct { // NewFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformer]). func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredFlowSchemaInformer]). func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredFlowSchemaInformer constructs a new informer for FlowSchema type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers FlowSchemaIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) FlowSchemaIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFlowSchemaInformerWithOptions]). func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedFlowSchemaInformerWithOptions(client, options) +} + +// NewTypedFlowSchemaInformerWithOptions constructs a new informer for FlowSchema type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFlowSchemaInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) FlowSchemaIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta3", Resource: "flowschemas"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.FlowSchema](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewFlowSchemaInformerWithOptions(client kubernetes.Interface, options inter Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedFlowSchemaInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta3.FlowSchema{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *flowSchemaInformer) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.FlowSchema](f.factory.InformerFor(&apiflowcontrolv1beta3.FlowSchema{}, f.defaultInformer)) } func (f *flowSchemaInformer) Lister() flowcontrolv1beta3.FlowSchemaLister { return flowcontrolv1beta3.NewFlowSchemaLister(f.Informer().GetIndexer()) } + +// ToTypedFlowSchemaInformer converts an untyped informer into a TypedFlowSchemaInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// TypedFlowSchemaInformer leads to runtime panics. A safer alternative is to pass +// around a TypedFlowSchemaInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedFlowSchemaInformer(informer FlowSchemaInformer) TypedFlowSchemaInformer { + if informer, ok := informer.(TypedFlowSchemaInformer); ok { + return informer + } + return &flowSchemaTypedInformerAdapter{informer} +} + +type flowSchemaTypedInformerAdapter struct { + FlowSchemaInformer +} + +func (a *flowSchemaTypedInformerAdapter) TypedInformer() FlowSchemaIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.FlowSchema](a.Informer()) +} + +// ToFlowSchemaIndexInformer converts an untyped informer into a FlowSchemaIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *FlowSchema. If that is not the case, calling type-safe methods of the returned +// FlowSchemaIndexInformer leads to runtime panics. A safer alternative is to pass +// around a FlowSchemaIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToFlowSchemaIndexInformer(informer cache.SharedIndexInformer) FlowSchemaIndexInformer { + if informer, ok := informer.(FlowSchemaIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.FlowSchema](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go index 54c5414a2..cff3a94cb 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // FlowSchemas returns a FlowSchemaInformer. - FlowSchemas() FlowSchemaInformer + FlowSchemas() TypedFlowSchemaInformer // PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. - PriorityLevelConfigurations() PriorityLevelConfigurationInformer + PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// FlowSchemas returns a FlowSchemaInformer. -func (v *version) FlowSchemas() FlowSchemaInformer { +// FlowSchemas returns a TypedFlowSchemaInformer. +func (v *version) FlowSchemas() TypedFlowSchemaInformer { return &flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer. -func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer { +// PriorityLevelConfigurations returns a TypedPriorityLevelConfigurationInformer. +func (v *version) PriorityLevelConfigurations() TypedPriorityLevelConfigurationInformer { return &priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go index ab63c8e62..0402662b8 100644 --- a/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go +++ b/constraint/vendor/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go @@ -34,12 +34,40 @@ import ( ) // PriorityLevelConfigurationInformer provides access to a shared informer and lister for -// PriorityLevelConfigurations. +// PriorityLevelConfigurations. Prefer using the type-safe variant (see [TypedPriorityLevelConfigurationInformer]). type PriorityLevelConfigurationInformer interface { Informer() cache.SharedIndexInformer Lister() flowcontrolv1beta3.PriorityLevelConfigurationLister } +// TypedPriorityLevelConfigurationInformer provides access to a shared informer and lister for +// PriorityLevelConfigurations, including the type-safe TypedInformer variant. +// It is a superset of PriorityLevelConfigurationInformer. +type TypedPriorityLevelConfigurationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityLevelConfigurationIndexInformer + Lister() flowcontrolv1beta3.PriorityLevelConfigurationLister +} + +// PriorityLevelConfigurationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityLevelConfigurationIndexInformer cache.TypedSharedIndexInformer[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + +// PriorityLevelConfigurationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + +// PriorityLevelConfigurationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityLevelConfiguration. +type PriorityLevelConfigurationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + +// PriorityLevelConfigurationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityLevelConfiguration. +type PriorityLevelConfigurationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + +// PriorityLevelConfigurationIndexers is a specialization of [cache.TypedIndexers] for PriorityLevelConfiguration. +type PriorityLevelConfigurationIndexers = cache.TypedIndexers[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + +// DeletedPriorityLevelConfiguration is a specialization of [cache.DeletedObject] for PriorityLevelConfiguration. +type DeletedPriorityLevelConfiguration = cache.DeletedObject[*apiflowcontrolv1beta3.PriorityLevelConfiguration] + type priorityLevelConfigurationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityLevelConfigurationInformer struct { // NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformer]). func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityLevelConfigurationInformer]). func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityLevelConfigurationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityLevelConfigurationIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityLevelConfigurationInformerWithOptions]). func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, options) +} + +// NewTypedPriorityLevelConfigurationInformerWithOptions constructs a new informer for PriorityLevelConfiguration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityLevelConfigurationIndexInformer { gvr := schema.GroupVersionResource{Group: "flowcontrol.apiserver.k8s.io", Version: "v1beta3", Resource: "prioritylevelconfigurations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.PriorityLevelConfiguration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityLevelConfigurationInformerWithOptions(client kubernetes.Interfac Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityLevelConfigurationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiflowcontrolv1beta3.PriorityLevelConfiguration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityLevelConfigurationInformer) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.PriorityLevelConfiguration](f.factory.InformerFor(&apiflowcontrolv1beta3.PriorityLevelConfiguration{}, f.defaultInformer)) } func (f *priorityLevelConfigurationInformer) Lister() flowcontrolv1beta3.PriorityLevelConfigurationLister { return flowcontrolv1beta3.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityLevelConfigurationInformer converts an untyped informer into a TypedPriorityLevelConfigurationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// TypedPriorityLevelConfigurationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityLevelConfigurationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityLevelConfigurationInformer(informer PriorityLevelConfigurationInformer) TypedPriorityLevelConfigurationInformer { + if informer, ok := informer.(TypedPriorityLevelConfigurationInformer); ok { + return informer + } + return &priorityLevelConfigurationTypedInformerAdapter{informer} +} + +type priorityLevelConfigurationTypedInformerAdapter struct { + PriorityLevelConfigurationInformer +} + +func (a *priorityLevelConfigurationTypedInformerAdapter) TypedInformer() PriorityLevelConfigurationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.PriorityLevelConfiguration](a.Informer()) +} + +// ToPriorityLevelConfigurationIndexInformer converts an untyped informer into a PriorityLevelConfigurationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityLevelConfiguration. If that is not the case, calling type-safe methods of the returned +// PriorityLevelConfigurationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityLevelConfigurationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityLevelConfigurationIndexInformer(informer cache.SharedIndexInformer) PriorityLevelConfigurationIndexInformer { + if informer, ok := informer.(PriorityLevelConfigurationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiflowcontrolv1beta3.PriorityLevelConfiguration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/generic.go b/constraint/vendor/k8s.io/client-go/informers/generic.go index 03c45c71c..ab966b949 100644 --- a/constraint/vendor/k8s.io/client-go/informers/generic.go +++ b/constraint/vendor/k8s.io/client-go/informers/generic.go @@ -48,6 +48,7 @@ import ( flowcontrolv1beta1 "k8s.io/api/flowcontrol/v1beta1" flowcontrolv1beta2 "k8s.io/api/flowcontrol/v1beta2" v1beta3 "k8s.io/api/flowcontrol/v1beta3" + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" networkingv1 "k8s.io/api/networking/v1" networkingv1beta1 "k8s.io/api/networking/v1beta1" nodev1 "k8s.io/api/node/v1" @@ -63,11 +64,12 @@ import ( resourcev1beta1 "k8s.io/api/resource/v1beta1" resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" storagev1 "k8s.io/api/storage/v1" storagev1alpha1 "k8s.io/api/storage/v1alpha1" storagev1beta1 "k8s.io/api/storage/v1beta1" + storagemigrationv1 "k8s.io/api/storagemigration/v1" storagemigrationv1beta1 "k8s.io/api/storagemigration/v1beta1" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" @@ -190,6 +192,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=certificates.k8s.io, Version=v1 case certificatesv1.SchemeGroupVersion.WithResource("certificatesigningrequests"): return &genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1().CertificateSigningRequests().Informer()}, nil + case certificatesv1.SchemeGroupVersion.WithResource("clustertrustbundles"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1().ClusterTrustBundles().Informer()}, nil + case certificatesv1.SchemeGroupVersion.WithResource("podcertificaterequests"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1().PodCertificateRequests().Informer()}, nil // Group=certificates.k8s.io, Version=v1alpha1 case certificatesv1alpha1.SchemeGroupVersion.WithResource("clustertrustbundles"): @@ -307,6 +313,12 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case apiserverinternalv1alpha1.SchemeGroupVersion.WithResource("storageversions"): return &genericInformer{resource: resource.GroupResource(), informer: f.Internal().V1alpha1().StorageVersions().Informer()}, nil + // Group=lifecycle.k8s.io, Version=v1alpha1 + case lifecyclev1alpha1.SchemeGroupVersion.WithResource("evictions"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Lifecycle().V1alpha1().Evictions().Informer()}, nil + case lifecyclev1alpha1.SchemeGroupVersion.WithResource("evictionrequests"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Lifecycle().V1alpha1().EvictionRequests().Informer()}, nil + // Group=networking.k8s.io, Version=v1 case networkingv1.SchemeGroupVersion.WithResource("ipaddresses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().IPAddresses().Informer()}, nil @@ -382,6 +394,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource // Group=resource.k8s.io, Version=v1 case resourcev1.SchemeGroupVersion.WithResource("deviceclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1().DeviceClasses().Informer()}, nil + case resourcev1.SchemeGroupVersion.WithResource("devicetaintrules"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1().DeviceTaintRules().Informer()}, nil case resourcev1.SchemeGroupVersion.WithResource("resourceclaims"): return &genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1().ResourceClaims().Informer()}, nil case resourcev1.SchemeGroupVersion.WithResource("resourceclaimtemplates"): @@ -421,15 +435,21 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case schedulingv1.SchemeGroupVersion.WithResource("priorityclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1().PriorityClasses().Informer()}, nil - // Group=scheduling.k8s.io, Version=v1alpha2 - case schedulingv1alpha2.SchemeGroupVersion.WithResource("podgroups"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha2().PodGroups().Informer()}, nil - case schedulingv1alpha2.SchemeGroupVersion.WithResource("workloads"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha2().Workloads().Informer()}, nil + // Group=scheduling.k8s.io, Version=v1alpha3 + case schedulingv1alpha3.SchemeGroupVersion.WithResource("compositepodgroups"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha3().CompositePodGroups().Informer()}, nil + case schedulingv1alpha3.SchemeGroupVersion.WithResource("podgroups"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha3().PodGroups().Informer()}, nil + case schedulingv1alpha3.SchemeGroupVersion.WithResource("workloads"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha3().Workloads().Informer()}, nil // Group=scheduling.k8s.io, Version=v1beta1 + case schedulingv1beta1.SchemeGroupVersion.WithResource("podgroups"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1beta1().PodGroups().Informer()}, nil case schedulingv1beta1.SchemeGroupVersion.WithResource("priorityclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1beta1().PriorityClasses().Informer()}, nil + case schedulingv1beta1.SchemeGroupVersion.WithResource("workloads"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1beta1().Workloads().Informer()}, nil // Group=storage.k8s.io, Version=v1 case storagev1.SchemeGroupVersion.WithResource("csidrivers"): @@ -467,6 +487,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case storagev1beta1.SchemeGroupVersion.WithResource("volumeattributesclasses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().VolumeAttributesClasses().Informer()}, nil + // Group=storagemigration.k8s.io, Version=v1 + case storagemigrationv1.SchemeGroupVersion.WithResource("storageversionmigrations"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Storagemigration().V1().StorageVersionMigrations().Informer()}, nil + // Group=storagemigration.k8s.io, Version=v1beta1 case storagemigrationv1beta1.SchemeGroupVersion.WithResource("storageversionmigrations"): return &genericInformer{resource: resource.GroupResource(), informer: f.Storagemigration().V1beta1().StorageVersionMigrations().Informer()}, nil diff --git a/constraint/vendor/k8s.io/client-go/informers/lifecycle/interface.go b/constraint/vendor/k8s.io/client-go/informers/lifecycle/interface.go new file mode 100644 index 000000000..c9b3e3476 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/lifecycle/interface.go @@ -0,0 +1,46 @@ +/* +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 informer-gen. DO NOT EDIT. + +package lifecycle + +import ( + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + v1alpha1 "k8s.io/client-go/informers/lifecycle/v1alpha1" +) + +// Interface provides access to each of this group's versions. +type Interface interface { + // V1alpha1 provides access to shared informers for resources in V1alpha1. + V1alpha1() v1alpha1.Interface +} + +type group struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// V1alpha1 returns a new v1alpha1.Interface. +func (g *group) V1alpha1() v1alpha1.Interface { + return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/eviction.go b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/eviction.go new file mode 100644 index 000000000..bf408957f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/eviction.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + time "time" + + apilifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + lifecyclev1alpha1 "k8s.io/client-go/listers/lifecycle/v1alpha1" + cache "k8s.io/client-go/tools/cache" +) + +// EvictionInformer provides access to a shared informer and lister for +// Evictions. Prefer using the type-safe variant (see [TypedEvictionInformer]). +type EvictionInformer interface { + Informer() cache.SharedIndexInformer + Lister() lifecyclev1alpha1.EvictionLister +} + +// TypedEvictionInformer provides access to a shared informer and lister for +// Evictions, including the type-safe TypedInformer variant. +// It is a superset of EvictionInformer. +type TypedEvictionInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EvictionIndexInformer + Lister() lifecyclev1alpha1.EvictionLister +} + +// EvictionIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EvictionIndexInformer cache.TypedSharedIndexInformer[*apilifecyclev1alpha1.Eviction] + +// EvictionHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Eviction. +type EvictionHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apilifecyclev1alpha1.Eviction] + +// EvictionDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Eviction. +type EvictionDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apilifecyclev1alpha1.Eviction] + +// EvictionFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Eviction. +type EvictionFilteringHandler = cache.TypedFilteringResourceEventHandler[*apilifecyclev1alpha1.Eviction] + +// EvictionIndexers is a specialization of [cache.TypedIndexers] for Eviction. +type EvictionIndexers = cache.TypedIndexers[*apilifecyclev1alpha1.Eviction] + +// DeletedEviction is a specialization of [cache.DeletedObject] for Eviction. +type DeletedEviction = cache.DeletedObject[*apilifecyclev1alpha1.Eviction] + +type evictionInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewEvictionInformer constructs a new informer for Eviction type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEvictionInformer]). +func NewEvictionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewEvictionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedEvictionInformer constructs a new informer for Eviction type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEvictionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EvictionIndexers) EvictionIndexInformer { + return NewTypedEvictionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredEvictionInformer constructs a new informer for Eviction type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEvictionInformer]). +func NewFilteredEvictionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedEvictionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEvictionInformer constructs a new informer for Eviction type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEvictionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EvictionIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EvictionIndexInformer { + return NewTypedEvictionInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewEvictionInformerWithOptions constructs a new informer for Eviction type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEvictionInformerWithOptions]). +func NewEvictionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEvictionInformerWithOptions(client, namespace, options) +} + +// NewTypedEvictionInformerWithOptions constructs a new informer for Eviction type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEvictionInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EvictionIndexInformer { + gvr := schema.GroupVersionResource{Group: "lifecycle.k8s.io", Version: "v1alpha1", Resource: "evictions"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.Eviction](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().Evictions(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().Evictions(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().Evictions(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().Evictions(namespace).Watch(ctx, opts) + }, + }, client), + &apilifecyclev1alpha1.Eviction{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *evictionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedEvictionInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *evictionInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *evictionInformer) TypedInformer() EvictionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.Eviction](f.factory.InformerFor(&apilifecyclev1alpha1.Eviction{}, f.defaultInformer)) +} + +func (f *evictionInformer) Lister() lifecyclev1alpha1.EvictionLister { + return lifecyclev1alpha1.NewEvictionLister(f.Informer().GetIndexer()) +} + +// ToTypedEvictionInformer converts an untyped informer into a TypedEvictionInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Eviction. If that is not the case, calling type-safe methods of the returned +// TypedEvictionInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEvictionInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEvictionInformer(informer EvictionInformer) TypedEvictionInformer { + if informer, ok := informer.(TypedEvictionInformer); ok { + return informer + } + return &evictionTypedInformerAdapter{informer} +} + +type evictionTypedInformerAdapter struct { + EvictionInformer +} + +func (a *evictionTypedInformerAdapter) TypedInformer() EvictionIndexInformer { + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.Eviction](a.Informer()) +} + +// ToEvictionIndexInformer converts an untyped informer into a EvictionIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Eviction. If that is not the case, calling type-safe methods of the returned +// EvictionIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EvictionIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEvictionIndexInformer(informer cache.SharedIndexInformer) EvictionIndexInformer { + if informer, ok := informer.(EvictionIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.Eviction](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/evictionrequest.go b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/evictionrequest.go new file mode 100644 index 000000000..2e7615740 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/evictionrequest.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + time "time" + + apilifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + lifecyclev1alpha1 "k8s.io/client-go/listers/lifecycle/v1alpha1" + cache "k8s.io/client-go/tools/cache" +) + +// EvictionRequestInformer provides access to a shared informer and lister for +// EvictionRequests. Prefer using the type-safe variant (see [TypedEvictionRequestInformer]). +type EvictionRequestInformer interface { + Informer() cache.SharedIndexInformer + Lister() lifecyclev1alpha1.EvictionRequestLister +} + +// TypedEvictionRequestInformer provides access to a shared informer and lister for +// EvictionRequests, including the type-safe TypedInformer variant. +// It is a superset of EvictionRequestInformer. +type TypedEvictionRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() EvictionRequestIndexInformer + Lister() lifecyclev1alpha1.EvictionRequestLister +} + +// EvictionRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type EvictionRequestIndexInformer cache.TypedSharedIndexInformer[*apilifecyclev1alpha1.EvictionRequest] + +// EvictionRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for EvictionRequest. +type EvictionRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apilifecyclev1alpha1.EvictionRequest] + +// EvictionRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for EvictionRequest. +type EvictionRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apilifecyclev1alpha1.EvictionRequest] + +// EvictionRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for EvictionRequest. +type EvictionRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apilifecyclev1alpha1.EvictionRequest] + +// EvictionRequestIndexers is a specialization of [cache.TypedIndexers] for EvictionRequest. +type EvictionRequestIndexers = cache.TypedIndexers[*apilifecyclev1alpha1.EvictionRequest] + +// DeletedEvictionRequest is a specialization of [cache.DeletedObject] for EvictionRequest. +type DeletedEvictionRequest = cache.DeletedObject[*apilifecyclev1alpha1.EvictionRequest] + +type evictionRequestInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewEvictionRequestInformer constructs a new informer for EvictionRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEvictionRequestInformer]). +func NewEvictionRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewEvictionRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedEvictionRequestInformer constructs a new informer for EvictionRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEvictionRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EvictionRequestIndexers) EvictionRequestIndexInformer { + return NewTypedEvictionRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredEvictionRequestInformer constructs a new informer for EvictionRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredEvictionRequestInformer]). +func NewFilteredEvictionRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedEvictionRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredEvictionRequestInformer constructs a new informer for EvictionRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredEvictionRequestInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers EvictionRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) EvictionRequestIndexInformer { + return NewTypedEvictionRequestInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewEvictionRequestInformerWithOptions constructs a new informer for EvictionRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedEvictionRequestInformerWithOptions]). +func NewEvictionRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedEvictionRequestInformerWithOptions(client, namespace, options) +} + +// NewTypedEvictionRequestInformerWithOptions constructs a new informer for EvictionRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedEvictionRequestInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) EvictionRequestIndexInformer { + gvr := schema.GroupVersionResource{Group: "lifecycle.k8s.io", Version: "v1alpha1", Resource: "evictionrequests"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.EvictionRequest](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().EvictionRequests(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().EvictionRequests(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().EvictionRequests(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.LifecycleV1alpha1().EvictionRequests(namespace).Watch(ctx, opts) + }, + }, client), + &apilifecyclev1alpha1.EvictionRequest{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *evictionRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedEvictionRequestInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *evictionRequestInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *evictionRequestInformer) TypedInformer() EvictionRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.EvictionRequest](f.factory.InformerFor(&apilifecyclev1alpha1.EvictionRequest{}, f.defaultInformer)) +} + +func (f *evictionRequestInformer) Lister() lifecyclev1alpha1.EvictionRequestLister { + return lifecyclev1alpha1.NewEvictionRequestLister(f.Informer().GetIndexer()) +} + +// ToTypedEvictionRequestInformer converts an untyped informer into a TypedEvictionRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EvictionRequest. If that is not the case, calling type-safe methods of the returned +// TypedEvictionRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedEvictionRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedEvictionRequestInformer(informer EvictionRequestInformer) TypedEvictionRequestInformer { + if informer, ok := informer.(TypedEvictionRequestInformer); ok { + return informer + } + return &evictionRequestTypedInformerAdapter{informer} +} + +type evictionRequestTypedInformerAdapter struct { + EvictionRequestInformer +} + +func (a *evictionRequestTypedInformerAdapter) TypedInformer() EvictionRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.EvictionRequest](a.Informer()) +} + +// ToEvictionRequestIndexInformer converts an untyped informer into a EvictionRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *EvictionRequest. If that is not the case, calling type-safe methods of the returned +// EvictionRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a EvictionRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToEvictionRequestIndexInformer(informer cache.SharedIndexInformer) EvictionRequestIndexInformer { + if informer, ok := informer.(EvictionRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apilifecyclev1alpha1.EvictionRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/interface.go new file mode 100644 index 000000000..81141bb1c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/lifecycle/v1alpha1/interface.go @@ -0,0 +1,52 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // Evictions returns a EvictionInformer. + Evictions() TypedEvictionInformer + // EvictionRequests returns a EvictionRequestInformer. + EvictionRequests() TypedEvictionRequestInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// Evictions returns a TypedEvictionInformer. +func (v *version) Evictions() TypedEvictionInformer { + return &evictionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// EvictionRequests returns a TypedEvictionRequestInformer. +func (v *version) EvictionRequests() TypedEvictionRequestInformer { + return &evictionRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingress.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingress.go index 65be7320d..9ec5a53dc 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingress.go @@ -34,12 +34,40 @@ import ( ) // IngressInformer provides access to a shared informer and lister for -// Ingresses. +// Ingresses. Prefer using the type-safe variant (see [TypedIngressInformer]). type IngressInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1.IngressLister } +// TypedIngressInformer provides access to a shared informer and lister for +// Ingresses, including the type-safe TypedInformer variant. +// It is a superset of IngressInformer. +type TypedIngressInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IngressIndexInformer + Lister() networkingv1.IngressLister +} + +// IngressIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IngressIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1.Ingress] + +// IngressHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Ingress. +type IngressHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1.Ingress] + +// IngressDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Ingress. +type IngressDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1.Ingress] + +// IngressFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Ingress. +type IngressFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1.Ingress] + +// IngressIndexers is a specialization of [cache.TypedIndexers] for Ingress. +type IngressIndexers = cache.TypedIndexers[*apinetworkingv1.Ingress] + +// DeletedIngress is a specialization of [cache.DeletedObject] for Ingress. +type DeletedIngress = cache.DeletedObject[*apinetworkingv1.Ingress] + type ingressInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type ingressInformer struct { // NewIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformer]). func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIngressInformer]). func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIngressInformerWithOptions constructs a new informer for Ingress type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformerWithOptions]). func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, options) +} + +// NewTypedIngressInformerWithOptions constructs a new informer for Ingress type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) IngressIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "ingresss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.Ingress](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *ingressInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1.Ingress{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *ingressInformer) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.Ingress](f.factory.InformerFor(&apinetworkingv1.Ingress{}, f.defaultInformer)) } func (f *ingressInformer) Lister() networkingv1.IngressLister { return networkingv1.NewIngressLister(f.Informer().GetIndexer()) } + +// ToTypedIngressInformer converts an untyped informer into a TypedIngressInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// TypedIngressInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIngressInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIngressInformer(informer IngressInformer) TypedIngressInformer { + if informer, ok := informer.(TypedIngressInformer); ok { + return informer + } + return &ingressTypedInformerAdapter{informer} +} + +type ingressTypedInformerAdapter struct { + IngressInformer +} + +func (a *ingressTypedInformerAdapter) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.Ingress](a.Informer()) +} + +// ToIngressIndexInformer converts an untyped informer into a IngressIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// IngressIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IngressIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIngressIndexInformer(informer cache.SharedIndexInformer) IngressIndexInformer { + if informer, ok := informer.(IngressIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.Ingress](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingressclass.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingressclass.go index bcb118f99..9174877fe 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingressclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ingressclass.go @@ -34,12 +34,40 @@ import ( ) // IngressClassInformer provides access to a shared informer and lister for -// IngressClasses. +// IngressClasses. Prefer using the type-safe variant (see [TypedIngressClassInformer]). type IngressClassInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1.IngressClassLister } +// TypedIngressClassInformer provides access to a shared informer and lister for +// IngressClasses, including the type-safe TypedInformer variant. +// It is a superset of IngressClassInformer. +type TypedIngressClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IngressClassIndexInformer + Lister() networkingv1.IngressClassLister +} + +// IngressClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IngressClassIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1.IngressClass] + +// IngressClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for IngressClass. +type IngressClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1.IngressClass] + +// IngressClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for IngressClass. +type IngressClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1.IngressClass] + +// IngressClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for IngressClass. +type IngressClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1.IngressClass] + +// IngressClassIndexers is a specialization of [cache.TypedIndexers] for IngressClass. +type IngressClassIndexers = cache.TypedIndexers[*apinetworkingv1.IngressClass] + +// DeletedIngressClass is a specialization of [cache.DeletedObject] for IngressClass. +type DeletedIngressClass = cache.DeletedObject[*apinetworkingv1.IngressClass] + type ingressClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type ingressClassInformer struct { // NewIngressClassInformer constructs a new informer for IngressClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressClassInformer]). func NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIngressClassInformer constructs a new informer for IngressClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IngressClassIndexers) IngressClassIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIngressClassInformer constructs a new informer for IngressClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIngressClassInformer]). func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIngressClassInformer constructs a new informer for IngressClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IngressClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IngressClassIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIngressClassInformerWithOptions constructs a new informer for IngressClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressClassInformerWithOptions]). func NewIngressClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, options) +} + +// NewTypedIngressClassInformerWithOptions constructs a new informer for IngressClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) IngressClassIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "ingressclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IngressClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewIngressClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *ingressClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1.IngressClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *ingressClassInformer) TypedInformer() IngressClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IngressClass](f.factory.InformerFor(&apinetworkingv1.IngressClass{}, f.defaultInformer)) } func (f *ingressClassInformer) Lister() networkingv1.IngressClassLister { return networkingv1.NewIngressClassLister(f.Informer().GetIndexer()) } + +// ToTypedIngressClassInformer converts an untyped informer into a TypedIngressClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IngressClass. If that is not the case, calling type-safe methods of the returned +// TypedIngressClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIngressClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIngressClassInformer(informer IngressClassInformer) TypedIngressClassInformer { + if informer, ok := informer.(TypedIngressClassInformer); ok { + return informer + } + return &ingressClassTypedInformerAdapter{informer} +} + +type ingressClassTypedInformerAdapter struct { + IngressClassInformer +} + +func (a *ingressClassTypedInformerAdapter) TypedInformer() IngressClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IngressClass](a.Informer()) +} + +// ToIngressClassIndexInformer converts an untyped informer into a IngressClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IngressClass. If that is not the case, calling type-safe methods of the returned +// IngressClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IngressClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIngressClassIndexInformer(informer cache.SharedIndexInformer) IngressClassIndexInformer { + if informer, ok := informer.(IngressClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IngressClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/interface.go index 09634929b..6fecd84d6 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/interface.go @@ -25,15 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // IPAddresses returns a IPAddressInformer. - IPAddresses() IPAddressInformer + IPAddresses() TypedIPAddressInformer // Ingresses returns a IngressInformer. - Ingresses() IngressInformer + Ingresses() TypedIngressInformer // IngressClasses returns a IngressClassInformer. - IngressClasses() IngressClassInformer + IngressClasses() TypedIngressClassInformer // NetworkPolicies returns a NetworkPolicyInformer. - NetworkPolicies() NetworkPolicyInformer + NetworkPolicies() TypedNetworkPolicyInformer // ServiceCIDRs returns a ServiceCIDRInformer. - ServiceCIDRs() ServiceCIDRInformer + ServiceCIDRs() TypedServiceCIDRInformer } type version struct { @@ -47,27 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// IPAddresses returns a IPAddressInformer. -func (v *version) IPAddresses() IPAddressInformer { +// IPAddresses returns a TypedIPAddressInformer. +func (v *version) IPAddresses() TypedIPAddressInformer { return &iPAddressInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Ingresses returns a IngressInformer. -func (v *version) Ingresses() IngressInformer { +// Ingresses returns a TypedIngressInformer. +func (v *version) Ingresses() TypedIngressInformer { return &ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// IngressClasses returns a IngressClassInformer. -func (v *version) IngressClasses() IngressClassInformer { +// IngressClasses returns a TypedIngressClassInformer. +func (v *version) IngressClasses() TypedIngressClassInformer { return &ingressClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// NetworkPolicies returns a NetworkPolicyInformer. -func (v *version) NetworkPolicies() NetworkPolicyInformer { +// NetworkPolicies returns a TypedNetworkPolicyInformer. +func (v *version) NetworkPolicies() TypedNetworkPolicyInformer { return &networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ServiceCIDRs returns a ServiceCIDRInformer. -func (v *version) ServiceCIDRs() ServiceCIDRInformer { +// ServiceCIDRs returns a TypedServiceCIDRInformer. +func (v *version) ServiceCIDRs() TypedServiceCIDRInformer { return &serviceCIDRInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ipaddress.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ipaddress.go index ea4bb280c..45d85ae87 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/ipaddress.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/ipaddress.go @@ -34,12 +34,40 @@ import ( ) // IPAddressInformer provides access to a shared informer and lister for -// IPAddresses. +// IPAddresses. Prefer using the type-safe variant (see [TypedIPAddressInformer]). type IPAddressInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1.IPAddressLister } +// TypedIPAddressInformer provides access to a shared informer and lister for +// IPAddresses, including the type-safe TypedInformer variant. +// It is a superset of IPAddressInformer. +type TypedIPAddressInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IPAddressIndexInformer + Lister() networkingv1.IPAddressLister +} + +// IPAddressIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IPAddressIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1.IPAddress] + +// IPAddressHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for IPAddress. +type IPAddressHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1.IPAddress] + +// IPAddressDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for IPAddress. +type IPAddressDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1.IPAddress] + +// IPAddressFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for IPAddress. +type IPAddressFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1.IPAddress] + +// IPAddressIndexers is a specialization of [cache.TypedIndexers] for IPAddress. +type IPAddressIndexers = cache.TypedIndexers[*apinetworkingv1.IPAddress] + +// DeletedIPAddress is a specialization of [cache.DeletedObject] for IPAddress. +type DeletedIPAddress = cache.DeletedObject[*apinetworkingv1.IPAddress] + type iPAddressInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type iPAddressInformer struct { // NewIPAddressInformer constructs a new informer for IPAddress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIPAddressInformer]). func NewIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IPAddressIndexers) IPAddressIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIPAddressInformer constructs a new informer for IPAddress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIPAddressInformer]). func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IPAddressIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IPAddressIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIPAddressInformerWithOptions constructs a new informer for IPAddress type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIPAddressInformerWithOptions]). func NewIPAddressInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, options) +} + +// NewTypedIPAddressInformerWithOptions constructs a new informer for IPAddress type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIPAddressInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) IPAddressIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "ipaddresss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IPAddress](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewIPAddressInformerWithOptions(client kubernetes.Interface, options intern Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *iPAddressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *iPAddressInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1.IPAddress{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *iPAddressInformer) TypedInformer() IPAddressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IPAddress](f.factory.InformerFor(&apinetworkingv1.IPAddress{}, f.defaultInformer)) } func (f *iPAddressInformer) Lister() networkingv1.IPAddressLister { return networkingv1.NewIPAddressLister(f.Informer().GetIndexer()) } + +// ToTypedIPAddressInformer converts an untyped informer into a TypedIPAddressInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IPAddress. If that is not the case, calling type-safe methods of the returned +// TypedIPAddressInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIPAddressInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIPAddressInformer(informer IPAddressInformer) TypedIPAddressInformer { + if informer, ok := informer.(TypedIPAddressInformer); ok { + return informer + } + return &iPAddressTypedInformerAdapter{informer} +} + +type iPAddressTypedInformerAdapter struct { + IPAddressInformer +} + +func (a *iPAddressTypedInformerAdapter) TypedInformer() IPAddressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IPAddress](a.Informer()) +} + +// ToIPAddressIndexInformer converts an untyped informer into a IPAddressIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IPAddress. If that is not the case, calling type-safe methods of the returned +// IPAddressIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IPAddressIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIPAddressIndexInformer(informer cache.SharedIndexInformer) IPAddressIndexInformer { + if informer, ok := informer.(IPAddressIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.IPAddress](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/networkpolicy.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/networkpolicy.go index 237fe6266..41586c52a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/networkpolicy.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/networkpolicy.go @@ -34,12 +34,40 @@ import ( ) // NetworkPolicyInformer provides access to a shared informer and lister for -// NetworkPolicies. +// NetworkPolicies. Prefer using the type-safe variant (see [TypedNetworkPolicyInformer]). type NetworkPolicyInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1.NetworkPolicyLister } +// TypedNetworkPolicyInformer provides access to a shared informer and lister for +// NetworkPolicies, including the type-safe TypedInformer variant. +// It is a superset of NetworkPolicyInformer. +type TypedNetworkPolicyInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() NetworkPolicyIndexInformer + Lister() networkingv1.NetworkPolicyLister +} + +// NetworkPolicyIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type NetworkPolicyIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1.NetworkPolicy] + +// NetworkPolicyHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for NetworkPolicy. +type NetworkPolicyHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1.NetworkPolicy] + +// NetworkPolicyDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for NetworkPolicy. +type NetworkPolicyDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1.NetworkPolicy] + +// NetworkPolicyFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for NetworkPolicy. +type NetworkPolicyFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1.NetworkPolicy] + +// NetworkPolicyIndexers is a specialization of [cache.TypedIndexers] for NetworkPolicy. +type NetworkPolicyIndexers = cache.TypedIndexers[*apinetworkingv1.NetworkPolicy] + +// DeletedNetworkPolicy is a specialization of [cache.DeletedObject] for NetworkPolicy. +type DeletedNetworkPolicy = cache.DeletedObject[*apinetworkingv1.NetworkPolicy] + type networkPolicyInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type networkPolicyInformer struct { // NewNetworkPolicyInformer constructs a new informer for NetworkPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNetworkPolicyInformer]). func NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedNetworkPolicyInformer constructs a new informer for NetworkPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers NetworkPolicyIndexers) NetworkPolicyIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredNetworkPolicyInformer]). func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers NetworkPolicyIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) NetworkPolicyIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewNetworkPolicyInformerWithOptions constructs a new informer for NetworkPolicy type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedNetworkPolicyInformerWithOptions]). func NewNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedNetworkPolicyInformerWithOptions(client, namespace, options) +} + +// NewTypedNetworkPolicyInformerWithOptions constructs a new informer for NetworkPolicy type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) NetworkPolicyIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "networkpolicys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.NetworkPolicy](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewNetworkPolicyInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewNetworkPolicyInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedNetworkPolicyInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1.NetworkPolicy{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *networkPolicyInformer) TypedInformer() NetworkPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.NetworkPolicy](f.factory.InformerFor(&apinetworkingv1.NetworkPolicy{}, f.defaultInformer)) } func (f *networkPolicyInformer) Lister() networkingv1.NetworkPolicyLister { return networkingv1.NewNetworkPolicyLister(f.Informer().GetIndexer()) } + +// ToTypedNetworkPolicyInformer converts an untyped informer into a TypedNetworkPolicyInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *NetworkPolicy. If that is not the case, calling type-safe methods of the returned +// TypedNetworkPolicyInformer leads to runtime panics. A safer alternative is to pass +// around a TypedNetworkPolicyInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedNetworkPolicyInformer(informer NetworkPolicyInformer) TypedNetworkPolicyInformer { + if informer, ok := informer.(TypedNetworkPolicyInformer); ok { + return informer + } + return &networkPolicyTypedInformerAdapter{informer} +} + +type networkPolicyTypedInformerAdapter struct { + NetworkPolicyInformer +} + +func (a *networkPolicyTypedInformerAdapter) TypedInformer() NetworkPolicyIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.NetworkPolicy](a.Informer()) +} + +// ToNetworkPolicyIndexInformer converts an untyped informer into a NetworkPolicyIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *NetworkPolicy. If that is not the case, calling type-safe methods of the returned +// NetworkPolicyIndexInformer leads to runtime panics. A safer alternative is to pass +// around a NetworkPolicyIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToNetworkPolicyIndexInformer(informer cache.SharedIndexInformer) NetworkPolicyIndexInformer { + if informer, ok := informer.(NetworkPolicyIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.NetworkPolicy](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1/servicecidr.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1/servicecidr.go index ee1810f81..e78ac8908 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1/servicecidr.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1/servicecidr.go @@ -34,12 +34,40 @@ import ( ) // ServiceCIDRInformer provides access to a shared informer and lister for -// ServiceCIDRs. +// ServiceCIDRs. Prefer using the type-safe variant (see [TypedServiceCIDRInformer]). type ServiceCIDRInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1.ServiceCIDRLister } +// TypedServiceCIDRInformer provides access to a shared informer and lister for +// ServiceCIDRs, including the type-safe TypedInformer variant. +// It is a superset of ServiceCIDRInformer. +type TypedServiceCIDRInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ServiceCIDRIndexInformer + Lister() networkingv1.ServiceCIDRLister +} + +// ServiceCIDRIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ServiceCIDRIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1.ServiceCIDR] + +// ServiceCIDRHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ServiceCIDR. +type ServiceCIDRHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1.ServiceCIDR] + +// ServiceCIDRDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ServiceCIDR. +type ServiceCIDRDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1.ServiceCIDR] + +// ServiceCIDRFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ServiceCIDR. +type ServiceCIDRFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1.ServiceCIDR] + +// ServiceCIDRIndexers is a specialization of [cache.TypedIndexers] for ServiceCIDR. +type ServiceCIDRIndexers = cache.TypedIndexers[*apinetworkingv1.ServiceCIDR] + +// DeletedServiceCIDR is a specialization of [cache.DeletedObject] for ServiceCIDR. +type DeletedServiceCIDR = cache.DeletedObject[*apinetworkingv1.ServiceCIDR] + type serviceCIDRInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type serviceCIDRInformer struct { // NewServiceCIDRInformer constructs a new informer for ServiceCIDR type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceCIDRInformer]). func NewServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ServiceCIDRIndexers) ServiceCIDRIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredServiceCIDRInformer constructs a new informer for ServiceCIDR type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredServiceCIDRInformer]). func NewFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ServiceCIDRIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ServiceCIDRIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewServiceCIDRInformerWithOptions constructs a new informer for ServiceCIDR type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceCIDRInformerWithOptions]). func NewServiceCIDRInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, options) +} + +// NewTypedServiceCIDRInformerWithOptions constructs a new informer for ServiceCIDR type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceCIDRInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ServiceCIDRIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "servicecidrs"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.ServiceCIDR](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewServiceCIDRInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *serviceCIDRInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *serviceCIDRInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1.ServiceCIDR{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *serviceCIDRInformer) TypedInformer() ServiceCIDRIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.ServiceCIDR](f.factory.InformerFor(&apinetworkingv1.ServiceCIDR{}, f.defaultInformer)) } func (f *serviceCIDRInformer) Lister() networkingv1.ServiceCIDRLister { return networkingv1.NewServiceCIDRLister(f.Informer().GetIndexer()) } + +// ToTypedServiceCIDRInformer converts an untyped informer into a TypedServiceCIDRInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceCIDR. If that is not the case, calling type-safe methods of the returned +// TypedServiceCIDRInformer leads to runtime panics. A safer alternative is to pass +// around a TypedServiceCIDRInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedServiceCIDRInformer(informer ServiceCIDRInformer) TypedServiceCIDRInformer { + if informer, ok := informer.(TypedServiceCIDRInformer); ok { + return informer + } + return &serviceCIDRTypedInformerAdapter{informer} +} + +type serviceCIDRTypedInformerAdapter struct { + ServiceCIDRInformer +} + +func (a *serviceCIDRTypedInformerAdapter) TypedInformer() ServiceCIDRIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.ServiceCIDR](a.Informer()) +} + +// ToServiceCIDRIndexInformer converts an untyped informer into a ServiceCIDRIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceCIDR. If that is not the case, calling type-safe methods of the returned +// ServiceCIDRIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ServiceCIDRIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToServiceCIDRIndexInformer(informer cache.SharedIndexInformer) ServiceCIDRIndexInformer { + if informer, ok := informer.(ServiceCIDRIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1.ServiceCIDR](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingress.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingress.go index ba35b8ac7..60ca6fb84 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingress.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingress.go @@ -34,12 +34,40 @@ import ( ) // IngressInformer provides access to a shared informer and lister for -// Ingresses. +// Ingresses. Prefer using the type-safe variant (see [TypedIngressInformer]). type IngressInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1beta1.IngressLister } +// TypedIngressInformer provides access to a shared informer and lister for +// Ingresses, including the type-safe TypedInformer variant. +// It is a superset of IngressInformer. +type TypedIngressInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IngressIndexInformer + Lister() networkingv1beta1.IngressLister +} + +// IngressIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IngressIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1beta1.Ingress] + +// IngressHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Ingress. +type IngressHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1beta1.Ingress] + +// IngressDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Ingress. +type IngressDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1beta1.Ingress] + +// IngressFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Ingress. +type IngressFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1beta1.Ingress] + +// IngressIndexers is a specialization of [cache.TypedIndexers] for Ingress. +type IngressIndexers = cache.TypedIndexers[*apinetworkingv1beta1.Ingress] + +// DeletedIngress is a specialization of [cache.DeletedObject] for Ingress. +type DeletedIngress = cache.DeletedObject[*apinetworkingv1beta1.Ingress] + type ingressInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type ingressInformer struct { // NewIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformer]). func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIngressInformer constructs a new informer for Ingress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIngressInformer]). func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIngressInformer constructs a new informer for Ingress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers IngressIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IngressIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIngressInformerWithOptions constructs a new informer for Ingress type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressInformerWithOptions]). func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIngressInformerWithOptions(client, namespace, options) +} + +// NewTypedIngressInformerWithOptions constructs a new informer for Ingress type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) IngressIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ingresss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.Ingress](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewIngressInformerWithOptions(client kubernetes.Interface, namespace string Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIngressInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *ingressInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1beta1.Ingress{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *ingressInformer) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.Ingress](f.factory.InformerFor(&apinetworkingv1beta1.Ingress{}, f.defaultInformer)) } func (f *ingressInformer) Lister() networkingv1beta1.IngressLister { return networkingv1beta1.NewIngressLister(f.Informer().GetIndexer()) } + +// ToTypedIngressInformer converts an untyped informer into a TypedIngressInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// TypedIngressInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIngressInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIngressInformer(informer IngressInformer) TypedIngressInformer { + if informer, ok := informer.(TypedIngressInformer); ok { + return informer + } + return &ingressTypedInformerAdapter{informer} +} + +type ingressTypedInformerAdapter struct { + IngressInformer +} + +func (a *ingressTypedInformerAdapter) TypedInformer() IngressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.Ingress](a.Informer()) +} + +// ToIngressIndexInformer converts an untyped informer into a IngressIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Ingress. If that is not the case, calling type-safe methods of the returned +// IngressIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IngressIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIngressIndexInformer(informer cache.SharedIndexInformer) IngressIndexInformer { + if informer, ok := informer.(IngressIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.Ingress](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go index 97d761a63..71ccdad0c 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go @@ -34,12 +34,40 @@ import ( ) // IngressClassInformer provides access to a shared informer and lister for -// IngressClasses. +// IngressClasses. Prefer using the type-safe variant (see [TypedIngressClassInformer]). type IngressClassInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1beta1.IngressClassLister } +// TypedIngressClassInformer provides access to a shared informer and lister for +// IngressClasses, including the type-safe TypedInformer variant. +// It is a superset of IngressClassInformer. +type TypedIngressClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IngressClassIndexInformer + Lister() networkingv1beta1.IngressClassLister +} + +// IngressClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IngressClassIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1beta1.IngressClass] + +// IngressClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for IngressClass. +type IngressClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1beta1.IngressClass] + +// IngressClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for IngressClass. +type IngressClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1beta1.IngressClass] + +// IngressClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for IngressClass. +type IngressClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1beta1.IngressClass] + +// IngressClassIndexers is a specialization of [cache.TypedIndexers] for IngressClass. +type IngressClassIndexers = cache.TypedIndexers[*apinetworkingv1beta1.IngressClass] + +// DeletedIngressClass is a specialization of [cache.DeletedObject] for IngressClass. +type DeletedIngressClass = cache.DeletedObject[*apinetworkingv1beta1.IngressClass] + type ingressClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type ingressClassInformer struct { // NewIngressClassInformer constructs a new informer for IngressClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressClassInformer]). func NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIngressClassInformer constructs a new informer for IngressClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IngressClassIndexers) IngressClassIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIngressClassInformer constructs a new informer for IngressClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIngressClassInformer]). func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIngressClassInformer constructs a new informer for IngressClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IngressClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IngressClassIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIngressClassInformerWithOptions constructs a new informer for IngressClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIngressClassInformerWithOptions]). func NewIngressClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIngressClassInformerWithOptions(client, options) +} + +// NewTypedIngressClassInformerWithOptions constructs a new informer for IngressClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIngressClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) IngressClassIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ingressclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IngressClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewIngressClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIngressClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *ingressClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1beta1.IngressClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *ingressClassInformer) TypedInformer() IngressClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IngressClass](f.factory.InformerFor(&apinetworkingv1beta1.IngressClass{}, f.defaultInformer)) } func (f *ingressClassInformer) Lister() networkingv1beta1.IngressClassLister { return networkingv1beta1.NewIngressClassLister(f.Informer().GetIndexer()) } + +// ToTypedIngressClassInformer converts an untyped informer into a TypedIngressClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IngressClass. If that is not the case, calling type-safe methods of the returned +// TypedIngressClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIngressClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIngressClassInformer(informer IngressClassInformer) TypedIngressClassInformer { + if informer, ok := informer.(TypedIngressClassInformer); ok { + return informer + } + return &ingressClassTypedInformerAdapter{informer} +} + +type ingressClassTypedInformerAdapter struct { + IngressClassInformer +} + +func (a *ingressClassTypedInformerAdapter) TypedInformer() IngressClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IngressClass](a.Informer()) +} + +// ToIngressClassIndexInformer converts an untyped informer into a IngressClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IngressClass. If that is not the case, calling type-safe methods of the returned +// IngressClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IngressClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIngressClassIndexInformer(informer cache.SharedIndexInformer) IngressClassIndexInformer { + if informer, ok := informer.(IngressClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IngressClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/interface.go index 974a8fd5b..f6489bd5d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // IPAddresses returns a IPAddressInformer. - IPAddresses() IPAddressInformer + IPAddresses() TypedIPAddressInformer // Ingresses returns a IngressInformer. - Ingresses() IngressInformer + Ingresses() TypedIngressInformer // IngressClasses returns a IngressClassInformer. - IngressClasses() IngressClassInformer + IngressClasses() TypedIngressClassInformer // ServiceCIDRs returns a ServiceCIDRInformer. - ServiceCIDRs() ServiceCIDRInformer + ServiceCIDRs() TypedServiceCIDRInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// IPAddresses returns a IPAddressInformer. -func (v *version) IPAddresses() IPAddressInformer { +// IPAddresses returns a TypedIPAddressInformer. +func (v *version) IPAddresses() TypedIPAddressInformer { return &iPAddressInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Ingresses returns a IngressInformer. -func (v *version) Ingresses() IngressInformer { +// Ingresses returns a TypedIngressInformer. +func (v *version) Ingresses() TypedIngressInformer { return &ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// IngressClasses returns a IngressClassInformer. -func (v *version) IngressClasses() IngressClassInformer { +// IngressClasses returns a TypedIngressClassInformer. +func (v *version) IngressClasses() TypedIngressClassInformer { return &ingressClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ServiceCIDRs returns a ServiceCIDRInformer. -func (v *version) ServiceCIDRs() ServiceCIDRInformer { +// ServiceCIDRs returns a TypedServiceCIDRInformer. +func (v *version) ServiceCIDRs() TypedServiceCIDRInformer { return &serviceCIDRInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ipaddress.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ipaddress.go index fd9439239..b63d156d7 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ipaddress.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/ipaddress.go @@ -34,12 +34,40 @@ import ( ) // IPAddressInformer provides access to a shared informer and lister for -// IPAddresses. +// IPAddresses. Prefer using the type-safe variant (see [TypedIPAddressInformer]). type IPAddressInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1beta1.IPAddressLister } +// TypedIPAddressInformer provides access to a shared informer and lister for +// IPAddresses, including the type-safe TypedInformer variant. +// It is a superset of IPAddressInformer. +type TypedIPAddressInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() IPAddressIndexInformer + Lister() networkingv1beta1.IPAddressLister +} + +// IPAddressIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type IPAddressIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1beta1.IPAddress] + +// IPAddressHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for IPAddress. +type IPAddressHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1beta1.IPAddress] + +// IPAddressDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for IPAddress. +type IPAddressDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1beta1.IPAddress] + +// IPAddressFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for IPAddress. +type IPAddressFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1beta1.IPAddress] + +// IPAddressIndexers is a specialization of [cache.TypedIndexers] for IPAddress. +type IPAddressIndexers = cache.TypedIndexers[*apinetworkingv1beta1.IPAddress] + +// DeletedIPAddress is a specialization of [cache.DeletedObject] for IPAddress. +type DeletedIPAddress = cache.DeletedObject[*apinetworkingv1beta1.IPAddress] + type iPAddressInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type iPAddressInformer struct { // NewIPAddressInformer constructs a new informer for IPAddress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIPAddressInformer]). func NewIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IPAddressIndexers) IPAddressIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredIPAddressInformer constructs a new informer for IPAddress type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredIPAddressInformer]). func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredIPAddressInformer constructs a new informer for IPAddress type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers IPAddressIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) IPAddressIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewIPAddressInformerWithOptions constructs a new informer for IPAddress type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedIPAddressInformerWithOptions]). func NewIPAddressInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedIPAddressInformerWithOptions(client, options) +} + +// NewTypedIPAddressInformerWithOptions constructs a new informer for IPAddress type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedIPAddressInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) IPAddressIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ipaddresss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IPAddress](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewIPAddressInformerWithOptions(client kubernetes.Interface, options intern Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *iPAddressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedIPAddressInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *iPAddressInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1beta1.IPAddress{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *iPAddressInformer) TypedInformer() IPAddressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IPAddress](f.factory.InformerFor(&apinetworkingv1beta1.IPAddress{}, f.defaultInformer)) } func (f *iPAddressInformer) Lister() networkingv1beta1.IPAddressLister { return networkingv1beta1.NewIPAddressLister(f.Informer().GetIndexer()) } + +// ToTypedIPAddressInformer converts an untyped informer into a TypedIPAddressInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IPAddress. If that is not the case, calling type-safe methods of the returned +// TypedIPAddressInformer leads to runtime panics. A safer alternative is to pass +// around a TypedIPAddressInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedIPAddressInformer(informer IPAddressInformer) TypedIPAddressInformer { + if informer, ok := informer.(TypedIPAddressInformer); ok { + return informer + } + return &iPAddressTypedInformerAdapter{informer} +} + +type iPAddressTypedInformerAdapter struct { + IPAddressInformer +} + +func (a *iPAddressTypedInformerAdapter) TypedInformer() IPAddressIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IPAddress](a.Informer()) +} + +// ToIPAddressIndexInformer converts an untyped informer into a IPAddressIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *IPAddress. If that is not the case, calling type-safe methods of the returned +// IPAddressIndexInformer leads to runtime panics. A safer alternative is to pass +// around a IPAddressIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToIPAddressIndexInformer(informer cache.SharedIndexInformer) IPAddressIndexInformer { + if informer, ok := informer.(IPAddressIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.IPAddress](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/servicecidr.go b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/servicecidr.go index 6fe8c3bd1..538ef3132 100644 --- a/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/servicecidr.go +++ b/constraint/vendor/k8s.io/client-go/informers/networking/v1beta1/servicecidr.go @@ -34,12 +34,40 @@ import ( ) // ServiceCIDRInformer provides access to a shared informer and lister for -// ServiceCIDRs. +// ServiceCIDRs. Prefer using the type-safe variant (see [TypedServiceCIDRInformer]). type ServiceCIDRInformer interface { Informer() cache.SharedIndexInformer Lister() networkingv1beta1.ServiceCIDRLister } +// TypedServiceCIDRInformer provides access to a shared informer and lister for +// ServiceCIDRs, including the type-safe TypedInformer variant. +// It is a superset of ServiceCIDRInformer. +type TypedServiceCIDRInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ServiceCIDRIndexInformer + Lister() networkingv1beta1.ServiceCIDRLister +} + +// ServiceCIDRIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ServiceCIDRIndexInformer cache.TypedSharedIndexInformer[*apinetworkingv1beta1.ServiceCIDR] + +// ServiceCIDRHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ServiceCIDR. +type ServiceCIDRHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinetworkingv1beta1.ServiceCIDR] + +// ServiceCIDRDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ServiceCIDR. +type ServiceCIDRDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinetworkingv1beta1.ServiceCIDR] + +// ServiceCIDRFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ServiceCIDR. +type ServiceCIDRFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinetworkingv1beta1.ServiceCIDR] + +// ServiceCIDRIndexers is a specialization of [cache.TypedIndexers] for ServiceCIDR. +type ServiceCIDRIndexers = cache.TypedIndexers[*apinetworkingv1beta1.ServiceCIDR] + +// DeletedServiceCIDR is a specialization of [cache.DeletedObject] for ServiceCIDR. +type DeletedServiceCIDR = cache.DeletedObject[*apinetworkingv1beta1.ServiceCIDR] + type serviceCIDRInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type serviceCIDRInformer struct { // NewServiceCIDRInformer constructs a new informer for ServiceCIDR type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceCIDRInformer]). func NewServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ServiceCIDRIndexers) ServiceCIDRIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredServiceCIDRInformer constructs a new informer for ServiceCIDR type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredServiceCIDRInformer]). func NewFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredServiceCIDRInformer constructs a new informer for ServiceCIDR type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredServiceCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ServiceCIDRIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ServiceCIDRIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewServiceCIDRInformerWithOptions constructs a new informer for ServiceCIDR type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedServiceCIDRInformerWithOptions]). func NewServiceCIDRInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedServiceCIDRInformerWithOptions(client, options) +} + +// NewTypedServiceCIDRInformerWithOptions constructs a new informer for ServiceCIDR type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedServiceCIDRInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ServiceCIDRIndexInformer { gvr := schema.GroupVersionResource{Group: "networking.k8s.io", Version: "v1beta1", Resource: "servicecidrs"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.ServiceCIDR](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewServiceCIDRInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *serviceCIDRInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedServiceCIDRInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *serviceCIDRInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinetworkingv1beta1.ServiceCIDR{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *serviceCIDRInformer) TypedInformer() ServiceCIDRIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.ServiceCIDR](f.factory.InformerFor(&apinetworkingv1beta1.ServiceCIDR{}, f.defaultInformer)) } func (f *serviceCIDRInformer) Lister() networkingv1beta1.ServiceCIDRLister { return networkingv1beta1.NewServiceCIDRLister(f.Informer().GetIndexer()) } + +// ToTypedServiceCIDRInformer converts an untyped informer into a TypedServiceCIDRInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceCIDR. If that is not the case, calling type-safe methods of the returned +// TypedServiceCIDRInformer leads to runtime panics. A safer alternative is to pass +// around a TypedServiceCIDRInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedServiceCIDRInformer(informer ServiceCIDRInformer) TypedServiceCIDRInformer { + if informer, ok := informer.(TypedServiceCIDRInformer); ok { + return informer + } + return &serviceCIDRTypedInformerAdapter{informer} +} + +type serviceCIDRTypedInformerAdapter struct { + ServiceCIDRInformer +} + +func (a *serviceCIDRTypedInformerAdapter) TypedInformer() ServiceCIDRIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.ServiceCIDR](a.Informer()) +} + +// ToServiceCIDRIndexInformer converts an untyped informer into a ServiceCIDRIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ServiceCIDR. If that is not the case, calling type-safe methods of the returned +// ServiceCIDRIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ServiceCIDRIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToServiceCIDRIndexInformer(informer cache.SharedIndexInformer) ServiceCIDRIndexInformer { + if informer, ok := informer.(ServiceCIDRIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinetworkingv1beta1.ServiceCIDR](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/node/v1/interface.go index 913fec4ac..53a4abd92 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // RuntimeClasses returns a RuntimeClassInformer. - RuntimeClasses() RuntimeClassInformer + RuntimeClasses() TypedRuntimeClassInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// RuntimeClasses returns a RuntimeClassInformer. -func (v *version) RuntimeClasses() RuntimeClassInformer { +// RuntimeClasses returns a TypedRuntimeClassInformer. +func (v *version) RuntimeClasses() TypedRuntimeClassInformer { return &runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/informers/node/v1/runtimeclass.go index 3b7d4a25d..4fe406546 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1/runtimeclass.go @@ -34,12 +34,40 @@ import ( ) // RuntimeClassInformer provides access to a shared informer and lister for -// RuntimeClasses. +// RuntimeClasses. Prefer using the type-safe variant (see [TypedRuntimeClassInformer]). type RuntimeClassInformer interface { Informer() cache.SharedIndexInformer Lister() nodev1.RuntimeClassLister } +// TypedRuntimeClassInformer provides access to a shared informer and lister for +// RuntimeClasses, including the type-safe TypedInformer variant. +// It is a superset of RuntimeClassInformer. +type TypedRuntimeClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RuntimeClassIndexInformer + Lister() nodev1.RuntimeClassLister +} + +// RuntimeClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RuntimeClassIndexInformer cache.TypedSharedIndexInformer[*apinodev1.RuntimeClass] + +// RuntimeClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RuntimeClass. +type RuntimeClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinodev1.RuntimeClass] + +// RuntimeClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RuntimeClass. +type RuntimeClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinodev1.RuntimeClass] + +// RuntimeClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RuntimeClass. +type RuntimeClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinodev1.RuntimeClass] + +// RuntimeClassIndexers is a specialization of [cache.TypedIndexers] for RuntimeClass. +type RuntimeClassIndexers = cache.TypedIndexers[*apinodev1.RuntimeClass] + +// DeletedRuntimeClass is a specialization of [cache.DeletedObject] for RuntimeClass. +type DeletedRuntimeClass = cache.DeletedObject[*apinodev1.RuntimeClass] + type runtimeClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type runtimeClassInformer struct { // NewRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformer]). func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRuntimeClassInformer]). func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformerWithOptions]). func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, options) +} + +// NewTypedRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) RuntimeClassIndexInformer { gvr := schema.GroupVersionResource{Group: "node.k8s.io", Version: "v1", Resource: "runtimeclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinodev1.RuntimeClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinodev1.RuntimeClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *runtimeClassInformer) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1.RuntimeClass](f.factory.InformerFor(&apinodev1.RuntimeClass{}, f.defaultInformer)) } func (f *runtimeClassInformer) Lister() nodev1.RuntimeClassLister { return nodev1.NewRuntimeClassLister(f.Informer().GetIndexer()) } + +// ToTypedRuntimeClassInformer converts an untyped informer into a TypedRuntimeClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// TypedRuntimeClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRuntimeClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRuntimeClassInformer(informer RuntimeClassInformer) TypedRuntimeClassInformer { + if informer, ok := informer.(TypedRuntimeClassInformer); ok { + return informer + } + return &runtimeClassTypedInformerAdapter{informer} +} + +type runtimeClassTypedInformerAdapter struct { + RuntimeClassInformer +} + +func (a *runtimeClassTypedInformerAdapter) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1.RuntimeClass](a.Informer()) +} + +// ToRuntimeClassIndexInformer converts an untyped informer into a RuntimeClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// RuntimeClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RuntimeClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRuntimeClassIndexInformer(informer cache.SharedIndexInformer) RuntimeClassIndexInformer { + if informer, ok := informer.(RuntimeClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinodev1.RuntimeClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/interface.go index c56442957..402674241 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // RuntimeClasses returns a RuntimeClassInformer. - RuntimeClasses() RuntimeClassInformer + RuntimeClasses() TypedRuntimeClassInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// RuntimeClasses returns a RuntimeClassInformer. -func (v *version) RuntimeClasses() RuntimeClassInformer { +// RuntimeClasses returns a TypedRuntimeClassInformer. +func (v *version) RuntimeClasses() TypedRuntimeClassInformer { return &runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go index 1907a122d..d264133fe 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go @@ -34,12 +34,40 @@ import ( ) // RuntimeClassInformer provides access to a shared informer and lister for -// RuntimeClasses. +// RuntimeClasses. Prefer using the type-safe variant (see [TypedRuntimeClassInformer]). type RuntimeClassInformer interface { Informer() cache.SharedIndexInformer Lister() nodev1alpha1.RuntimeClassLister } +// TypedRuntimeClassInformer provides access to a shared informer and lister for +// RuntimeClasses, including the type-safe TypedInformer variant. +// It is a superset of RuntimeClassInformer. +type TypedRuntimeClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RuntimeClassIndexInformer + Lister() nodev1alpha1.RuntimeClassLister +} + +// RuntimeClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RuntimeClassIndexInformer cache.TypedSharedIndexInformer[*apinodev1alpha1.RuntimeClass] + +// RuntimeClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RuntimeClass. +type RuntimeClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinodev1alpha1.RuntimeClass] + +// RuntimeClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RuntimeClass. +type RuntimeClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinodev1alpha1.RuntimeClass] + +// RuntimeClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RuntimeClass. +type RuntimeClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinodev1alpha1.RuntimeClass] + +// RuntimeClassIndexers is a specialization of [cache.TypedIndexers] for RuntimeClass. +type RuntimeClassIndexers = cache.TypedIndexers[*apinodev1alpha1.RuntimeClass] + +// DeletedRuntimeClass is a specialization of [cache.DeletedObject] for RuntimeClass. +type DeletedRuntimeClass = cache.DeletedObject[*apinodev1alpha1.RuntimeClass] + type runtimeClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type runtimeClassInformer struct { // NewRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformer]). func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRuntimeClassInformer]). func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformerWithOptions]). func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, options) +} + +// NewTypedRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) RuntimeClassIndexInformer { gvr := schema.GroupVersionResource{Group: "node.k8s.io", Version: "v1alpha1", Resource: "runtimeclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinodev1alpha1.RuntimeClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinodev1alpha1.RuntimeClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *runtimeClassInformer) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1alpha1.RuntimeClass](f.factory.InformerFor(&apinodev1alpha1.RuntimeClass{}, f.defaultInformer)) } func (f *runtimeClassInformer) Lister() nodev1alpha1.RuntimeClassLister { return nodev1alpha1.NewRuntimeClassLister(f.Informer().GetIndexer()) } + +// ToTypedRuntimeClassInformer converts an untyped informer into a TypedRuntimeClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// TypedRuntimeClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRuntimeClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRuntimeClassInformer(informer RuntimeClassInformer) TypedRuntimeClassInformer { + if informer, ok := informer.(TypedRuntimeClassInformer); ok { + return informer + } + return &runtimeClassTypedInformerAdapter{informer} +} + +type runtimeClassTypedInformerAdapter struct { + RuntimeClassInformer +} + +func (a *runtimeClassTypedInformerAdapter) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1alpha1.RuntimeClass](a.Informer()) +} + +// ToRuntimeClassIndexInformer converts an untyped informer into a RuntimeClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// RuntimeClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RuntimeClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRuntimeClassIndexInformer(informer cache.SharedIndexInformer) RuntimeClassIndexInformer { + if informer, ok := informer.(RuntimeClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinodev1alpha1.RuntimeClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/interface.go index 44a1defb6..6e81a66e4 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // RuntimeClasses returns a RuntimeClassInformer. - RuntimeClasses() RuntimeClassInformer + RuntimeClasses() TypedRuntimeClassInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// RuntimeClasses returns a RuntimeClassInformer. -func (v *version) RuntimeClasses() RuntimeClassInformer { +// RuntimeClasses returns a TypedRuntimeClassInformer. +func (v *version) RuntimeClasses() TypedRuntimeClassInformer { return &runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go b/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go index ca7e9307a..58d602da2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go @@ -34,12 +34,40 @@ import ( ) // RuntimeClassInformer provides access to a shared informer and lister for -// RuntimeClasses. +// RuntimeClasses. Prefer using the type-safe variant (see [TypedRuntimeClassInformer]). type RuntimeClassInformer interface { Informer() cache.SharedIndexInformer Lister() nodev1beta1.RuntimeClassLister } +// TypedRuntimeClassInformer provides access to a shared informer and lister for +// RuntimeClasses, including the type-safe TypedInformer variant. +// It is a superset of RuntimeClassInformer. +type TypedRuntimeClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RuntimeClassIndexInformer + Lister() nodev1beta1.RuntimeClassLister +} + +// RuntimeClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RuntimeClassIndexInformer cache.TypedSharedIndexInformer[*apinodev1beta1.RuntimeClass] + +// RuntimeClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RuntimeClass. +type RuntimeClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apinodev1beta1.RuntimeClass] + +// RuntimeClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RuntimeClass. +type RuntimeClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apinodev1beta1.RuntimeClass] + +// RuntimeClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RuntimeClass. +type RuntimeClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apinodev1beta1.RuntimeClass] + +// RuntimeClassIndexers is a specialization of [cache.TypedIndexers] for RuntimeClass. +type RuntimeClassIndexers = cache.TypedIndexers[*apinodev1beta1.RuntimeClass] + +// DeletedRuntimeClass is a specialization of [cache.DeletedObject] for RuntimeClass. +type DeletedRuntimeClass = cache.DeletedObject[*apinodev1beta1.RuntimeClass] + type runtimeClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type runtimeClassInformer struct { // NewRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformer]). func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRuntimeClassInformer]). func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers RuntimeClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RuntimeClassIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRuntimeClassInformerWithOptions]). func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRuntimeClassInformerWithOptions(client, options) +} + +// NewTypedRuntimeClassInformerWithOptions constructs a new informer for RuntimeClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRuntimeClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) RuntimeClassIndexInformer { gvr := schema.GroupVersionResource{Group: "node.k8s.io", Version: "v1beta1", Resource: "runtimeclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apinodev1beta1.RuntimeClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewRuntimeClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRuntimeClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apinodev1beta1.RuntimeClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *runtimeClassInformer) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1beta1.RuntimeClass](f.factory.InformerFor(&apinodev1beta1.RuntimeClass{}, f.defaultInformer)) } func (f *runtimeClassInformer) Lister() nodev1beta1.RuntimeClassLister { return nodev1beta1.NewRuntimeClassLister(f.Informer().GetIndexer()) } + +// ToTypedRuntimeClassInformer converts an untyped informer into a TypedRuntimeClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// TypedRuntimeClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRuntimeClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRuntimeClassInformer(informer RuntimeClassInformer) TypedRuntimeClassInformer { + if informer, ok := informer.(TypedRuntimeClassInformer); ok { + return informer + } + return &runtimeClassTypedInformerAdapter{informer} +} + +type runtimeClassTypedInformerAdapter struct { + RuntimeClassInformer +} + +func (a *runtimeClassTypedInformerAdapter) TypedInformer() RuntimeClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apinodev1beta1.RuntimeClass](a.Informer()) +} + +// ToRuntimeClassIndexInformer converts an untyped informer into a RuntimeClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RuntimeClass. If that is not the case, calling type-safe methods of the returned +// RuntimeClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RuntimeClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRuntimeClassIndexInformer(informer cache.SharedIndexInformer) RuntimeClassIndexInformer { + if informer, ok := informer.(RuntimeClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apinodev1beta1.RuntimeClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/policy/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/policy/v1/interface.go index 2c42e1993..2035254dc 100644 --- a/constraint/vendor/k8s.io/client-go/informers/policy/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/policy/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // PodDisruptionBudgets returns a PodDisruptionBudgetInformer. - PodDisruptionBudgets() PodDisruptionBudgetInformer + PodDisruptionBudgets() TypedPodDisruptionBudgetInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// PodDisruptionBudgets returns a PodDisruptionBudgetInformer. -func (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer { +// PodDisruptionBudgets returns a TypedPodDisruptionBudgetInformer. +func (v *version) PodDisruptionBudgets() TypedPodDisruptionBudgetInformer { return &podDisruptionBudgetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go b/constraint/vendor/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go index 2945e543d..24ed2870d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go +++ b/constraint/vendor/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go @@ -34,12 +34,40 @@ import ( ) // PodDisruptionBudgetInformer provides access to a shared informer and lister for -// PodDisruptionBudgets. +// PodDisruptionBudgets. Prefer using the type-safe variant (see [TypedPodDisruptionBudgetInformer]). type PodDisruptionBudgetInformer interface { Informer() cache.SharedIndexInformer Lister() policyv1.PodDisruptionBudgetLister } +// TypedPodDisruptionBudgetInformer provides access to a shared informer and lister for +// PodDisruptionBudgets, including the type-safe TypedInformer variant. +// It is a superset of PodDisruptionBudgetInformer. +type TypedPodDisruptionBudgetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodDisruptionBudgetIndexInformer + Lister() policyv1.PodDisruptionBudgetLister +} + +// PodDisruptionBudgetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodDisruptionBudgetIndexInformer cache.TypedSharedIndexInformer[*apipolicyv1.PodDisruptionBudget] + +// PodDisruptionBudgetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodDisruptionBudget. +type PodDisruptionBudgetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apipolicyv1.PodDisruptionBudget] + +// PodDisruptionBudgetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodDisruptionBudget. +type PodDisruptionBudgetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apipolicyv1.PodDisruptionBudget] + +// PodDisruptionBudgetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodDisruptionBudget. +type PodDisruptionBudgetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apipolicyv1.PodDisruptionBudget] + +// PodDisruptionBudgetIndexers is a specialization of [cache.TypedIndexers] for PodDisruptionBudget. +type PodDisruptionBudgetIndexers = cache.TypedIndexers[*apipolicyv1.PodDisruptionBudget] + +// DeletedPodDisruptionBudget is a specialization of [cache.DeletedObject] for PodDisruptionBudget. +type DeletedPodDisruptionBudget = cache.DeletedObject[*apipolicyv1.PodDisruptionBudget] + type podDisruptionBudgetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type podDisruptionBudgetInformer struct { // NewPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodDisruptionBudgetInformer]). func NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodDisruptionBudgetIndexers) PodDisruptionBudgetIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodDisruptionBudgetInformer]). func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodDisruptionBudgetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodDisruptionBudgetIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPodDisruptionBudgetInformerWithOptions constructs a new informer for PodDisruptionBudget type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodDisruptionBudgetInformerWithOptions]). func NewPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, options) +} + +// NewTypedPodDisruptionBudgetInformerWithOptions constructs a new informer for PodDisruptionBudget type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodDisruptionBudgetIndexInformer { gvr := schema.GroupVersionResource{Group: "policy", Version: "v1", Resource: "poddisruptionbudgets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apipolicyv1.PodDisruptionBudget](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, name Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodDisruptionBudgetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPodDisruptionBudgetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apipolicyv1.PodDisruptionBudget{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *podDisruptionBudgetInformer) TypedInformer() PodDisruptionBudgetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apipolicyv1.PodDisruptionBudget](f.factory.InformerFor(&apipolicyv1.PodDisruptionBudget{}, f.defaultInformer)) } func (f *podDisruptionBudgetInformer) Lister() policyv1.PodDisruptionBudgetLister { return policyv1.NewPodDisruptionBudgetLister(f.Informer().GetIndexer()) } + +// ToTypedPodDisruptionBudgetInformer converts an untyped informer into a TypedPodDisruptionBudgetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodDisruptionBudget. If that is not the case, calling type-safe methods of the returned +// TypedPodDisruptionBudgetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodDisruptionBudgetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodDisruptionBudgetInformer(informer PodDisruptionBudgetInformer) TypedPodDisruptionBudgetInformer { + if informer, ok := informer.(TypedPodDisruptionBudgetInformer); ok { + return informer + } + return &podDisruptionBudgetTypedInformerAdapter{informer} +} + +type podDisruptionBudgetTypedInformerAdapter struct { + PodDisruptionBudgetInformer +} + +func (a *podDisruptionBudgetTypedInformerAdapter) TypedInformer() PodDisruptionBudgetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apipolicyv1.PodDisruptionBudget](a.Informer()) +} + +// ToPodDisruptionBudgetIndexInformer converts an untyped informer into a PodDisruptionBudgetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodDisruptionBudget. If that is not the case, calling type-safe methods of the returned +// PodDisruptionBudgetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodDisruptionBudgetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodDisruptionBudgetIndexInformer(informer cache.SharedIndexInformer) PodDisruptionBudgetIndexInformer { + if informer, ok := informer.(PodDisruptionBudgetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apipolicyv1.PodDisruptionBudget](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/interface.go index 055c8adc5..31c09bc17 100644 --- a/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // PodDisruptionBudgets returns a PodDisruptionBudgetInformer. - PodDisruptionBudgets() PodDisruptionBudgetInformer + PodDisruptionBudgets() TypedPodDisruptionBudgetInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// PodDisruptionBudgets returns a PodDisruptionBudgetInformer. -func (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer { +// PodDisruptionBudgets returns a TypedPodDisruptionBudgetInformer. +func (v *version) PodDisruptionBudgets() TypedPodDisruptionBudgetInformer { return &podDisruptionBudgetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go b/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go index 70c79683f..8069aad31 100644 --- a/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go +++ b/constraint/vendor/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go @@ -34,12 +34,40 @@ import ( ) // PodDisruptionBudgetInformer provides access to a shared informer and lister for -// PodDisruptionBudgets. +// PodDisruptionBudgets. Prefer using the type-safe variant (see [TypedPodDisruptionBudgetInformer]). type PodDisruptionBudgetInformer interface { Informer() cache.SharedIndexInformer Lister() policyv1beta1.PodDisruptionBudgetLister } +// TypedPodDisruptionBudgetInformer provides access to a shared informer and lister for +// PodDisruptionBudgets, including the type-safe TypedInformer variant. +// It is a superset of PodDisruptionBudgetInformer. +type TypedPodDisruptionBudgetInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodDisruptionBudgetIndexInformer + Lister() policyv1beta1.PodDisruptionBudgetLister +} + +// PodDisruptionBudgetIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodDisruptionBudgetIndexInformer cache.TypedSharedIndexInformer[*apipolicyv1beta1.PodDisruptionBudget] + +// PodDisruptionBudgetHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodDisruptionBudget. +type PodDisruptionBudgetHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apipolicyv1beta1.PodDisruptionBudget] + +// PodDisruptionBudgetDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodDisruptionBudget. +type PodDisruptionBudgetDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apipolicyv1beta1.PodDisruptionBudget] + +// PodDisruptionBudgetFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodDisruptionBudget. +type PodDisruptionBudgetFilteringHandler = cache.TypedFilteringResourceEventHandler[*apipolicyv1beta1.PodDisruptionBudget] + +// PodDisruptionBudgetIndexers is a specialization of [cache.TypedIndexers] for PodDisruptionBudget. +type PodDisruptionBudgetIndexers = cache.TypedIndexers[*apipolicyv1beta1.PodDisruptionBudget] + +// DeletedPodDisruptionBudget is a specialization of [cache.DeletedObject] for PodDisruptionBudget. +type DeletedPodDisruptionBudget = cache.DeletedObject[*apipolicyv1beta1.PodDisruptionBudget] + type podDisruptionBudgetInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type podDisruptionBudgetInformer struct { // NewPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodDisruptionBudgetInformer]). func NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodDisruptionBudgetIndexers) PodDisruptionBudgetIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodDisruptionBudgetInformer]). func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodDisruptionBudgetIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodDisruptionBudgetIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPodDisruptionBudgetInformerWithOptions constructs a new informer for PodDisruptionBudget type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodDisruptionBudgetInformerWithOptions]). func NewPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodDisruptionBudgetInformerWithOptions(client, namespace, options) +} + +// NewTypedPodDisruptionBudgetInformerWithOptions constructs a new informer for PodDisruptionBudget type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodDisruptionBudgetIndexInformer { gvr := schema.GroupVersionResource{Group: "policy", Version: "v1beta1", Resource: "poddisruptionbudgets"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apipolicyv1beta1.PodDisruptionBudget](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewPodDisruptionBudgetInformerWithOptions(client kubernetes.Interface, name Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodDisruptionBudgetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPodDisruptionBudgetInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apipolicyv1beta1.PodDisruptionBudget{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *podDisruptionBudgetInformer) TypedInformer() PodDisruptionBudgetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apipolicyv1beta1.PodDisruptionBudget](f.factory.InformerFor(&apipolicyv1beta1.PodDisruptionBudget{}, f.defaultInformer)) } func (f *podDisruptionBudgetInformer) Lister() policyv1beta1.PodDisruptionBudgetLister { return policyv1beta1.NewPodDisruptionBudgetLister(f.Informer().GetIndexer()) } + +// ToTypedPodDisruptionBudgetInformer converts an untyped informer into a TypedPodDisruptionBudgetInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodDisruptionBudget. If that is not the case, calling type-safe methods of the returned +// TypedPodDisruptionBudgetInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodDisruptionBudgetInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodDisruptionBudgetInformer(informer PodDisruptionBudgetInformer) TypedPodDisruptionBudgetInformer { + if informer, ok := informer.(TypedPodDisruptionBudgetInformer); ok { + return informer + } + return &podDisruptionBudgetTypedInformerAdapter{informer} +} + +type podDisruptionBudgetTypedInformerAdapter struct { + PodDisruptionBudgetInformer +} + +func (a *podDisruptionBudgetTypedInformerAdapter) TypedInformer() PodDisruptionBudgetIndexInformer { + return cache.NewTypedSharedIndexInformer[*apipolicyv1beta1.PodDisruptionBudget](a.Informer()) +} + +// ToPodDisruptionBudgetIndexInformer converts an untyped informer into a PodDisruptionBudgetIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodDisruptionBudget. If that is not the case, calling type-safe methods of the returned +// PodDisruptionBudgetIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodDisruptionBudgetIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodDisruptionBudgetIndexInformer(informer cache.SharedIndexInformer) PodDisruptionBudgetIndexInformer { + if informer, ok := informer.(PodDisruptionBudgetIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apipolicyv1beta1.PodDisruptionBudget](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrole.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrole.go index d938be79e..3c0bc9e12 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrole.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleInformer provides access to a shared informer and lister for -// ClusterRoles. +// ClusterRoles. Prefer using the type-safe variant (see [TypedClusterRoleInformer]). type ClusterRoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1.ClusterRoleLister } +// TypedClusterRoleInformer provides access to a shared informer and lister for +// ClusterRoles, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleInformer. +type TypedClusterRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleIndexInformer + Lister() rbacv1.ClusterRoleLister +} + +// ClusterRoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1.ClusterRole] + +// ClusterRoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRole. +type ClusterRoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1.ClusterRole] + +// ClusterRoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRole. +type ClusterRoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1.ClusterRole] + +// ClusterRoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRole. +type ClusterRoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1.ClusterRole] + +// ClusterRoleIndexers is a specialization of [cache.TypedIndexers] for ClusterRole. +type ClusterRoleIndexers = cache.TypedIndexers[*apirbacv1.ClusterRole] + +// DeletedClusterRole is a specialization of [cache.DeletedObject] for ClusterRole. +type DeletedClusterRole = cache.DeletedObject[*apirbacv1.ClusterRole] + type clusterRoleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleInformer struct { // NewClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformer]). func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleInformer]). func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformerWithOptions]). func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, options) +} + +// NewTypedClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "clusterroles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRole](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1.ClusterRole{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleInformer) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRole](f.factory.InformerFor(&apirbacv1.ClusterRole{}, f.defaultInformer)) } func (f *clusterRoleInformer) Lister() rbacv1.ClusterRoleLister { return rbacv1.NewClusterRoleLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleInformer converts an untyped informer into a TypedClusterRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleInformer(informer ClusterRoleInformer) TypedClusterRoleInformer { + if informer, ok := informer.(TypedClusterRoleInformer); ok { + return informer + } + return &clusterRoleTypedInformerAdapter{informer} +} + +type clusterRoleTypedInformerAdapter struct { + ClusterRoleInformer +} + +func (a *clusterRoleTypedInformerAdapter) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRole](a.Informer()) +} + +// ToClusterRoleIndexInformer converts an untyped informer into a ClusterRoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// ClusterRoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleIndexInformer(informer cache.SharedIndexInformer) ClusterRoleIndexInformer { + if informer, ok := informer.(ClusterRoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRole](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go index 72fe655da..34dde5197 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleBindingInformer provides access to a shared informer and lister for -// ClusterRoleBindings. +// ClusterRoleBindings. Prefer using the type-safe variant (see [TypedClusterRoleBindingInformer]). type ClusterRoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1.ClusterRoleBindingLister } +// TypedClusterRoleBindingInformer provides access to a shared informer and lister for +// ClusterRoleBindings, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleBindingInformer. +type TypedClusterRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleBindingIndexInformer + Lister() rbacv1.ClusterRoleBindingLister +} + +// ClusterRoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1.ClusterRoleBinding] + +// ClusterRoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRoleBinding. +type ClusterRoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1.ClusterRoleBinding] + +// ClusterRoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRoleBinding. +type ClusterRoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1.ClusterRoleBinding] + +// ClusterRoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRoleBinding. +type ClusterRoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1.ClusterRoleBinding] + +// ClusterRoleBindingIndexers is a specialization of [cache.TypedIndexers] for ClusterRoleBinding. +type ClusterRoleBindingIndexers = cache.TypedIndexers[*apirbacv1.ClusterRoleBinding] + +// DeletedClusterRoleBinding is a specialization of [cache.DeletedObject] for ClusterRoleBinding. +type DeletedClusterRoleBinding = cache.DeletedObject[*apirbacv1.ClusterRoleBinding] + type clusterRoleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleBindingInformer struct { // NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformer]). func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleBindingInformer]). func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformerWithOptions]). func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, options) +} + +// NewTypedClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "clusterrolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, optio Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1.ClusterRoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleBindingInformer) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRoleBinding](f.factory.InformerFor(&apirbacv1.ClusterRoleBinding{}, f.defaultInformer)) } func (f *clusterRoleBindingInformer) Lister() rbacv1.ClusterRoleBindingLister { return rbacv1.NewClusterRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleBindingInformer converts an untyped informer into a TypedClusterRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleBindingInformer(informer ClusterRoleBindingInformer) TypedClusterRoleBindingInformer { + if informer, ok := informer.(TypedClusterRoleBindingInformer); ok { + return informer + } + return &clusterRoleBindingTypedInformerAdapter{informer} +} + +type clusterRoleBindingTypedInformerAdapter struct { + ClusterRoleBindingInformer +} + +func (a *clusterRoleBindingTypedInformerAdapter) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRoleBinding](a.Informer()) +} + +// ToClusterRoleBindingIndexInformer converts an untyped informer into a ClusterRoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// ClusterRoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleBindingIndexInformer(informer cache.SharedIndexInformer) ClusterRoleBindingIndexInformer { + if informer, ok := informer.(ClusterRoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1.ClusterRoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/interface.go index 7f99c9454..829564c28 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ClusterRoles returns a ClusterRoleInformer. - ClusterRoles() ClusterRoleInformer + ClusterRoles() TypedClusterRoleInformer // ClusterRoleBindings returns a ClusterRoleBindingInformer. - ClusterRoleBindings() ClusterRoleBindingInformer + ClusterRoleBindings() TypedClusterRoleBindingInformer // Roles returns a RoleInformer. - Roles() RoleInformer + Roles() TypedRoleInformer // RoleBindings returns a RoleBindingInformer. - RoleBindings() RoleBindingInformer + RoleBindings() TypedRoleBindingInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterRoles returns a ClusterRoleInformer. -func (v *version) ClusterRoles() ClusterRoleInformer { +// ClusterRoles returns a TypedClusterRoleInformer. +func (v *version) ClusterRoles() TypedClusterRoleInformer { return &clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ClusterRoleBindings returns a ClusterRoleBindingInformer. -func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer { +// ClusterRoleBindings returns a TypedClusterRoleBindingInformer. +func (v *version) ClusterRoleBindings() TypedClusterRoleBindingInformer { return &clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Roles returns a RoleInformer. -func (v *version) Roles() RoleInformer { +// Roles returns a TypedRoleInformer. +func (v *version) Roles() TypedRoleInformer { return &roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// RoleBindings returns a RoleBindingInformer. -func (v *version) RoleBindings() RoleBindingInformer { +// RoleBindings returns a TypedRoleBindingInformer. +func (v *version) RoleBindings() TypedRoleBindingInformer { return &roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/role.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/role.go index f66decf04..0e288582b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/role.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/role.go @@ -34,12 +34,40 @@ import ( ) // RoleInformer provides access to a shared informer and lister for -// Roles. +// Roles. Prefer using the type-safe variant (see [TypedRoleInformer]). type RoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1.RoleLister } +// TypedRoleInformer provides access to a shared informer and lister for +// Roles, including the type-safe TypedInformer variant. +// It is a superset of RoleInformer. +type TypedRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleIndexInformer + Lister() rbacv1.RoleLister +} + +// RoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1.Role] + +// RoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Role. +type RoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1.Role] + +// RoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Role. +type RoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1.Role] + +// RoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Role. +type RoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1.Role] + +// RoleIndexers is a specialization of [cache.TypedIndexers] for Role. +type RoleIndexers = cache.TypedIndexers[*apirbacv1.Role] + +// DeletedRole is a specialization of [cache.DeletedObject] for Role. +type DeletedRole = cache.DeletedObject[*apirbacv1.Role] + type roleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleInformer struct { // NewRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformer]). func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleInformer]). func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleInformerWithOptions constructs a new informer for Role type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformerWithOptions]). func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleInformerWithOptions constructs a new informer for Role type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "roles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1.Role](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, o Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1.Role{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleInformer) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.Role](f.factory.InformerFor(&apirbacv1.Role{}, f.defaultInformer)) } func (f *roleInformer) Lister() rbacv1.RoleLister { return rbacv1.NewRoleLister(f.Informer().GetIndexer()) } + +// ToTypedRoleInformer converts an untyped informer into a TypedRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// TypedRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleInformer(informer RoleInformer) TypedRoleInformer { + if informer, ok := informer.(TypedRoleInformer); ok { + return informer + } + return &roleTypedInformerAdapter{informer} +} + +type roleTypedInformerAdapter struct { + RoleInformer +} + +func (a *roleTypedInformerAdapter) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.Role](a.Informer()) +} + +// ToRoleIndexInformer converts an untyped informer into a RoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// RoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleIndexInformer(informer cache.SharedIndexInformer) RoleIndexInformer { + if informer, ok := informer.(RoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1.Role](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/rolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/rolebinding.go index c17b1c474..261a1d03a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1/rolebinding.go @@ -34,12 +34,40 @@ import ( ) // RoleBindingInformer provides access to a shared informer and lister for -// RoleBindings. +// RoleBindings. Prefer using the type-safe variant (see [TypedRoleBindingInformer]). type RoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1.RoleBindingLister } +// TypedRoleBindingInformer provides access to a shared informer and lister for +// RoleBindings, including the type-safe TypedInformer variant. +// It is a superset of RoleBindingInformer. +type TypedRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleBindingIndexInformer + Lister() rbacv1.RoleBindingLister +} + +// RoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1.RoleBinding] + +// RoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RoleBinding. +type RoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1.RoleBinding] + +// RoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RoleBinding. +type RoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1.RoleBinding] + +// RoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RoleBinding. +type RoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1.RoleBinding] + +// RoleBindingIndexers is a specialization of [cache.TypedIndexers] for RoleBinding. +type RoleBindingIndexers = cache.TypedIndexers[*apirbacv1.RoleBinding] + +// DeletedRoleBinding is a specialization of [cache.DeletedObject] for RoleBinding. +type DeletedRoleBinding = cache.DeletedObject[*apirbacv1.RoleBinding] + type roleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleBindingInformer struct { // NewRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformer]). func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleBindingInformer]). func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformerWithOptions]). func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "rolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1.RoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1.RoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleBindingInformer) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.RoleBinding](f.factory.InformerFor(&apirbacv1.RoleBinding{}, f.defaultInformer)) } func (f *roleBindingInformer) Lister() rbacv1.RoleBindingLister { return rbacv1.NewRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedRoleBindingInformer converts an untyped informer into a TypedRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleBindingInformer(informer RoleBindingInformer) TypedRoleBindingInformer { + if informer, ok := informer.(TypedRoleBindingInformer); ok { + return informer + } + return &roleBindingTypedInformerAdapter{informer} +} + +type roleBindingTypedInformerAdapter struct { + RoleBindingInformer +} + +func (a *roleBindingTypedInformerAdapter) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1.RoleBinding](a.Informer()) +} + +// ToRoleBindingIndexInformer converts an untyped informer into a RoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// RoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleBindingIndexInformer(informer cache.SharedIndexInformer) RoleBindingIndexInformer { + if informer, ok := informer.(RoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1.RoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go index cac4ba05b..2fbc6c2f7 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleInformer provides access to a shared informer and lister for -// ClusterRoles. +// ClusterRoles. Prefer using the type-safe variant (see [TypedClusterRoleInformer]). type ClusterRoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1alpha1.ClusterRoleLister } +// TypedClusterRoleInformer provides access to a shared informer and lister for +// ClusterRoles, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleInformer. +type TypedClusterRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleIndexInformer + Lister() rbacv1alpha1.ClusterRoleLister +} + +// ClusterRoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1alpha1.ClusterRole] + +// ClusterRoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRole. +type ClusterRoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1alpha1.ClusterRole] + +// ClusterRoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRole. +type ClusterRoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1alpha1.ClusterRole] + +// ClusterRoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRole. +type ClusterRoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1alpha1.ClusterRole] + +// ClusterRoleIndexers is a specialization of [cache.TypedIndexers] for ClusterRole. +type ClusterRoleIndexers = cache.TypedIndexers[*apirbacv1alpha1.ClusterRole] + +// DeletedClusterRole is a specialization of [cache.DeletedObject] for ClusterRole. +type DeletedClusterRole = cache.DeletedObject[*apirbacv1alpha1.ClusterRole] + type clusterRoleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleInformer struct { // NewClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformer]). func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleInformer]). func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformerWithOptions]). func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, options) +} + +// NewTypedClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "clusterroles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRole](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1alpha1.ClusterRole{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleInformer) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRole](f.factory.InformerFor(&apirbacv1alpha1.ClusterRole{}, f.defaultInformer)) } func (f *clusterRoleInformer) Lister() rbacv1alpha1.ClusterRoleLister { return rbacv1alpha1.NewClusterRoleLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleInformer converts an untyped informer into a TypedClusterRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleInformer(informer ClusterRoleInformer) TypedClusterRoleInformer { + if informer, ok := informer.(TypedClusterRoleInformer); ok { + return informer + } + return &clusterRoleTypedInformerAdapter{informer} +} + +type clusterRoleTypedInformerAdapter struct { + ClusterRoleInformer +} + +func (a *clusterRoleTypedInformerAdapter) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRole](a.Informer()) +} + +// ToClusterRoleIndexInformer converts an untyped informer into a ClusterRoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// ClusterRoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleIndexInformer(informer cache.SharedIndexInformer) ClusterRoleIndexInformer { + if informer, ok := informer.(ClusterRoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRole](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go index 944e16cef..1932c1ef4 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleBindingInformer provides access to a shared informer and lister for -// ClusterRoleBindings. +// ClusterRoleBindings. Prefer using the type-safe variant (see [TypedClusterRoleBindingInformer]). type ClusterRoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1alpha1.ClusterRoleBindingLister } +// TypedClusterRoleBindingInformer provides access to a shared informer and lister for +// ClusterRoleBindings, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleBindingInformer. +type TypedClusterRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleBindingIndexInformer + Lister() rbacv1alpha1.ClusterRoleBindingLister +} + +// ClusterRoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1alpha1.ClusterRoleBinding] + +// ClusterRoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRoleBinding. +type ClusterRoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1alpha1.ClusterRoleBinding] + +// ClusterRoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRoleBinding. +type ClusterRoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1alpha1.ClusterRoleBinding] + +// ClusterRoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRoleBinding. +type ClusterRoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1alpha1.ClusterRoleBinding] + +// ClusterRoleBindingIndexers is a specialization of [cache.TypedIndexers] for ClusterRoleBinding. +type ClusterRoleBindingIndexers = cache.TypedIndexers[*apirbacv1alpha1.ClusterRoleBinding] + +// DeletedClusterRoleBinding is a specialization of [cache.DeletedObject] for ClusterRoleBinding. +type DeletedClusterRoleBinding = cache.DeletedObject[*apirbacv1alpha1.ClusterRoleBinding] + type clusterRoleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleBindingInformer struct { // NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformer]). func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleBindingInformer]). func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformerWithOptions]). func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, options) +} + +// NewTypedClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "clusterrolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, optio Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1alpha1.ClusterRoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleBindingInformer) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRoleBinding](f.factory.InformerFor(&apirbacv1alpha1.ClusterRoleBinding{}, f.defaultInformer)) } func (f *clusterRoleBindingInformer) Lister() rbacv1alpha1.ClusterRoleBindingLister { return rbacv1alpha1.NewClusterRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleBindingInformer converts an untyped informer into a TypedClusterRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleBindingInformer(informer ClusterRoleBindingInformer) TypedClusterRoleBindingInformer { + if informer, ok := informer.(TypedClusterRoleBindingInformer); ok { + return informer + } + return &clusterRoleBindingTypedInformerAdapter{informer} +} + +type clusterRoleBindingTypedInformerAdapter struct { + ClusterRoleBindingInformer +} + +func (a *clusterRoleBindingTypedInformerAdapter) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRoleBinding](a.Informer()) +} + +// ToClusterRoleBindingIndexInformer converts an untyped informer into a ClusterRoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// ClusterRoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleBindingIndexInformer(informer cache.SharedIndexInformer) ClusterRoleBindingIndexInformer { + if informer, ok := informer.(ClusterRoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.ClusterRoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/interface.go index d27c79987..fcfc9d232 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ClusterRoles returns a ClusterRoleInformer. - ClusterRoles() ClusterRoleInformer + ClusterRoles() TypedClusterRoleInformer // ClusterRoleBindings returns a ClusterRoleBindingInformer. - ClusterRoleBindings() ClusterRoleBindingInformer + ClusterRoleBindings() TypedClusterRoleBindingInformer // Roles returns a RoleInformer. - Roles() RoleInformer + Roles() TypedRoleInformer // RoleBindings returns a RoleBindingInformer. - RoleBindings() RoleBindingInformer + RoleBindings() TypedRoleBindingInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterRoles returns a ClusterRoleInformer. -func (v *version) ClusterRoles() ClusterRoleInformer { +// ClusterRoles returns a TypedClusterRoleInformer. +func (v *version) ClusterRoles() TypedClusterRoleInformer { return &clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ClusterRoleBindings returns a ClusterRoleBindingInformer. -func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer { +// ClusterRoleBindings returns a TypedClusterRoleBindingInformer. +func (v *version) ClusterRoleBindings() TypedClusterRoleBindingInformer { return &clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Roles returns a RoleInformer. -func (v *version) Roles() RoleInformer { +// Roles returns a TypedRoleInformer. +func (v *version) Roles() TypedRoleInformer { return &roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// RoleBindings returns a RoleBindingInformer. -func (v *version) RoleBindings() RoleBindingInformer { +// RoleBindings returns a TypedRoleBindingInformer. +func (v *version) RoleBindings() TypedRoleBindingInformer { return &roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/role.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/role.go index c4e2a6cf6..f50036840 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/role.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/role.go @@ -34,12 +34,40 @@ import ( ) // RoleInformer provides access to a shared informer and lister for -// Roles. +// Roles. Prefer using the type-safe variant (see [TypedRoleInformer]). type RoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1alpha1.RoleLister } +// TypedRoleInformer provides access to a shared informer and lister for +// Roles, including the type-safe TypedInformer variant. +// It is a superset of RoleInformer. +type TypedRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleIndexInformer + Lister() rbacv1alpha1.RoleLister +} + +// RoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1alpha1.Role] + +// RoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Role. +type RoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1alpha1.Role] + +// RoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Role. +type RoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1alpha1.Role] + +// RoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Role. +type RoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1alpha1.Role] + +// RoleIndexers is a specialization of [cache.TypedIndexers] for Role. +type RoleIndexers = cache.TypedIndexers[*apirbacv1alpha1.Role] + +// DeletedRole is a specialization of [cache.DeletedObject] for Role. +type DeletedRole = cache.DeletedObject[*apirbacv1alpha1.Role] + type roleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleInformer struct { // NewRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformer]). func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleInformer]). func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleInformerWithOptions constructs a new informer for Role type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformerWithOptions]). func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleInformerWithOptions constructs a new informer for Role type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "roles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.Role](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, o Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1alpha1.Role{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleInformer) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.Role](f.factory.InformerFor(&apirbacv1alpha1.Role{}, f.defaultInformer)) } func (f *roleInformer) Lister() rbacv1alpha1.RoleLister { return rbacv1alpha1.NewRoleLister(f.Informer().GetIndexer()) } + +// ToTypedRoleInformer converts an untyped informer into a TypedRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// TypedRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleInformer(informer RoleInformer) TypedRoleInformer { + if informer, ok := informer.(TypedRoleInformer); ok { + return informer + } + return &roleTypedInformerAdapter{informer} +} + +type roleTypedInformerAdapter struct { + RoleInformer +} + +func (a *roleTypedInformerAdapter) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.Role](a.Informer()) +} + +// ToRoleIndexInformer converts an untyped informer into a RoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// RoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleIndexInformer(informer cache.SharedIndexInformer) RoleIndexInformer { + if informer, ok := informer.(RoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.Role](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go index ef1e246f5..64b5b257f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go @@ -34,12 +34,40 @@ import ( ) // RoleBindingInformer provides access to a shared informer and lister for -// RoleBindings. +// RoleBindings. Prefer using the type-safe variant (see [TypedRoleBindingInformer]). type RoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1alpha1.RoleBindingLister } +// TypedRoleBindingInformer provides access to a shared informer and lister for +// RoleBindings, including the type-safe TypedInformer variant. +// It is a superset of RoleBindingInformer. +type TypedRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleBindingIndexInformer + Lister() rbacv1alpha1.RoleBindingLister +} + +// RoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1alpha1.RoleBinding] + +// RoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RoleBinding. +type RoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1alpha1.RoleBinding] + +// RoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RoleBinding. +type RoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1alpha1.RoleBinding] + +// RoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RoleBinding. +type RoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1alpha1.RoleBinding] + +// RoleBindingIndexers is a specialization of [cache.TypedIndexers] for RoleBinding. +type RoleBindingIndexers = cache.TypedIndexers[*apirbacv1alpha1.RoleBinding] + +// DeletedRoleBinding is a specialization of [cache.DeletedObject] for RoleBinding. +type DeletedRoleBinding = cache.DeletedObject[*apirbacv1alpha1.RoleBinding] + type roleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleBindingInformer struct { // NewRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformer]). func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleBindingInformer]). func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformerWithOptions]). func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "rolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.RoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1alpha1.RoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleBindingInformer) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.RoleBinding](f.factory.InformerFor(&apirbacv1alpha1.RoleBinding{}, f.defaultInformer)) } func (f *roleBindingInformer) Lister() rbacv1alpha1.RoleBindingLister { return rbacv1alpha1.NewRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedRoleBindingInformer converts an untyped informer into a TypedRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleBindingInformer(informer RoleBindingInformer) TypedRoleBindingInformer { + if informer, ok := informer.(TypedRoleBindingInformer); ok { + return informer + } + return &roleBindingTypedInformerAdapter{informer} +} + +type roleBindingTypedInformerAdapter struct { + RoleBindingInformer +} + +func (a *roleBindingTypedInformerAdapter) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.RoleBinding](a.Informer()) +} + +// ToRoleBindingIndexInformer converts an untyped informer into a RoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// RoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleBindingIndexInformer(informer cache.SharedIndexInformer) RoleBindingIndexInformer { + if informer, ok := informer.(RoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1alpha1.RoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go index df87d468c..20261642d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleInformer provides access to a shared informer and lister for -// ClusterRoles. +// ClusterRoles. Prefer using the type-safe variant (see [TypedClusterRoleInformer]). type ClusterRoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1beta1.ClusterRoleLister } +// TypedClusterRoleInformer provides access to a shared informer and lister for +// ClusterRoles, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleInformer. +type TypedClusterRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleIndexInformer + Lister() rbacv1beta1.ClusterRoleLister +} + +// ClusterRoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1beta1.ClusterRole] + +// ClusterRoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRole. +type ClusterRoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1beta1.ClusterRole] + +// ClusterRoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRole. +type ClusterRoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1beta1.ClusterRole] + +// ClusterRoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRole. +type ClusterRoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1beta1.ClusterRole] + +// ClusterRoleIndexers is a specialization of [cache.TypedIndexers] for ClusterRole. +type ClusterRoleIndexers = cache.TypedIndexers[*apirbacv1beta1.ClusterRole] + +// DeletedClusterRole is a specialization of [cache.DeletedObject] for ClusterRole. +type DeletedClusterRole = cache.DeletedObject[*apirbacv1beta1.ClusterRole] + type clusterRoleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleInformer struct { // NewClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformer]). func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleInformer]). func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleInformer constructs a new informer for ClusterRole type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleInformerWithOptions]). func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleInformerWithOptions(client, options) +} + +// NewTypedClusterRoleInformerWithOptions constructs a new informer for ClusterRole type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterroles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRole](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1beta1.ClusterRole{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleInformer) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRole](f.factory.InformerFor(&apirbacv1beta1.ClusterRole{}, f.defaultInformer)) } func (f *clusterRoleInformer) Lister() rbacv1beta1.ClusterRoleLister { return rbacv1beta1.NewClusterRoleLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleInformer converts an untyped informer into a TypedClusterRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleInformer(informer ClusterRoleInformer) TypedClusterRoleInformer { + if informer, ok := informer.(TypedClusterRoleInformer); ok { + return informer + } + return &clusterRoleTypedInformerAdapter{informer} +} + +type clusterRoleTypedInformerAdapter struct { + ClusterRoleInformer +} + +func (a *clusterRoleTypedInformerAdapter) TypedInformer() ClusterRoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRole](a.Informer()) +} + +// ToClusterRoleIndexInformer converts an untyped informer into a ClusterRoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRole. If that is not the case, calling type-safe methods of the returned +// ClusterRoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleIndexInformer(informer cache.SharedIndexInformer) ClusterRoleIndexInformer { + if informer, ok := informer.(ClusterRoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRole](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go index 9f14c10da..a454f0c64 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go @@ -34,12 +34,40 @@ import ( ) // ClusterRoleBindingInformer provides access to a shared informer and lister for -// ClusterRoleBindings. +// ClusterRoleBindings. Prefer using the type-safe variant (see [TypedClusterRoleBindingInformer]). type ClusterRoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1beta1.ClusterRoleBindingLister } +// TypedClusterRoleBindingInformer provides access to a shared informer and lister for +// ClusterRoleBindings, including the type-safe TypedInformer variant. +// It is a superset of ClusterRoleBindingInformer. +type TypedClusterRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ClusterRoleBindingIndexInformer + Lister() rbacv1beta1.ClusterRoleBindingLister +} + +// ClusterRoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ClusterRoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1beta1.ClusterRoleBinding] + +// ClusterRoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ClusterRoleBinding. +type ClusterRoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1beta1.ClusterRoleBinding] + +// ClusterRoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ClusterRoleBinding. +type ClusterRoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1beta1.ClusterRoleBinding] + +// ClusterRoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ClusterRoleBinding. +type ClusterRoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1beta1.ClusterRoleBinding] + +// ClusterRoleBindingIndexers is a specialization of [cache.TypedIndexers] for ClusterRoleBinding. +type ClusterRoleBindingIndexers = cache.TypedIndexers[*apirbacv1beta1.ClusterRoleBinding] + +// DeletedClusterRoleBinding is a specialization of [cache.DeletedObject] for ClusterRoleBinding. +type DeletedClusterRoleBinding = cache.DeletedObject[*apirbacv1beta1.ClusterRoleBinding] + type clusterRoleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type clusterRoleBindingInformer struct { // NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformer]). func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredClusterRoleBindingInformer]). func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ClusterRoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ClusterRoleBindingIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedClusterRoleBindingInformerWithOptions]). func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedClusterRoleBindingInformerWithOptions(client, options) +} + +// NewTypedClusterRoleBindingInformerWithOptions constructs a new informer for ClusterRoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedClusterRoleBindingInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ClusterRoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterrolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewClusterRoleBindingInformerWithOptions(client kubernetes.Interface, optio Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedClusterRoleBindingInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1beta1.ClusterRoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *clusterRoleBindingInformer) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRoleBinding](f.factory.InformerFor(&apirbacv1beta1.ClusterRoleBinding{}, f.defaultInformer)) } func (f *clusterRoleBindingInformer) Lister() rbacv1beta1.ClusterRoleBindingLister { return rbacv1beta1.NewClusterRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedClusterRoleBindingInformer converts an untyped informer into a TypedClusterRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedClusterRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedClusterRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedClusterRoleBindingInformer(informer ClusterRoleBindingInformer) TypedClusterRoleBindingInformer { + if informer, ok := informer.(TypedClusterRoleBindingInformer); ok { + return informer + } + return &clusterRoleBindingTypedInformerAdapter{informer} +} + +type clusterRoleBindingTypedInformerAdapter struct { + ClusterRoleBindingInformer +} + +func (a *clusterRoleBindingTypedInformerAdapter) TypedInformer() ClusterRoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRoleBinding](a.Informer()) +} + +// ToClusterRoleBindingIndexInformer converts an untyped informer into a ClusterRoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ClusterRoleBinding. If that is not the case, calling type-safe methods of the returned +// ClusterRoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ClusterRoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToClusterRoleBindingIndexInformer(informer cache.SharedIndexInformer) ClusterRoleBindingIndexInformer { + if informer, ok := informer.(ClusterRoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.ClusterRoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/interface.go index 04add43af..af356b40e 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // ClusterRoles returns a ClusterRoleInformer. - ClusterRoles() ClusterRoleInformer + ClusterRoles() TypedClusterRoleInformer // ClusterRoleBindings returns a ClusterRoleBindingInformer. - ClusterRoleBindings() ClusterRoleBindingInformer + ClusterRoleBindings() TypedClusterRoleBindingInformer // Roles returns a RoleInformer. - Roles() RoleInformer + Roles() TypedRoleInformer // RoleBindings returns a RoleBindingInformer. - RoleBindings() RoleBindingInformer + RoleBindings() TypedRoleBindingInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterRoles returns a ClusterRoleInformer. -func (v *version) ClusterRoles() ClusterRoleInformer { +// ClusterRoles returns a TypedClusterRoleInformer. +func (v *version) ClusterRoles() TypedClusterRoleInformer { return &clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ClusterRoleBindings returns a ClusterRoleBindingInformer. -func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer { +// ClusterRoleBindings returns a TypedClusterRoleBindingInformer. +func (v *version) ClusterRoleBindings() TypedClusterRoleBindingInformer { return &clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// Roles returns a RoleInformer. -func (v *version) Roles() RoleInformer { +// Roles returns a TypedRoleInformer. +func (v *version) Roles() TypedRoleInformer { return &roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// RoleBindings returns a RoleBindingInformer. -func (v *version) RoleBindings() RoleBindingInformer { +// RoleBindings returns a TypedRoleBindingInformer. +func (v *version) RoleBindings() TypedRoleBindingInformer { return &roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/role.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/role.go index 4dd948f16..fe0d4acf9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/role.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/role.go @@ -34,12 +34,40 @@ import ( ) // RoleInformer provides access to a shared informer and lister for -// Roles. +// Roles. Prefer using the type-safe variant (see [TypedRoleInformer]). type RoleInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1beta1.RoleLister } +// TypedRoleInformer provides access to a shared informer and lister for +// Roles, including the type-safe TypedInformer variant. +// It is a superset of RoleInformer. +type TypedRoleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleIndexInformer + Lister() rbacv1beta1.RoleLister +} + +// RoleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleIndexInformer cache.TypedSharedIndexInformer[*apirbacv1beta1.Role] + +// RoleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Role. +type RoleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1beta1.Role] + +// RoleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Role. +type RoleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1beta1.Role] + +// RoleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Role. +type RoleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1beta1.Role] + +// RoleIndexers is a specialization of [cache.TypedIndexers] for Role. +type RoleIndexers = cache.TypedIndexers[*apirbacv1beta1.Role] + +// DeletedRole is a specialization of [cache.DeletedObject] for Role. +type DeletedRole = cache.DeletedObject[*apirbacv1beta1.Role] + type roleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleInformer struct { // NewRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformer]). func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleInformer constructs a new informer for Role type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleInformer]). func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleInformer constructs a new informer for Role type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleInformerWithOptions constructs a new informer for Role type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleInformerWithOptions]). func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleInformerWithOptions constructs a new informer for Role type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "roles"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.Role](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleInformerWithOptions(client kubernetes.Interface, namespace string, o Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1beta1.Role{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleInformer) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.Role](f.factory.InformerFor(&apirbacv1beta1.Role{}, f.defaultInformer)) } func (f *roleInformer) Lister() rbacv1beta1.RoleLister { return rbacv1beta1.NewRoleLister(f.Informer().GetIndexer()) } + +// ToTypedRoleInformer converts an untyped informer into a TypedRoleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// TypedRoleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleInformer(informer RoleInformer) TypedRoleInformer { + if informer, ok := informer.(TypedRoleInformer); ok { + return informer + } + return &roleTypedInformerAdapter{informer} +} + +type roleTypedInformerAdapter struct { + RoleInformer +} + +func (a *roleTypedInformerAdapter) TypedInformer() RoleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.Role](a.Informer()) +} + +// ToRoleIndexInformer converts an untyped informer into a RoleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Role. If that is not the case, calling type-safe methods of the returned +// RoleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleIndexInformer(informer cache.SharedIndexInformer) RoleIndexInformer { + if informer, ok := informer.(RoleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.Role](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go index 882d59471..dc92e5433 100644 --- a/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go +++ b/constraint/vendor/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go @@ -34,12 +34,40 @@ import ( ) // RoleBindingInformer provides access to a shared informer and lister for -// RoleBindings. +// RoleBindings. Prefer using the type-safe variant (see [TypedRoleBindingInformer]). type RoleBindingInformer interface { Informer() cache.SharedIndexInformer Lister() rbacv1beta1.RoleBindingLister } +// TypedRoleBindingInformer provides access to a shared informer and lister for +// RoleBindings, including the type-safe TypedInformer variant. +// It is a superset of RoleBindingInformer. +type TypedRoleBindingInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() RoleBindingIndexInformer + Lister() rbacv1beta1.RoleBindingLister +} + +// RoleBindingIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type RoleBindingIndexInformer cache.TypedSharedIndexInformer[*apirbacv1beta1.RoleBinding] + +// RoleBindingHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for RoleBinding. +type RoleBindingHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apirbacv1beta1.RoleBinding] + +// RoleBindingDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for RoleBinding. +type RoleBindingDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apirbacv1beta1.RoleBinding] + +// RoleBindingFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for RoleBinding. +type RoleBindingFilteringHandler = cache.TypedFilteringResourceEventHandler[*apirbacv1beta1.RoleBinding] + +// RoleBindingIndexers is a specialization of [cache.TypedIndexers] for RoleBinding. +type RoleBindingIndexers = cache.TypedIndexers[*apirbacv1beta1.RoleBinding] + +// DeletedRoleBinding is a specialization of [cache.DeletedObject] for RoleBinding. +type DeletedRoleBinding = cache.DeletedObject[*apirbacv1beta1.RoleBinding] + type roleBindingInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type roleBindingInformer struct { // NewRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformer]). func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredRoleBindingInformer]). func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredRoleBindingInformer constructs a new informer for RoleBinding type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers RoleBindingIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) RoleBindingIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedRoleBindingInformerWithOptions]). func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedRoleBindingInformerWithOptions(client, namespace, options) +} + +// NewTypedRoleBindingInformerWithOptions constructs a new informer for RoleBinding type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedRoleBindingInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) RoleBindingIndexInformer { gvr := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "rolebindings"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.RoleBinding](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewRoleBindingInformerWithOptions(client kubernetes.Interface, namespace st Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedRoleBindingInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *roleBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apirbacv1beta1.RoleBinding{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *roleBindingInformer) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.RoleBinding](f.factory.InformerFor(&apirbacv1beta1.RoleBinding{}, f.defaultInformer)) } func (f *roleBindingInformer) Lister() rbacv1beta1.RoleBindingLister { return rbacv1beta1.NewRoleBindingLister(f.Informer().GetIndexer()) } + +// ToTypedRoleBindingInformer converts an untyped informer into a TypedRoleBindingInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// TypedRoleBindingInformer leads to runtime panics. A safer alternative is to pass +// around a TypedRoleBindingInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedRoleBindingInformer(informer RoleBindingInformer) TypedRoleBindingInformer { + if informer, ok := informer.(TypedRoleBindingInformer); ok { + return informer + } + return &roleBindingTypedInformerAdapter{informer} +} + +type roleBindingTypedInformerAdapter struct { + RoleBindingInformer +} + +func (a *roleBindingTypedInformerAdapter) TypedInformer() RoleBindingIndexInformer { + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.RoleBinding](a.Informer()) +} + +// ToRoleBindingIndexInformer converts an untyped informer into a RoleBindingIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *RoleBinding. If that is not the case, calling type-safe methods of the returned +// RoleBindingIndexInformer leads to runtime panics. A safer alternative is to pass +// around a RoleBindingIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToRoleBindingIndexInformer(informer cache.SharedIndexInformer) RoleBindingIndexInformer { + if informer, ok := informer.(RoleBindingIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apirbacv1beta1.RoleBinding](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/deviceclass.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/deviceclass.go index bacc65a28..807a8f946 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/deviceclass.go @@ -34,12 +34,40 @@ import ( ) // DeviceClassInformer provides access to a shared informer and lister for -// DeviceClasses. +// DeviceClasses. Prefer using the type-safe variant (see [TypedDeviceClassInformer]). type DeviceClassInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1.DeviceClassLister } +// TypedDeviceClassInformer provides access to a shared informer and lister for +// DeviceClasses, including the type-safe TypedInformer variant. +// It is a superset of DeviceClassInformer. +type TypedDeviceClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceClassIndexInformer + Lister() resourcev1.DeviceClassLister +} + +// DeviceClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceClassIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1.DeviceClass] + +// DeviceClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceClass. +type DeviceClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1.DeviceClass] + +// DeviceClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceClass. +type DeviceClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1.DeviceClass] + +// DeviceClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceClass. +type DeviceClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1.DeviceClass] + +// DeviceClassIndexers is a specialization of [cache.TypedIndexers] for DeviceClass. +type DeviceClassIndexers = cache.TypedIndexers[*apiresourcev1.DeviceClass] + +// DeletedDeviceClass is a specialization of [cache.DeletedObject] for DeviceClass. +type DeletedDeviceClass = cache.DeletedObject[*apiresourcev1.DeviceClass] + type deviceClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type deviceClassInformer struct { // NewDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformer]). func NewDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceClassInformer]). func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformerWithOptions]). func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, options) +} + +// NewTypedDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceClassIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1", Resource: "deviceclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deviceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deviceClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1.DeviceClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deviceClassInformer) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceClass](f.factory.InformerFor(&apiresourcev1.DeviceClass{}, f.defaultInformer)) } func (f *deviceClassInformer) Lister() resourcev1.DeviceClassLister { return resourcev1.NewDeviceClassLister(f.Informer().GetIndexer()) } + +// ToTypedDeviceClassInformer converts an untyped informer into a TypedDeviceClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// TypedDeviceClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceClassInformer(informer DeviceClassInformer) TypedDeviceClassInformer { + if informer, ok := informer.(TypedDeviceClassInformer); ok { + return informer + } + return &deviceClassTypedInformerAdapter{informer} +} + +type deviceClassTypedInformerAdapter struct { + DeviceClassInformer +} + +func (a *deviceClassTypedInformerAdapter) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceClass](a.Informer()) +} + +// ToDeviceClassIndexInformer converts an untyped informer into a DeviceClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// DeviceClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceClassIndexInformer(informer cache.SharedIndexInformer) DeviceClassIndexInformer { + if informer, ok := informer.(DeviceClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/devicetaintrule.go new file mode 100644 index 000000000..c0776f5fb --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/devicetaintrule.go @@ -0,0 +1,207 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apiresourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + resourcev1 "k8s.io/client-go/listers/resource/v1" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceTaintRuleInformer provides access to a shared informer and lister for +// DeviceTaintRules. Prefer using the type-safe variant (see [TypedDeviceTaintRuleInformer]). +type DeviceTaintRuleInformer interface { + Informer() cache.SharedIndexInformer + Lister() resourcev1.DeviceTaintRuleLister +} + +// TypedDeviceTaintRuleInformer provides access to a shared informer and lister for +// DeviceTaintRules, including the type-safe TypedInformer variant. +// It is a superset of DeviceTaintRuleInformer. +type TypedDeviceTaintRuleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceTaintRuleIndexInformer + Lister() resourcev1.DeviceTaintRuleLister +} + +// DeviceTaintRuleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceTaintRuleIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1.DeviceTaintRule] + +// DeviceTaintRuleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceTaintRule. +type DeviceTaintRuleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1.DeviceTaintRule] + +// DeviceTaintRuleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceTaintRule. +type DeviceTaintRuleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1.DeviceTaintRule] + +// DeviceTaintRuleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceTaintRule. +type DeviceTaintRuleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1.DeviceTaintRule] + +// DeviceTaintRuleIndexers is a specialization of [cache.TypedIndexers] for DeviceTaintRule. +type DeviceTaintRuleIndexers = cache.TypedIndexers[*apiresourcev1.DeviceTaintRule] + +// DeletedDeviceTaintRule is a specialization of [cache.DeletedObject] for DeviceTaintRule. +type DeletedDeviceTaintRule = cache.DeletedObject[*apiresourcev1.DeviceTaintRule] + +type deviceTaintRuleInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformer]). +func NewDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceTaintRuleInformer]). +func NewFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformerWithOptions]). +func NewDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, options) +} + +// NewTypedDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceTaintRuleIndexInformer { + gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1", Resource: "devicetaintrules"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceTaintRule](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.ResourceV1().DeviceTaintRules().List(context.Background(), opts) + }, + WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.ResourceV1().DeviceTaintRules().Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.ResourceV1().DeviceTaintRules().List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.ResourceV1().DeviceTaintRules().Watch(ctx, opts) + }, + }, client), + &apiresourcev1.DeviceTaintRule{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *deviceTaintRuleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *deviceTaintRuleInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *deviceTaintRuleInformer) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceTaintRule](f.factory.InformerFor(&apiresourcev1.DeviceTaintRule{}, f.defaultInformer)) +} + +func (f *deviceTaintRuleInformer) Lister() resourcev1.DeviceTaintRuleLister { + return resourcev1.NewDeviceTaintRuleLister(f.Informer().GetIndexer()) +} + +// ToTypedDeviceTaintRuleInformer converts an untyped informer into a TypedDeviceTaintRuleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// TypedDeviceTaintRuleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceTaintRuleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceTaintRuleInformer(informer DeviceTaintRuleInformer) TypedDeviceTaintRuleInformer { + if informer, ok := informer.(TypedDeviceTaintRuleInformer); ok { + return informer + } + return &deviceTaintRuleTypedInformerAdapter{informer} +} + +type deviceTaintRuleTypedInformerAdapter struct { + DeviceTaintRuleInformer +} + +func (a *deviceTaintRuleTypedInformerAdapter) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceTaintRule](a.Informer()) +} + +// ToDeviceTaintRuleIndexInformer converts an untyped informer into a DeviceTaintRuleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// DeviceTaintRuleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceTaintRuleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceTaintRuleIndexInformer(informer cache.SharedIndexInformer) DeviceTaintRuleIndexInformer { + if informer, ok := informer.(DeviceTaintRuleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1.DeviceTaintRule](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/interface.go index 4b409fbba..c0456078f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/interface.go @@ -25,13 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // DeviceClasses returns a DeviceClassInformer. - DeviceClasses() DeviceClassInformer + DeviceClasses() TypedDeviceClassInformer + // DeviceTaintRules returns a DeviceTaintRuleInformer. + DeviceTaintRules() TypedDeviceTaintRuleInformer // ResourceClaims returns a ResourceClaimInformer. - ResourceClaims() ResourceClaimInformer + ResourceClaims() TypedResourceClaimInformer // ResourceClaimTemplates returns a ResourceClaimTemplateInformer. - ResourceClaimTemplates() ResourceClaimTemplateInformer + ResourceClaimTemplates() TypedResourceClaimTemplateInformer // ResourceSlices returns a ResourceSliceInformer. - ResourceSlices() ResourceSliceInformer + ResourceSlices() TypedResourceSliceInformer } type version struct { @@ -45,22 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// DeviceClasses returns a DeviceClassInformer. -func (v *version) DeviceClasses() DeviceClassInformer { +// DeviceClasses returns a TypedDeviceClassInformer. +func (v *version) DeviceClasses() TypedDeviceClassInformer { return &deviceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ResourceClaims returns a ResourceClaimInformer. -func (v *version) ResourceClaims() ResourceClaimInformer { +// DeviceTaintRules returns a TypedDeviceTaintRuleInformer. +func (v *version) DeviceTaintRules() TypedDeviceTaintRuleInformer { + return &deviceTaintRuleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} + +// ResourceClaims returns a TypedResourceClaimInformer. +func (v *version) ResourceClaims() TypedResourceClaimInformer { return &resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceClaimTemplates returns a ResourceClaimTemplateInformer. -func (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer { +// ResourceClaimTemplates returns a TypedResourceClaimTemplateInformer. +func (v *version) ResourceClaimTemplates() TypedResourceClaimTemplateInformer { return &resourceClaimTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceSlices returns a ResourceSliceInformer. -func (v *version) ResourceSlices() ResourceSliceInformer { +// ResourceSlices returns a TypedResourceSliceInformer. +func (v *version) ResourceSlices() TypedResourceSliceInformer { return &resourceSliceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaim.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaim.go index 996cc77f6..cd5486739 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaim.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimInformer provides access to a shared informer and lister for -// ResourceClaims. +// ResourceClaims. Prefer using the type-safe variant (see [TypedResourceClaimInformer]). type ResourceClaimInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1.ResourceClaimLister } +// TypedResourceClaimInformer provides access to a shared informer and lister for +// ResourceClaims, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimInformer. +type TypedResourceClaimInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimIndexInformer + Lister() resourcev1.ResourceClaimLister +} + +// ResourceClaimIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1.ResourceClaim] + +// ResourceClaimHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaim. +type ResourceClaimHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1.ResourceClaim] + +// ResourceClaimDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaim. +type ResourceClaimDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1.ResourceClaim] + +// ResourceClaimFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaim. +type ResourceClaimFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1.ResourceClaim] + +// ResourceClaimIndexers is a specialization of [cache.TypedIndexers] for ResourceClaim. +type ResourceClaimIndexers = cache.TypedIndexers[*apiresourcev1.ResourceClaim] + +// DeletedResourceClaim is a specialization of [cache.DeletedObject] for ResourceClaim. +type DeletedResourceClaim = cache.DeletedObject[*apiresourcev1.ResourceClaim] + type resourceClaimInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimInformer struct { // NewResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformer]). func NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimInformer]). func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformerWithOptions]). func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1", Resource: "resourceclaims"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaim](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1.ResourceClaim{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimInformer) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaim](f.factory.InformerFor(&apiresourcev1.ResourceClaim{}, f.defaultInformer)) } func (f *resourceClaimInformer) Lister() resourcev1.ResourceClaimLister { return resourcev1.NewResourceClaimLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimInformer converts an untyped informer into a TypedResourceClaimInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimInformer(informer ResourceClaimInformer) TypedResourceClaimInformer { + if informer, ok := informer.(TypedResourceClaimInformer); ok { + return informer + } + return &resourceClaimTypedInformerAdapter{informer} +} + +type resourceClaimTypedInformerAdapter struct { + ResourceClaimInformer +} + +func (a *resourceClaimTypedInformerAdapter) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaim](a.Informer()) +} + +// ToResourceClaimIndexInformer converts an untyped informer into a ResourceClaimIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// ResourceClaimIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimIndexInformer(informer cache.SharedIndexInformer) ResourceClaimIndexInformer { + if informer, ok := informer.(ResourceClaimIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaim](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaimtemplate.go index e562314dc..9e2925ec2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceclaimtemplate.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimTemplateInformer provides access to a shared informer and lister for -// ResourceClaimTemplates. +// ResourceClaimTemplates. Prefer using the type-safe variant (see [TypedResourceClaimTemplateInformer]). type ResourceClaimTemplateInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1.ResourceClaimTemplateLister } +// TypedResourceClaimTemplateInformer provides access to a shared informer and lister for +// ResourceClaimTemplates, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimTemplateInformer. +type TypedResourceClaimTemplateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimTemplateIndexInformer + Lister() resourcev1.ResourceClaimTemplateLister +} + +// ResourceClaimTemplateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimTemplateIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1.ResourceClaimTemplate] + +// ResourceClaimTemplateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1.ResourceClaimTemplate] + +// ResourceClaimTemplateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1.ResourceClaimTemplate] + +// ResourceClaimTemplateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaimTemplate. +type ResourceClaimTemplateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1.ResourceClaimTemplate] + +// ResourceClaimTemplateIndexers is a specialization of [cache.TypedIndexers] for ResourceClaimTemplate. +type ResourceClaimTemplateIndexers = cache.TypedIndexers[*apiresourcev1.ResourceClaimTemplate] + +// DeletedResourceClaimTemplate is a specialization of [cache.DeletedObject] for ResourceClaimTemplate. +type DeletedResourceClaimTemplate = cache.DeletedObject[*apiresourcev1.ResourceClaimTemplate] + type resourceClaimTemplateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimTemplateInformer struct { // NewResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformer]). func NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimTemplateInformer]). func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformerWithOptions]). func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimTemplateIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1", Resource: "resourceclaimtemplates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaimTemplate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1.ResourceClaimTemplate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimTemplateInformer) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaimTemplate](f.factory.InformerFor(&apiresourcev1.ResourceClaimTemplate{}, f.defaultInformer)) } func (f *resourceClaimTemplateInformer) Lister() resourcev1.ResourceClaimTemplateLister { return resourcev1.NewResourceClaimTemplateLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimTemplateInformer converts an untyped informer into a TypedResourceClaimTemplateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimTemplateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimTemplateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimTemplateInformer(informer ResourceClaimTemplateInformer) TypedResourceClaimTemplateInformer { + if informer, ok := informer.(TypedResourceClaimTemplateInformer); ok { + return informer + } + return &resourceClaimTemplateTypedInformerAdapter{informer} +} + +type resourceClaimTemplateTypedInformerAdapter struct { + ResourceClaimTemplateInformer +} + +func (a *resourceClaimTemplateTypedInformerAdapter) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaimTemplate](a.Informer()) +} + +// ToResourceClaimTemplateIndexInformer converts an untyped informer into a ResourceClaimTemplateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// ResourceClaimTemplateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimTemplateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimTemplateIndexInformer(informer cache.SharedIndexInformer) ResourceClaimTemplateIndexInformer { + if informer, ok := informer.(ResourceClaimTemplateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceClaimTemplate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceslice.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceslice.go index 85c877f80..b03bc1b72 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1/resourceslice.go @@ -34,12 +34,40 @@ import ( ) // ResourceSliceInformer provides access to a shared informer and lister for -// ResourceSlices. +// ResourceSlices. Prefer using the type-safe variant (see [TypedResourceSliceInformer]). type ResourceSliceInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1.ResourceSliceLister } +// TypedResourceSliceInformer provides access to a shared informer and lister for +// ResourceSlices, including the type-safe TypedInformer variant. +// It is a superset of ResourceSliceInformer. +type TypedResourceSliceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceSliceIndexInformer + Lister() resourcev1.ResourceSliceLister +} + +// ResourceSliceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceSliceIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1.ResourceSlice] + +// ResourceSliceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceSlice. +type ResourceSliceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1.ResourceSlice] + +// ResourceSliceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceSlice. +type ResourceSliceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1.ResourceSlice] + +// ResourceSliceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceSlice. +type ResourceSliceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1.ResourceSlice] + +// ResourceSliceIndexers is a specialization of [cache.TypedIndexers] for ResourceSlice. +type ResourceSliceIndexers = cache.TypedIndexers[*apiresourcev1.ResourceSlice] + +// DeletedResourceSlice is a specialization of [cache.DeletedObject] for ResourceSlice. +type DeletedResourceSlice = cache.DeletedObject[*apiresourcev1.ResourceSlice] + type resourceSliceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type resourceSliceInformer struct { // NewResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformer]). func NewResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceSliceInformer]). func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformerWithOptions]). func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, options) +} + +// NewTypedResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ResourceSliceIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1", Resource: "resourceslices"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceSlice](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options in Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceSliceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1.ResourceSlice{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceSliceInformer) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceSlice](f.factory.InformerFor(&apiresourcev1.ResourceSlice{}, f.defaultInformer)) } func (f *resourceSliceInformer) Lister() resourcev1.ResourceSliceLister { return resourcev1.NewResourceSliceLister(f.Informer().GetIndexer()) } + +// ToTypedResourceSliceInformer converts an untyped informer into a TypedResourceSliceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// TypedResourceSliceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceSliceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceSliceInformer(informer ResourceSliceInformer) TypedResourceSliceInformer { + if informer, ok := informer.(TypedResourceSliceInformer); ok { + return informer + } + return &resourceSliceTypedInformerAdapter{informer} +} + +type resourceSliceTypedInformerAdapter struct { + ResourceSliceInformer +} + +func (a *resourceSliceTypedInformerAdapter) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceSlice](a.Informer()) +} + +// ToResourceSliceIndexInformer converts an untyped informer into a ResourceSliceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// ResourceSliceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceSliceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceSliceIndexInformer(informer cache.SharedIndexInformer) ResourceSliceIndexInformer { + if informer, ok := informer.(ResourceSliceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1.ResourceSlice](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/devicetaintrule.go index 0b0029ab5..a8775bd88 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/devicetaintrule.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/devicetaintrule.go @@ -34,12 +34,40 @@ import ( ) // DeviceTaintRuleInformer provides access to a shared informer and lister for -// DeviceTaintRules. +// DeviceTaintRules. Prefer using the type-safe variant (see [TypedDeviceTaintRuleInformer]). type DeviceTaintRuleInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1alpha3.DeviceTaintRuleLister } +// TypedDeviceTaintRuleInformer provides access to a shared informer and lister for +// DeviceTaintRules, including the type-safe TypedInformer variant. +// It is a superset of DeviceTaintRuleInformer. +type TypedDeviceTaintRuleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceTaintRuleIndexInformer + Lister() resourcev1alpha3.DeviceTaintRuleLister +} + +// DeviceTaintRuleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceTaintRuleIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1alpha3.DeviceTaintRule] + +// DeviceTaintRuleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceTaintRule. +type DeviceTaintRuleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1alpha3.DeviceTaintRule] + +// DeviceTaintRuleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceTaintRule. +type DeviceTaintRuleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1alpha3.DeviceTaintRule] + +// DeviceTaintRuleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceTaintRule. +type DeviceTaintRuleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1alpha3.DeviceTaintRule] + +// DeviceTaintRuleIndexers is a specialization of [cache.TypedIndexers] for DeviceTaintRule. +type DeviceTaintRuleIndexers = cache.TypedIndexers[*apiresourcev1alpha3.DeviceTaintRule] + +// DeletedDeviceTaintRule is a specialization of [cache.DeletedObject] for DeviceTaintRule. +type DeletedDeviceTaintRule = cache.DeletedObject[*apiresourcev1alpha3.DeviceTaintRule] + type deviceTaintRuleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type deviceTaintRuleInformer struct { // NewDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformer]). func NewDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceTaintRuleInformer]). func NewFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformerWithOptions]). func NewDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, options) +} + +// NewTypedDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceTaintRuleIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1alpha3", Resource: "devicetaintrules"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.DeviceTaintRule](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deviceTaintRuleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deviceTaintRuleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1alpha3.DeviceTaintRule{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deviceTaintRuleInformer) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.DeviceTaintRule](f.factory.InformerFor(&apiresourcev1alpha3.DeviceTaintRule{}, f.defaultInformer)) } func (f *deviceTaintRuleInformer) Lister() resourcev1alpha3.DeviceTaintRuleLister { return resourcev1alpha3.NewDeviceTaintRuleLister(f.Informer().GetIndexer()) } + +// ToTypedDeviceTaintRuleInformer converts an untyped informer into a TypedDeviceTaintRuleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// TypedDeviceTaintRuleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceTaintRuleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceTaintRuleInformer(informer DeviceTaintRuleInformer) TypedDeviceTaintRuleInformer { + if informer, ok := informer.(TypedDeviceTaintRuleInformer); ok { + return informer + } + return &deviceTaintRuleTypedInformerAdapter{informer} +} + +type deviceTaintRuleTypedInformerAdapter struct { + DeviceTaintRuleInformer +} + +func (a *deviceTaintRuleTypedInformerAdapter) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.DeviceTaintRule](a.Informer()) +} + +// ToDeviceTaintRuleIndexInformer converts an untyped informer into a DeviceTaintRuleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// DeviceTaintRuleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceTaintRuleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceTaintRuleIndexInformer(informer cache.SharedIndexInformer) DeviceTaintRuleIndexInformer { + if informer, ok := informer.(DeviceTaintRuleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.DeviceTaintRule](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/interface.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/interface.go index b30568123..46bdb3b16 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/interface.go @@ -25,9 +25,9 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // DeviceTaintRules returns a DeviceTaintRuleInformer. - DeviceTaintRules() DeviceTaintRuleInformer + DeviceTaintRules() TypedDeviceTaintRuleInformer // ResourcePoolStatusRequests returns a ResourcePoolStatusRequestInformer. - ResourcePoolStatusRequests() ResourcePoolStatusRequestInformer + ResourcePoolStatusRequests() TypedResourcePoolStatusRequestInformer } type version struct { @@ -41,12 +41,12 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// DeviceTaintRules returns a DeviceTaintRuleInformer. -func (v *version) DeviceTaintRules() DeviceTaintRuleInformer { +// DeviceTaintRules returns a TypedDeviceTaintRuleInformer. +func (v *version) DeviceTaintRules() TypedDeviceTaintRuleInformer { return &deviceTaintRuleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ResourcePoolStatusRequests returns a ResourcePoolStatusRequestInformer. -func (v *version) ResourcePoolStatusRequests() ResourcePoolStatusRequestInformer { +// ResourcePoolStatusRequests returns a TypedResourcePoolStatusRequestInformer. +func (v *version) ResourcePoolStatusRequests() TypedResourcePoolStatusRequestInformer { return &resourcePoolStatusRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/resourcepoolstatusrequest.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/resourcepoolstatusrequest.go index f34d57e13..87842dfbe 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/resourcepoolstatusrequest.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1alpha3/resourcepoolstatusrequest.go @@ -34,12 +34,40 @@ import ( ) // ResourcePoolStatusRequestInformer provides access to a shared informer and lister for -// ResourcePoolStatusRequests. +// ResourcePoolStatusRequests. Prefer using the type-safe variant (see [TypedResourcePoolStatusRequestInformer]). type ResourcePoolStatusRequestInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1alpha3.ResourcePoolStatusRequestLister } +// TypedResourcePoolStatusRequestInformer provides access to a shared informer and lister for +// ResourcePoolStatusRequests, including the type-safe TypedInformer variant. +// It is a superset of ResourcePoolStatusRequestInformer. +type TypedResourcePoolStatusRequestInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourcePoolStatusRequestIndexInformer + Lister() resourcev1alpha3.ResourcePoolStatusRequestLister +} + +// ResourcePoolStatusRequestIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourcePoolStatusRequestIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1alpha3.ResourcePoolStatusRequest] + +// ResourcePoolStatusRequestHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourcePoolStatusRequest. +type ResourcePoolStatusRequestHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1alpha3.ResourcePoolStatusRequest] + +// ResourcePoolStatusRequestDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourcePoolStatusRequest. +type ResourcePoolStatusRequestDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1alpha3.ResourcePoolStatusRequest] + +// ResourcePoolStatusRequestFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourcePoolStatusRequest. +type ResourcePoolStatusRequestFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1alpha3.ResourcePoolStatusRequest] + +// ResourcePoolStatusRequestIndexers is a specialization of [cache.TypedIndexers] for ResourcePoolStatusRequest. +type ResourcePoolStatusRequestIndexers = cache.TypedIndexers[*apiresourcev1alpha3.ResourcePoolStatusRequest] + +// DeletedResourcePoolStatusRequest is a specialization of [cache.DeletedObject] for ResourcePoolStatusRequest. +type DeletedResourcePoolStatusRequest = cache.DeletedObject[*apiresourcev1alpha3.ResourcePoolStatusRequest] + type resourcePoolStatusRequestInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type resourcePoolStatusRequestInformer struct { // NewResourcePoolStatusRequestInformer constructs a new informer for ResourcePoolStatusRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourcePoolStatusRequestInformer]). func NewResourcePoolStatusRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourcePoolStatusRequestInformer constructs a new informer for ResourcePoolStatusRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourcePoolStatusRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourcePoolStatusRequestIndexers) ResourcePoolStatusRequestIndexInformer { + return NewTypedResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourcePoolStatusRequestInformer constructs a new informer for ResourcePoolStatusRequest type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourcePoolStatusRequestInformer]). func NewFilteredResourcePoolStatusRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourcePoolStatusRequestInformer constructs a new informer for ResourcePoolStatusRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourcePoolStatusRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourcePoolStatusRequestIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourcePoolStatusRequestIndexInformer { + return NewTypedResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourcePoolStatusRequestInformerWithOptions constructs a new informer for ResourcePoolStatusRequest type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourcePoolStatusRequestInformerWithOptions]). func NewResourcePoolStatusRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourcePoolStatusRequestInformerWithOptions(client, options) +} + +// NewTypedResourcePoolStatusRequestInformerWithOptions constructs a new informer for ResourcePoolStatusRequest type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourcePoolStatusRequestInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ResourcePoolStatusRequestIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1alpha3", Resource: "resourcepoolstatusrequests"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.ResourcePoolStatusRequest](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewResourcePoolStatusRequestInformerWithOptions(client kubernetes.Interface Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourcePoolStatusRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourcePoolStatusRequestInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourcePoolStatusRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1alpha3.ResourcePoolStatusRequest{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourcePoolStatusRequestInformer) TypedInformer() ResourcePoolStatusRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.ResourcePoolStatusRequest](f.factory.InformerFor(&apiresourcev1alpha3.ResourcePoolStatusRequest{}, f.defaultInformer)) } func (f *resourcePoolStatusRequestInformer) Lister() resourcev1alpha3.ResourcePoolStatusRequestLister { return resourcev1alpha3.NewResourcePoolStatusRequestLister(f.Informer().GetIndexer()) } + +// ToTypedResourcePoolStatusRequestInformer converts an untyped informer into a TypedResourcePoolStatusRequestInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourcePoolStatusRequest. If that is not the case, calling type-safe methods of the returned +// TypedResourcePoolStatusRequestInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourcePoolStatusRequestInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourcePoolStatusRequestInformer(informer ResourcePoolStatusRequestInformer) TypedResourcePoolStatusRequestInformer { + if informer, ok := informer.(TypedResourcePoolStatusRequestInformer); ok { + return informer + } + return &resourcePoolStatusRequestTypedInformerAdapter{informer} +} + +type resourcePoolStatusRequestTypedInformerAdapter struct { + ResourcePoolStatusRequestInformer +} + +func (a *resourcePoolStatusRequestTypedInformerAdapter) TypedInformer() ResourcePoolStatusRequestIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.ResourcePoolStatusRequest](a.Informer()) +} + +// ToResourcePoolStatusRequestIndexInformer converts an untyped informer into a ResourcePoolStatusRequestIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourcePoolStatusRequest. If that is not the case, calling type-safe methods of the returned +// ResourcePoolStatusRequestIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourcePoolStatusRequestIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourcePoolStatusRequestIndexInformer(informer cache.SharedIndexInformer) ResourcePoolStatusRequestIndexInformer { + if informer, ok := informer.(ResourcePoolStatusRequestIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1alpha3.ResourcePoolStatusRequest](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/deviceclass.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/deviceclass.go index 0a4d4bea6..bbc371bd2 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/deviceclass.go @@ -34,12 +34,40 @@ import ( ) // DeviceClassInformer provides access to a shared informer and lister for -// DeviceClasses. +// DeviceClasses. Prefer using the type-safe variant (see [TypedDeviceClassInformer]). type DeviceClassInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta1.DeviceClassLister } +// TypedDeviceClassInformer provides access to a shared informer and lister for +// DeviceClasses, including the type-safe TypedInformer variant. +// It is a superset of DeviceClassInformer. +type TypedDeviceClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceClassIndexInformer + Lister() resourcev1beta1.DeviceClassLister +} + +// DeviceClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceClassIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta1.DeviceClass] + +// DeviceClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceClass. +type DeviceClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta1.DeviceClass] + +// DeviceClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceClass. +type DeviceClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta1.DeviceClass] + +// DeviceClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceClass. +type DeviceClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta1.DeviceClass] + +// DeviceClassIndexers is a specialization of [cache.TypedIndexers] for DeviceClass. +type DeviceClassIndexers = cache.TypedIndexers[*apiresourcev1beta1.DeviceClass] + +// DeletedDeviceClass is a specialization of [cache.DeletedObject] for DeviceClass. +type DeletedDeviceClass = cache.DeletedObject[*apiresourcev1beta1.DeviceClass] + type deviceClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type deviceClassInformer struct { // NewDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformer]). func NewDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceClassInformer]). func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformerWithOptions]). func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, options) +} + +// NewTypedDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceClassIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta1", Resource: "deviceclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.DeviceClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deviceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deviceClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta1.DeviceClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deviceClassInformer) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.DeviceClass](f.factory.InformerFor(&apiresourcev1beta1.DeviceClass{}, f.defaultInformer)) } func (f *deviceClassInformer) Lister() resourcev1beta1.DeviceClassLister { return resourcev1beta1.NewDeviceClassLister(f.Informer().GetIndexer()) } + +// ToTypedDeviceClassInformer converts an untyped informer into a TypedDeviceClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// TypedDeviceClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceClassInformer(informer DeviceClassInformer) TypedDeviceClassInformer { + if informer, ok := informer.(TypedDeviceClassInformer); ok { + return informer + } + return &deviceClassTypedInformerAdapter{informer} +} + +type deviceClassTypedInformerAdapter struct { + DeviceClassInformer +} + +func (a *deviceClassTypedInformerAdapter) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.DeviceClass](a.Informer()) +} + +// ToDeviceClassIndexInformer converts an untyped informer into a DeviceClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// DeviceClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceClassIndexInformer(informer cache.SharedIndexInformer) DeviceClassIndexInformer { + if informer, ok := informer.(DeviceClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.DeviceClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/interface.go index 07330763b..6cddfa8f4 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/interface.go @@ -25,13 +25,13 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // DeviceClasses returns a DeviceClassInformer. - DeviceClasses() DeviceClassInformer + DeviceClasses() TypedDeviceClassInformer // ResourceClaims returns a ResourceClaimInformer. - ResourceClaims() ResourceClaimInformer + ResourceClaims() TypedResourceClaimInformer // ResourceClaimTemplates returns a ResourceClaimTemplateInformer. - ResourceClaimTemplates() ResourceClaimTemplateInformer + ResourceClaimTemplates() TypedResourceClaimTemplateInformer // ResourceSlices returns a ResourceSliceInformer. - ResourceSlices() ResourceSliceInformer + ResourceSlices() TypedResourceSliceInformer } type version struct { @@ -45,22 +45,22 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// DeviceClasses returns a DeviceClassInformer. -func (v *version) DeviceClasses() DeviceClassInformer { +// DeviceClasses returns a TypedDeviceClassInformer. +func (v *version) DeviceClasses() TypedDeviceClassInformer { return &deviceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ResourceClaims returns a ResourceClaimInformer. -func (v *version) ResourceClaims() ResourceClaimInformer { +// ResourceClaims returns a TypedResourceClaimInformer. +func (v *version) ResourceClaims() TypedResourceClaimInformer { return &resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceClaimTemplates returns a ResourceClaimTemplateInformer. -func (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer { +// ResourceClaimTemplates returns a TypedResourceClaimTemplateInformer. +func (v *version) ResourceClaimTemplates() TypedResourceClaimTemplateInformer { return &resourceClaimTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceSlices returns a ResourceSliceInformer. -func (v *version) ResourceSlices() ResourceSliceInformer { +// ResourceSlices returns a TypedResourceSliceInformer. +func (v *version) ResourceSlices() TypedResourceSliceInformer { return &resourceSliceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaim.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaim.go index 9ec1ece31..31f1dec80 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaim.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimInformer provides access to a shared informer and lister for -// ResourceClaims. +// ResourceClaims. Prefer using the type-safe variant (see [TypedResourceClaimInformer]). type ResourceClaimInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta1.ResourceClaimLister } +// TypedResourceClaimInformer provides access to a shared informer and lister for +// ResourceClaims, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimInformer. +type TypedResourceClaimInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimIndexInformer + Lister() resourcev1beta1.ResourceClaimLister +} + +// ResourceClaimIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaim] + +// ResourceClaimHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaim. +type ResourceClaimHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta1.ResourceClaim] + +// ResourceClaimDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaim. +type ResourceClaimDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta1.ResourceClaim] + +// ResourceClaimFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaim. +type ResourceClaimFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta1.ResourceClaim] + +// ResourceClaimIndexers is a specialization of [cache.TypedIndexers] for ResourceClaim. +type ResourceClaimIndexers = cache.TypedIndexers[*apiresourcev1beta1.ResourceClaim] + +// DeletedResourceClaim is a specialization of [cache.DeletedObject] for ResourceClaim. +type DeletedResourceClaim = cache.DeletedObject[*apiresourcev1beta1.ResourceClaim] + type resourceClaimInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimInformer struct { // NewResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformer]). func NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimInformer]). func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformerWithOptions]). func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta1", Resource: "resourceclaims"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaim](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta1.ResourceClaim{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimInformer) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaim](f.factory.InformerFor(&apiresourcev1beta1.ResourceClaim{}, f.defaultInformer)) } func (f *resourceClaimInformer) Lister() resourcev1beta1.ResourceClaimLister { return resourcev1beta1.NewResourceClaimLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimInformer converts an untyped informer into a TypedResourceClaimInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimInformer(informer ResourceClaimInformer) TypedResourceClaimInformer { + if informer, ok := informer.(TypedResourceClaimInformer); ok { + return informer + } + return &resourceClaimTypedInformerAdapter{informer} +} + +type resourceClaimTypedInformerAdapter struct { + ResourceClaimInformer +} + +func (a *resourceClaimTypedInformerAdapter) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaim](a.Informer()) +} + +// ToResourceClaimIndexInformer converts an untyped informer into a ResourceClaimIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// ResourceClaimIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimIndexInformer(informer cache.SharedIndexInformer) ResourceClaimIndexInformer { + if informer, ok := informer.(ResourceClaimIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaim](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaimtemplate.go index b6aa9cb91..ff0056710 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceclaimtemplate.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimTemplateInformer provides access to a shared informer and lister for -// ResourceClaimTemplates. +// ResourceClaimTemplates. Prefer using the type-safe variant (see [TypedResourceClaimTemplateInformer]). type ResourceClaimTemplateInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta1.ResourceClaimTemplateLister } +// TypedResourceClaimTemplateInformer provides access to a shared informer and lister for +// ResourceClaimTemplates, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimTemplateInformer. +type TypedResourceClaimTemplateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimTemplateIndexInformer + Lister() resourcev1beta1.ResourceClaimTemplateLister +} + +// ResourceClaimTemplateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimTemplateIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaimTemplate] + +// ResourceClaimTemplateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta1.ResourceClaimTemplate] + +// ResourceClaimTemplateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta1.ResourceClaimTemplate] + +// ResourceClaimTemplateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaimTemplate. +type ResourceClaimTemplateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta1.ResourceClaimTemplate] + +// ResourceClaimTemplateIndexers is a specialization of [cache.TypedIndexers] for ResourceClaimTemplate. +type ResourceClaimTemplateIndexers = cache.TypedIndexers[*apiresourcev1beta1.ResourceClaimTemplate] + +// DeletedResourceClaimTemplate is a specialization of [cache.DeletedObject] for ResourceClaimTemplate. +type DeletedResourceClaimTemplate = cache.DeletedObject[*apiresourcev1beta1.ResourceClaimTemplate] + type resourceClaimTemplateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimTemplateInformer struct { // NewResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformer]). func NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimTemplateInformer]). func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformerWithOptions]). func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimTemplateIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta1", Resource: "resourceclaimtemplates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaimTemplate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta1.ResourceClaimTemplate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimTemplateInformer) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaimTemplate](f.factory.InformerFor(&apiresourcev1beta1.ResourceClaimTemplate{}, f.defaultInformer)) } func (f *resourceClaimTemplateInformer) Lister() resourcev1beta1.ResourceClaimTemplateLister { return resourcev1beta1.NewResourceClaimTemplateLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimTemplateInformer converts an untyped informer into a TypedResourceClaimTemplateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimTemplateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimTemplateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimTemplateInformer(informer ResourceClaimTemplateInformer) TypedResourceClaimTemplateInformer { + if informer, ok := informer.(TypedResourceClaimTemplateInformer); ok { + return informer + } + return &resourceClaimTemplateTypedInformerAdapter{informer} +} + +type resourceClaimTemplateTypedInformerAdapter struct { + ResourceClaimTemplateInformer +} + +func (a *resourceClaimTemplateTypedInformerAdapter) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaimTemplate](a.Informer()) +} + +// ToResourceClaimTemplateIndexInformer converts an untyped informer into a ResourceClaimTemplateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// ResourceClaimTemplateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimTemplateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimTemplateIndexInformer(informer cache.SharedIndexInformer) ResourceClaimTemplateIndexInformer { + if informer, ok := informer.(ResourceClaimTemplateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceClaimTemplate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceslice.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceslice.go index 39e971aec..72cc3062b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta1/resourceslice.go @@ -34,12 +34,40 @@ import ( ) // ResourceSliceInformer provides access to a shared informer and lister for -// ResourceSlices. +// ResourceSlices. Prefer using the type-safe variant (see [TypedResourceSliceInformer]). type ResourceSliceInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta1.ResourceSliceLister } +// TypedResourceSliceInformer provides access to a shared informer and lister for +// ResourceSlices, including the type-safe TypedInformer variant. +// It is a superset of ResourceSliceInformer. +type TypedResourceSliceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceSliceIndexInformer + Lister() resourcev1beta1.ResourceSliceLister +} + +// ResourceSliceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceSliceIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta1.ResourceSlice] + +// ResourceSliceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceSlice. +type ResourceSliceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta1.ResourceSlice] + +// ResourceSliceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceSlice. +type ResourceSliceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta1.ResourceSlice] + +// ResourceSliceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceSlice. +type ResourceSliceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta1.ResourceSlice] + +// ResourceSliceIndexers is a specialization of [cache.TypedIndexers] for ResourceSlice. +type ResourceSliceIndexers = cache.TypedIndexers[*apiresourcev1beta1.ResourceSlice] + +// DeletedResourceSlice is a specialization of [cache.DeletedObject] for ResourceSlice. +type DeletedResourceSlice = cache.DeletedObject[*apiresourcev1beta1.ResourceSlice] + type resourceSliceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type resourceSliceInformer struct { // NewResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformer]). func NewResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceSliceInformer]). func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformerWithOptions]). func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, options) +} + +// NewTypedResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ResourceSliceIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta1", Resource: "resourceslices"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceSlice](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options in Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceSliceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta1.ResourceSlice{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceSliceInformer) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceSlice](f.factory.InformerFor(&apiresourcev1beta1.ResourceSlice{}, f.defaultInformer)) } func (f *resourceSliceInformer) Lister() resourcev1beta1.ResourceSliceLister { return resourcev1beta1.NewResourceSliceLister(f.Informer().GetIndexer()) } + +// ToTypedResourceSliceInformer converts an untyped informer into a TypedResourceSliceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// TypedResourceSliceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceSliceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceSliceInformer(informer ResourceSliceInformer) TypedResourceSliceInformer { + if informer, ok := informer.(TypedResourceSliceInformer); ok { + return informer + } + return &resourceSliceTypedInformerAdapter{informer} +} + +type resourceSliceTypedInformerAdapter struct { + ResourceSliceInformer +} + +func (a *resourceSliceTypedInformerAdapter) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceSlice](a.Informer()) +} + +// ToResourceSliceIndexInformer converts an untyped informer into a ResourceSliceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// ResourceSliceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceSliceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceSliceIndexInformer(informer cache.SharedIndexInformer) ResourceSliceIndexInformer { + if informer, ok := informer.(ResourceSliceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta1.ResourceSlice](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/deviceclass.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/deviceclass.go index d98b4d658..7108cba10 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/deviceclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/deviceclass.go @@ -34,12 +34,40 @@ import ( ) // DeviceClassInformer provides access to a shared informer and lister for -// DeviceClasses. +// DeviceClasses. Prefer using the type-safe variant (see [TypedDeviceClassInformer]). type DeviceClassInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta2.DeviceClassLister } +// TypedDeviceClassInformer provides access to a shared informer and lister for +// DeviceClasses, including the type-safe TypedInformer variant. +// It is a superset of DeviceClassInformer. +type TypedDeviceClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceClassIndexInformer + Lister() resourcev1beta2.DeviceClassLister +} + +// DeviceClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceClassIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta2.DeviceClass] + +// DeviceClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceClass. +type DeviceClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta2.DeviceClass] + +// DeviceClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceClass. +type DeviceClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta2.DeviceClass] + +// DeviceClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceClass. +type DeviceClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta2.DeviceClass] + +// DeviceClassIndexers is a specialization of [cache.TypedIndexers] for DeviceClass. +type DeviceClassIndexers = cache.TypedIndexers[*apiresourcev1beta2.DeviceClass] + +// DeletedDeviceClass is a specialization of [cache.DeletedObject] for DeviceClass. +type DeletedDeviceClass = cache.DeletedObject[*apiresourcev1beta2.DeviceClass] + type deviceClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type deviceClassInformer struct { // NewDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformer]). func NewDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeviceClassInformer constructs a new informer for DeviceClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceClassInformer]). func NewFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceClassInformer constructs a new informer for DeviceClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceClassIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceClassInformerWithOptions]). func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceClassInformerWithOptions(client, options) +} + +// NewTypedDeviceClassInformerWithOptions constructs a new informer for DeviceClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceClassIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta2", Resource: "deviceclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewDeviceClassInformerWithOptions(client kubernetes.Interface, options inte Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deviceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeviceClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deviceClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta2.DeviceClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deviceClassInformer) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceClass](f.factory.InformerFor(&apiresourcev1beta2.DeviceClass{}, f.defaultInformer)) } func (f *deviceClassInformer) Lister() resourcev1beta2.DeviceClassLister { return resourcev1beta2.NewDeviceClassLister(f.Informer().GetIndexer()) } + +// ToTypedDeviceClassInformer converts an untyped informer into a TypedDeviceClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// TypedDeviceClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceClassInformer(informer DeviceClassInformer) TypedDeviceClassInformer { + if informer, ok := informer.(TypedDeviceClassInformer); ok { + return informer + } + return &deviceClassTypedInformerAdapter{informer} +} + +type deviceClassTypedInformerAdapter struct { + DeviceClassInformer +} + +func (a *deviceClassTypedInformerAdapter) TypedInformer() DeviceClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceClass](a.Informer()) +} + +// ToDeviceClassIndexInformer converts an untyped informer into a DeviceClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceClass. If that is not the case, calling type-safe methods of the returned +// DeviceClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceClassIndexInformer(informer cache.SharedIndexInformer) DeviceClassIndexInformer { + if informer, ok := informer.(DeviceClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/devicetaintrule.go index 328a9c393..7bc04a161 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/devicetaintrule.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/devicetaintrule.go @@ -34,12 +34,40 @@ import ( ) // DeviceTaintRuleInformer provides access to a shared informer and lister for -// DeviceTaintRules. +// DeviceTaintRules. Prefer using the type-safe variant (see [TypedDeviceTaintRuleInformer]). type DeviceTaintRuleInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta2.DeviceTaintRuleLister } +// TypedDeviceTaintRuleInformer provides access to a shared informer and lister for +// DeviceTaintRules, including the type-safe TypedInformer variant. +// It is a superset of DeviceTaintRuleInformer. +type TypedDeviceTaintRuleInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() DeviceTaintRuleIndexInformer + Lister() resourcev1beta2.DeviceTaintRuleLister +} + +// DeviceTaintRuleIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type DeviceTaintRuleIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta2.DeviceTaintRule] + +// DeviceTaintRuleHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for DeviceTaintRule. +type DeviceTaintRuleHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta2.DeviceTaintRule] + +// DeviceTaintRuleDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for DeviceTaintRule. +type DeviceTaintRuleDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta2.DeviceTaintRule] + +// DeviceTaintRuleFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for DeviceTaintRule. +type DeviceTaintRuleFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta2.DeviceTaintRule] + +// DeviceTaintRuleIndexers is a specialization of [cache.TypedIndexers] for DeviceTaintRule. +type DeviceTaintRuleIndexers = cache.TypedIndexers[*apiresourcev1beta2.DeviceTaintRule] + +// DeletedDeviceTaintRule is a specialization of [cache.DeletedObject] for DeviceTaintRule. +type DeletedDeviceTaintRule = cache.DeletedObject[*apiresourcev1beta2.DeviceTaintRule] + type deviceTaintRuleInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type deviceTaintRuleInformer struct { // NewDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformer]). func NewDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredDeviceTaintRuleInformer]). func NewFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredDeviceTaintRuleInformer constructs a new informer for DeviceTaintRule type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredDeviceTaintRuleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers DeviceTaintRuleIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) DeviceTaintRuleIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedDeviceTaintRuleInformerWithOptions]). func NewDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedDeviceTaintRuleInformerWithOptions(client, options) +} + +// NewTypedDeviceTaintRuleInformerWithOptions constructs a new informer for DeviceTaintRule type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) DeviceTaintRuleIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta2", Resource: "devicetaintrules"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceTaintRule](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewDeviceTaintRuleInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *deviceTaintRuleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedDeviceTaintRuleInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *deviceTaintRuleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta2.DeviceTaintRule{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *deviceTaintRuleInformer) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceTaintRule](f.factory.InformerFor(&apiresourcev1beta2.DeviceTaintRule{}, f.defaultInformer)) } func (f *deviceTaintRuleInformer) Lister() resourcev1beta2.DeviceTaintRuleLister { return resourcev1beta2.NewDeviceTaintRuleLister(f.Informer().GetIndexer()) } + +// ToTypedDeviceTaintRuleInformer converts an untyped informer into a TypedDeviceTaintRuleInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// TypedDeviceTaintRuleInformer leads to runtime panics. A safer alternative is to pass +// around a TypedDeviceTaintRuleInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedDeviceTaintRuleInformer(informer DeviceTaintRuleInformer) TypedDeviceTaintRuleInformer { + if informer, ok := informer.(TypedDeviceTaintRuleInformer); ok { + return informer + } + return &deviceTaintRuleTypedInformerAdapter{informer} +} + +type deviceTaintRuleTypedInformerAdapter struct { + DeviceTaintRuleInformer +} + +func (a *deviceTaintRuleTypedInformerAdapter) TypedInformer() DeviceTaintRuleIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceTaintRule](a.Informer()) +} + +// ToDeviceTaintRuleIndexInformer converts an untyped informer into a DeviceTaintRuleIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *DeviceTaintRule. If that is not the case, calling type-safe methods of the returned +// DeviceTaintRuleIndexInformer leads to runtime panics. A safer alternative is to pass +// around a DeviceTaintRuleIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToDeviceTaintRuleIndexInformer(informer cache.SharedIndexInformer) DeviceTaintRuleIndexInformer { + if informer, ok := informer.(DeviceTaintRuleIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.DeviceTaintRule](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/interface.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/interface.go index a05e518e2..29ac4b38f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/interface.go @@ -25,15 +25,15 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // DeviceClasses returns a DeviceClassInformer. - DeviceClasses() DeviceClassInformer + DeviceClasses() TypedDeviceClassInformer // DeviceTaintRules returns a DeviceTaintRuleInformer. - DeviceTaintRules() DeviceTaintRuleInformer + DeviceTaintRules() TypedDeviceTaintRuleInformer // ResourceClaims returns a ResourceClaimInformer. - ResourceClaims() ResourceClaimInformer + ResourceClaims() TypedResourceClaimInformer // ResourceClaimTemplates returns a ResourceClaimTemplateInformer. - ResourceClaimTemplates() ResourceClaimTemplateInformer + ResourceClaimTemplates() TypedResourceClaimTemplateInformer // ResourceSlices returns a ResourceSliceInformer. - ResourceSlices() ResourceSliceInformer + ResourceSlices() TypedResourceSliceInformer } type version struct { @@ -47,27 +47,27 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// DeviceClasses returns a DeviceClassInformer. -func (v *version) DeviceClasses() DeviceClassInformer { +// DeviceClasses returns a TypedDeviceClassInformer. +func (v *version) DeviceClasses() TypedDeviceClassInformer { return &deviceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// DeviceTaintRules returns a DeviceTaintRuleInformer. -func (v *version) DeviceTaintRules() DeviceTaintRuleInformer { +// DeviceTaintRules returns a TypedDeviceTaintRuleInformer. +func (v *version) DeviceTaintRules() TypedDeviceTaintRuleInformer { return &deviceTaintRuleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// ResourceClaims returns a ResourceClaimInformer. -func (v *version) ResourceClaims() ResourceClaimInformer { +// ResourceClaims returns a TypedResourceClaimInformer. +func (v *version) ResourceClaims() TypedResourceClaimInformer { return &resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceClaimTemplates returns a ResourceClaimTemplateInformer. -func (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer { +// ResourceClaimTemplates returns a TypedResourceClaimTemplateInformer. +func (v *version) ResourceClaimTemplates() TypedResourceClaimTemplateInformer { return &resourceClaimTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ResourceSlices returns a ResourceSliceInformer. -func (v *version) ResourceSlices() ResourceSliceInformer { +// ResourceSlices returns a TypedResourceSliceInformer. +func (v *version) ResourceSlices() TypedResourceSliceInformer { return &resourceSliceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaim.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaim.go index 61dc6db17..afea5d0d9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaim.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaim.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimInformer provides access to a shared informer and lister for -// ResourceClaims. +// ResourceClaims. Prefer using the type-safe variant (see [TypedResourceClaimInformer]). type ResourceClaimInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta2.ResourceClaimLister } +// TypedResourceClaimInformer provides access to a shared informer and lister for +// ResourceClaims, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimInformer. +type TypedResourceClaimInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimIndexInformer + Lister() resourcev1beta2.ResourceClaimLister +} + +// ResourceClaimIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaim] + +// ResourceClaimHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaim. +type ResourceClaimHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta2.ResourceClaim] + +// ResourceClaimDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaim. +type ResourceClaimDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta2.ResourceClaim] + +// ResourceClaimFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaim. +type ResourceClaimFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta2.ResourceClaim] + +// ResourceClaimIndexers is a specialization of [cache.TypedIndexers] for ResourceClaim. +type ResourceClaimIndexers = cache.TypedIndexers[*apiresourcev1beta2.ResourceClaim] + +// DeletedResourceClaim is a specialization of [cache.DeletedObject] for ResourceClaim. +type DeletedResourceClaim = cache.DeletedObject[*apiresourcev1beta2.ResourceClaim] + type resourceClaimInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimInformer struct { // NewResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformer]). func NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimInformer]). func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimInformer constructs a new informer for ResourceClaim type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimInformerWithOptions]). func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimInformerWithOptions constructs a new informer for ResourceClaim type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta2", Resource: "resourceclaims"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaim](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimInformerWithOptions(client kubernetes.Interface, namespace Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta2.ResourceClaim{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimInformer) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaim](f.factory.InformerFor(&apiresourcev1beta2.ResourceClaim{}, f.defaultInformer)) } func (f *resourceClaimInformer) Lister() resourcev1beta2.ResourceClaimLister { return resourcev1beta2.NewResourceClaimLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimInformer converts an untyped informer into a TypedResourceClaimInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimInformer(informer ResourceClaimInformer) TypedResourceClaimInformer { + if informer, ok := informer.(TypedResourceClaimInformer); ok { + return informer + } + return &resourceClaimTypedInformerAdapter{informer} +} + +type resourceClaimTypedInformerAdapter struct { + ResourceClaimInformer +} + +func (a *resourceClaimTypedInformerAdapter) TypedInformer() ResourceClaimIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaim](a.Informer()) +} + +// ToResourceClaimIndexInformer converts an untyped informer into a ResourceClaimIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaim. If that is not the case, calling type-safe methods of the returned +// ResourceClaimIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimIndexInformer(informer cache.SharedIndexInformer) ResourceClaimIndexInformer { + if informer, ok := informer.(ResourceClaimIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaim](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaimtemplate.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaimtemplate.go index ee22977a3..c7ee33df6 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaimtemplate.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceclaimtemplate.go @@ -34,12 +34,40 @@ import ( ) // ResourceClaimTemplateInformer provides access to a shared informer and lister for -// ResourceClaimTemplates. +// ResourceClaimTemplates. Prefer using the type-safe variant (see [TypedResourceClaimTemplateInformer]). type ResourceClaimTemplateInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta2.ResourceClaimTemplateLister } +// TypedResourceClaimTemplateInformer provides access to a shared informer and lister for +// ResourceClaimTemplates, including the type-safe TypedInformer variant. +// It is a superset of ResourceClaimTemplateInformer. +type TypedResourceClaimTemplateInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceClaimTemplateIndexInformer + Lister() resourcev1beta2.ResourceClaimTemplateLister +} + +// ResourceClaimTemplateIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceClaimTemplateIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaimTemplate] + +// ResourceClaimTemplateHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta2.ResourceClaimTemplate] + +// ResourceClaimTemplateDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceClaimTemplate. +type ResourceClaimTemplateDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta2.ResourceClaimTemplate] + +// ResourceClaimTemplateFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceClaimTemplate. +type ResourceClaimTemplateFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta2.ResourceClaimTemplate] + +// ResourceClaimTemplateIndexers is a specialization of [cache.TypedIndexers] for ResourceClaimTemplate. +type ResourceClaimTemplateIndexers = cache.TypedIndexers[*apiresourcev1beta2.ResourceClaimTemplate] + +// DeletedResourceClaimTemplate is a specialization of [cache.DeletedObject] for ResourceClaimTemplate. +type DeletedResourceClaimTemplate = cache.DeletedObject[*apiresourcev1beta2.ResourceClaimTemplate] + type resourceClaimTemplateInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type resourceClaimTemplateInformer struct { // NewResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformer]). func NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceClaimTemplateInformer]). func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers ResourceClaimTemplateIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceClaimTemplateIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceClaimTemplateInformerWithOptions]). func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceClaimTemplateInformerWithOptions(client, namespace, options) +} + +// NewTypedResourceClaimTemplateInformerWithOptions constructs a new informer for ResourceClaimTemplate type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) ResourceClaimTemplateIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta2", Resource: "resourceclaimtemplates"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaimTemplate](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewResourceClaimTemplateInformerWithOptions(client kubernetes.Interface, na Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceClaimTemplateInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta2.ResourceClaimTemplate{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceClaimTemplateInformer) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaimTemplate](f.factory.InformerFor(&apiresourcev1beta2.ResourceClaimTemplate{}, f.defaultInformer)) } func (f *resourceClaimTemplateInformer) Lister() resourcev1beta2.ResourceClaimTemplateLister { return resourcev1beta2.NewResourceClaimTemplateLister(f.Informer().GetIndexer()) } + +// ToTypedResourceClaimTemplateInformer converts an untyped informer into a TypedResourceClaimTemplateInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// TypedResourceClaimTemplateInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceClaimTemplateInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceClaimTemplateInformer(informer ResourceClaimTemplateInformer) TypedResourceClaimTemplateInformer { + if informer, ok := informer.(TypedResourceClaimTemplateInformer); ok { + return informer + } + return &resourceClaimTemplateTypedInformerAdapter{informer} +} + +type resourceClaimTemplateTypedInformerAdapter struct { + ResourceClaimTemplateInformer +} + +func (a *resourceClaimTemplateTypedInformerAdapter) TypedInformer() ResourceClaimTemplateIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaimTemplate](a.Informer()) +} + +// ToResourceClaimTemplateIndexInformer converts an untyped informer into a ResourceClaimTemplateIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceClaimTemplate. If that is not the case, calling type-safe methods of the returned +// ResourceClaimTemplateIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceClaimTemplateIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceClaimTemplateIndexInformer(informer cache.SharedIndexInformer) ResourceClaimTemplateIndexInformer { + if informer, ok := informer.(ResourceClaimTemplateIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceClaimTemplate](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceslice.go b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceslice.go index 7a8027886..248ad4478 100644 --- a/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceslice.go +++ b/constraint/vendor/k8s.io/client-go/informers/resource/v1beta2/resourceslice.go @@ -34,12 +34,40 @@ import ( ) // ResourceSliceInformer provides access to a shared informer and lister for -// ResourceSlices. +// ResourceSlices. Prefer using the type-safe variant (see [TypedResourceSliceInformer]). type ResourceSliceInformer interface { Informer() cache.SharedIndexInformer Lister() resourcev1beta2.ResourceSliceLister } +// TypedResourceSliceInformer provides access to a shared informer and lister for +// ResourceSlices, including the type-safe TypedInformer variant. +// It is a superset of ResourceSliceInformer. +type TypedResourceSliceInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() ResourceSliceIndexInformer + Lister() resourcev1beta2.ResourceSliceLister +} + +// ResourceSliceIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type ResourceSliceIndexInformer cache.TypedSharedIndexInformer[*apiresourcev1beta2.ResourceSlice] + +// ResourceSliceHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for ResourceSlice. +type ResourceSliceHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apiresourcev1beta2.ResourceSlice] + +// ResourceSliceDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for ResourceSlice. +type ResourceSliceDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apiresourcev1beta2.ResourceSlice] + +// ResourceSliceFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for ResourceSlice. +type ResourceSliceFilteringHandler = cache.TypedFilteringResourceEventHandler[*apiresourcev1beta2.ResourceSlice] + +// ResourceSliceIndexers is a specialization of [cache.TypedIndexers] for ResourceSlice. +type ResourceSliceIndexers = cache.TypedIndexers[*apiresourcev1beta2.ResourceSlice] + +// DeletedResourceSlice is a specialization of [cache.DeletedObject] for ResourceSlice. +type DeletedResourceSlice = cache.DeletedObject[*apiresourcev1beta2.ResourceSlice] + type resourceSliceInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type resourceSliceInformer struct { // NewResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformer]). func NewResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredResourceSliceInformer]). func NewFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredResourceSliceInformer constructs a new informer for ResourceSlice type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredResourceSliceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers ResourceSliceIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) ResourceSliceIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedResourceSliceInformerWithOptions]). func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedResourceSliceInformerWithOptions(client, options) +} + +// NewTypedResourceSliceInformerWithOptions constructs a new informer for ResourceSlice type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedResourceSliceInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) ResourceSliceIndexInformer { gvr := schema.GroupVersionResource{Group: "resource.k8s.io", Version: "v1beta2", Resource: "resourceslices"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceSlice](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewResourceSliceInformerWithOptions(client kubernetes.Interface, options in Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *resourceSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedResourceSliceInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *resourceSliceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiresourcev1beta2.ResourceSlice{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *resourceSliceInformer) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceSlice](f.factory.InformerFor(&apiresourcev1beta2.ResourceSlice{}, f.defaultInformer)) } func (f *resourceSliceInformer) Lister() resourcev1beta2.ResourceSliceLister { return resourcev1beta2.NewResourceSliceLister(f.Informer().GetIndexer()) } + +// ToTypedResourceSliceInformer converts an untyped informer into a TypedResourceSliceInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// TypedResourceSliceInformer leads to runtime panics. A safer alternative is to pass +// around a TypedResourceSliceInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedResourceSliceInformer(informer ResourceSliceInformer) TypedResourceSliceInformer { + if informer, ok := informer.(TypedResourceSliceInformer); ok { + return informer + } + return &resourceSliceTypedInformerAdapter{informer} +} + +type resourceSliceTypedInformerAdapter struct { + ResourceSliceInformer +} + +func (a *resourceSliceTypedInformerAdapter) TypedInformer() ResourceSliceIndexInformer { + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceSlice](a.Informer()) +} + +// ToResourceSliceIndexInformer converts an untyped informer into a ResourceSliceIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *ResourceSlice. If that is not the case, calling type-safe methods of the returned +// ResourceSliceIndexInformer leads to runtime panics. A safer alternative is to pass +// around a ResourceSliceIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToResourceSliceIndexInformer(informer cache.SharedIndexInformer) ResourceSliceIndexInformer { + if informer, ok := informer.(ResourceSliceIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apiresourcev1beta2.ResourceSlice](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/interface.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/interface.go index e55a8410d..bd66d6c3a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/interface.go @@ -21,7 +21,7 @@ package scheduling import ( internalinterfaces "k8s.io/client-go/informers/internalinterfaces" v1 "k8s.io/client-go/informers/scheduling/v1" - v1alpha2 "k8s.io/client-go/informers/scheduling/v1alpha2" + v1alpha3 "k8s.io/client-go/informers/scheduling/v1alpha3" v1beta1 "k8s.io/client-go/informers/scheduling/v1beta1" ) @@ -29,8 +29,8 @@ import ( type Interface interface { // V1 provides access to shared informers for resources in V1. V1() v1.Interface - // V1alpha2 provides access to shared informers for resources in V1alpha2. - V1alpha2() v1alpha2.Interface + // V1alpha3 provides access to shared informers for resources in V1alpha3. + V1alpha3() v1alpha3.Interface // V1beta1 provides access to shared informers for resources in V1beta1. V1beta1() v1beta1.Interface } @@ -51,9 +51,9 @@ func (g *group) V1() v1.Interface { return v1.New(g.factory, g.namespace, g.tweakListOptions) } -// V1alpha2 returns a new v1alpha2.Interface. -func (g *group) V1alpha2() v1alpha2.Interface { - return v1alpha2.New(g.factory, g.namespace, g.tweakListOptions) +// V1alpha3 returns a new v1alpha3.Interface. +func (g *group) V1alpha3() v1alpha3.Interface { + return v1alpha3.New(g.factory, g.namespace, g.tweakListOptions) } // V1beta1 returns a new v1beta1.Interface. diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/interface.go index fd7931f34..fd3b20d96 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // PriorityClasses returns a PriorityClassInformer. - PriorityClasses() PriorityClassInformer + PriorityClasses() TypedPriorityClassInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// PriorityClasses returns a PriorityClassInformer. -func (v *version) PriorityClasses() PriorityClassInformer { +// PriorityClasses returns a TypedPriorityClassInformer. +func (v *version) PriorityClasses() TypedPriorityClassInformer { return &priorityClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/priorityclass.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/priorityclass.go index f1d18f2a0..8b4daf5ca 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/priorityclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1/priorityclass.go @@ -34,12 +34,40 @@ import ( ) // PriorityClassInformer provides access to a shared informer and lister for -// PriorityClasses. +// PriorityClasses. Prefer using the type-safe variant (see [TypedPriorityClassInformer]). type PriorityClassInformer interface { Informer() cache.SharedIndexInformer Lister() schedulingv1.PriorityClassLister } +// TypedPriorityClassInformer provides access to a shared informer and lister for +// PriorityClasses, including the type-safe TypedInformer variant. +// It is a superset of PriorityClassInformer. +type TypedPriorityClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityClassIndexInformer + Lister() schedulingv1.PriorityClassLister +} + +// PriorityClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityClassIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1.PriorityClass] + +// PriorityClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityClass. +type PriorityClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1.PriorityClass] + +// PriorityClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityClass. +type PriorityClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1.PriorityClass] + +// PriorityClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityClass. +type PriorityClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1.PriorityClass] + +// PriorityClassIndexers is a specialization of [cache.TypedIndexers] for PriorityClass. +type PriorityClassIndexers = cache.TypedIndexers[*apischedulingv1.PriorityClass] + +// DeletedPriorityClass is a specialization of [cache.DeletedObject] for PriorityClass. +type DeletedPriorityClass = cache.DeletedObject[*apischedulingv1.PriorityClass] + type priorityClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityClassInformer struct { // NewPriorityClassInformer constructs a new informer for PriorityClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityClassInformer]). func NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityClassInformer constructs a new informer for PriorityClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityClassIndexers) PriorityClassIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityClassInformer constructs a new informer for PriorityClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityClassInformer]). func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityClassInformer constructs a new informer for PriorityClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityClassIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityClassInformerWithOptions constructs a new informer for PriorityClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityClassInformerWithOptions]). func NewPriorityClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, options) +} + +// NewTypedPriorityClassInformerWithOptions constructs a new informer for PriorityClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityClassIndexInformer { gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1", Resource: "priorityclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apischedulingv1.PriorityClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityClassInformerWithOptions(client kubernetes.Interface, options in Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apischedulingv1.PriorityClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityClassInformer) TypedInformer() PriorityClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1.PriorityClass](f.factory.InformerFor(&apischedulingv1.PriorityClass{}, f.defaultInformer)) } func (f *priorityClassInformer) Lister() schedulingv1.PriorityClassLister { return schedulingv1.NewPriorityClassLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityClassInformer converts an untyped informer into a TypedPriorityClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityClass. If that is not the case, calling type-safe methods of the returned +// TypedPriorityClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityClassInformer(informer PriorityClassInformer) TypedPriorityClassInformer { + if informer, ok := informer.(TypedPriorityClassInformer); ok { + return informer + } + return &priorityClassTypedInformerAdapter{informer} +} + +type priorityClassTypedInformerAdapter struct { + PriorityClassInformer +} + +func (a *priorityClassTypedInformerAdapter) TypedInformer() PriorityClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1.PriorityClass](a.Informer()) +} + +// ToPriorityClassIndexInformer converts an untyped informer into a PriorityClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityClass. If that is not the case, calling type-safe methods of the returned +// PriorityClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityClassIndexInformer(informer cache.SharedIndexInformer) PriorityClassIndexInformer { + if informer, ok := informer.(PriorityClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1.PriorityClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/podgroup.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/podgroup.go deleted file mode 100644 index 5f39858c6..000000000 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/podgroup.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apischedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - watch "k8s.io/apimachinery/pkg/watch" - internalinterfaces "k8s.io/client-go/informers/internalinterfaces" - kubernetes "k8s.io/client-go/kubernetes" - schedulingv1alpha2 "k8s.io/client-go/listers/scheduling/v1alpha2" - cache "k8s.io/client-go/tools/cache" -) - -// PodGroupInformer provides access to a shared informer and lister for -// PodGroups. -type PodGroupInformer interface { - Informer() cache.SharedIndexInformer - Lister() schedulingv1alpha2.PodGroupLister -} - -type podGroupInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewPodGroupInformer constructs a new informer for PodGroup type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) -} - -// NewFilteredPodGroupInformer constructs a new informer for PodGroup type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) -} - -// NewPodGroupInformerWithOptions constructs a new informer for PodGroup type with additional options. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewPodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { - gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1alpha2", Resource: "podgroups"} - identifier := options.InformerName.WithResource(gvr) - tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().PodGroups(namespace).List(context.Background(), opts) - }, - WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().PodGroups(namespace).Watch(context.Background(), opts) - }, - ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().PodGroups(namespace).List(ctx, opts) - }, - WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().PodGroups(namespace).Watch(ctx, opts) - }, - }, client), - &apischedulingv1alpha2.PodGroup{}, - cache.SharedIndexInformerOptions{ - ResyncPeriod: options.ResyncPeriod, - Indexers: options.Indexers, - Identifier: identifier, - }, - ) -} - -func (f *podGroupInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPodGroupInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) -} - -func (f *podGroupInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apischedulingv1alpha2.PodGroup{}, f.defaultInformer) -} - -func (f *podGroupInformer) Lister() schedulingv1alpha2.PodGroupLister { - return schedulingv1alpha2.NewPodGroupLister(f.Informer().GetIndexer()) -} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/workload.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/workload.go deleted file mode 100644 index ffe2f4ece..000000000 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/workload.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apischedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - watch "k8s.io/apimachinery/pkg/watch" - internalinterfaces "k8s.io/client-go/informers/internalinterfaces" - kubernetes "k8s.io/client-go/kubernetes" - schedulingv1alpha2 "k8s.io/client-go/listers/scheduling/v1alpha2" - cache "k8s.io/client-go/tools/cache" -) - -// WorkloadInformer provides access to a shared informer and lister for -// Workloads. -type WorkloadInformer interface { - Informer() cache.SharedIndexInformer - Lister() schedulingv1alpha2.WorkloadLister -} - -type workloadInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewWorkloadInformer constructs a new informer for Workload type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) -} - -// NewFilteredWorkloadInformer constructs a new informer for Workload type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) -} - -// NewWorkloadInformerWithOptions constructs a new informer for Workload type with additional options. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewWorkloadInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { - gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1alpha2", Resource: "workloads"} - identifier := options.InformerName.WithResource(gvr) - tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().Workloads(namespace).List(context.Background(), opts) - }, - WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().Workloads(namespace).Watch(context.Background(), opts) - }, - ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().Workloads(namespace).List(ctx, opts) - }, - WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&opts) - } - return client.SchedulingV1alpha2().Workloads(namespace).Watch(ctx, opts) - }, - }, client), - &apischedulingv1alpha2.Workload{}, - cache.SharedIndexInformerOptions{ - ResyncPeriod: options.ResyncPeriod, - Indexers: options.Indexers, - Identifier: identifier, - }, - ) -} - -func (f *workloadInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewWorkloadInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) -} - -func (f *workloadInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apischedulingv1alpha2.Workload{}, f.defaultInformer) -} - -func (f *workloadInformer) Lister() schedulingv1alpha2.WorkloadLister { - return schedulingv1alpha2.NewWorkloadLister(f.Informer().GetIndexer()) -} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/compositepodgroup.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/compositepodgroup.go new file mode 100644 index 000000000..9556755dc --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/compositepodgroup.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + time "time" + + apischedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + schedulingv1alpha3 "k8s.io/client-go/listers/scheduling/v1alpha3" + cache "k8s.io/client-go/tools/cache" +) + +// CompositePodGroupInformer provides access to a shared informer and lister for +// CompositePodGroups. Prefer using the type-safe variant (see [TypedCompositePodGroupInformer]). +type CompositePodGroupInformer interface { + Informer() cache.SharedIndexInformer + Lister() schedulingv1alpha3.CompositePodGroupLister +} + +// TypedCompositePodGroupInformer provides access to a shared informer and lister for +// CompositePodGroups, including the type-safe TypedInformer variant. +// It is a superset of CompositePodGroupInformer. +type TypedCompositePodGroupInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CompositePodGroupIndexInformer + Lister() schedulingv1alpha3.CompositePodGroupLister +} + +// CompositePodGroupIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CompositePodGroupIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1alpha3.CompositePodGroup] + +// CompositePodGroupHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CompositePodGroup. +type CompositePodGroupHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1alpha3.CompositePodGroup] + +// CompositePodGroupDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CompositePodGroup. +type CompositePodGroupDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1alpha3.CompositePodGroup] + +// CompositePodGroupFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CompositePodGroup. +type CompositePodGroupFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1alpha3.CompositePodGroup] + +// CompositePodGroupIndexers is a specialization of [cache.TypedIndexers] for CompositePodGroup. +type CompositePodGroupIndexers = cache.TypedIndexers[*apischedulingv1alpha3.CompositePodGroup] + +// DeletedCompositePodGroup is a specialization of [cache.DeletedObject] for CompositePodGroup. +type DeletedCompositePodGroup = cache.DeletedObject[*apischedulingv1alpha3.CompositePodGroup] + +type compositePodGroupInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewCompositePodGroupInformer constructs a new informer for CompositePodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCompositePodGroupInformer]). +func NewCompositePodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewCompositePodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedCompositePodGroupInformer constructs a new informer for CompositePodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCompositePodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CompositePodGroupIndexers) CompositePodGroupIndexInformer { + return NewTypedCompositePodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredCompositePodGroupInformer constructs a new informer for CompositePodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCompositePodGroupInformer]). +func NewFilteredCompositePodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedCompositePodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCompositePodGroupInformer constructs a new informer for CompositePodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCompositePodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CompositePodGroupIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CompositePodGroupIndexInformer { + return NewTypedCompositePodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewCompositePodGroupInformerWithOptions constructs a new informer for CompositePodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCompositePodGroupInformerWithOptions]). +func NewCompositePodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCompositePodGroupInformerWithOptions(client, namespace, options) +} + +// NewTypedCompositePodGroupInformerWithOptions constructs a new informer for CompositePodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCompositePodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CompositePodGroupIndexInformer { + gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1alpha3", Resource: "compositepodgroups"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.CompositePodGroup](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().CompositePodGroups(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().CompositePodGroups(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().CompositePodGroups(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().CompositePodGroups(namespace).Watch(ctx, opts) + }, + }, client), + &apischedulingv1alpha3.CompositePodGroup{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *compositePodGroupInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedCompositePodGroupInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *compositePodGroupInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *compositePodGroupInformer) TypedInformer() CompositePodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.CompositePodGroup](f.factory.InformerFor(&apischedulingv1alpha3.CompositePodGroup{}, f.defaultInformer)) +} + +func (f *compositePodGroupInformer) Lister() schedulingv1alpha3.CompositePodGroupLister { + return schedulingv1alpha3.NewCompositePodGroupLister(f.Informer().GetIndexer()) +} + +// ToTypedCompositePodGroupInformer converts an untyped informer into a TypedCompositePodGroupInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CompositePodGroup. If that is not the case, calling type-safe methods of the returned +// TypedCompositePodGroupInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCompositePodGroupInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCompositePodGroupInformer(informer CompositePodGroupInformer) TypedCompositePodGroupInformer { + if informer, ok := informer.(TypedCompositePodGroupInformer); ok { + return informer + } + return &compositePodGroupTypedInformerAdapter{informer} +} + +type compositePodGroupTypedInformerAdapter struct { + CompositePodGroupInformer +} + +func (a *compositePodGroupTypedInformerAdapter) TypedInformer() CompositePodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.CompositePodGroup](a.Informer()) +} + +// ToCompositePodGroupIndexInformer converts an untyped informer into a CompositePodGroupIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CompositePodGroup. If that is not the case, calling type-safe methods of the returned +// CompositePodGroupIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CompositePodGroupIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCompositePodGroupIndexInformer(informer cache.SharedIndexInformer) CompositePodGroupIndexInformer { + if informer, ok := informer.(CompositePodGroupIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.CompositePodGroup](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/interface.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/interface.go similarity index 70% rename from constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/interface.go rename to constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/interface.go index 8edc498b6..1471eb3d5 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha2/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/interface.go @@ -16,7 +16,7 @@ limitations under the License. // Code generated by informer-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( internalinterfaces "k8s.io/client-go/informers/internalinterfaces" @@ -24,10 +24,12 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // CompositePodGroups returns a CompositePodGroupInformer. + CompositePodGroups() TypedCompositePodGroupInformer // PodGroups returns a PodGroupInformer. - PodGroups() PodGroupInformer + PodGroups() TypedPodGroupInformer // Workloads returns a WorkloadInformer. - Workloads() WorkloadInformer + Workloads() TypedWorkloadInformer } type version struct { @@ -41,12 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// PodGroups returns a PodGroupInformer. -func (v *version) PodGroups() PodGroupInformer { +// CompositePodGroups returns a TypedCompositePodGroupInformer. +func (v *version) CompositePodGroups() TypedCompositePodGroupInformer { + return &compositePodGroupInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// PodGroups returns a TypedPodGroupInformer. +func (v *version) PodGroups() TypedPodGroupInformer { return &podGroupInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// Workloads returns a WorkloadInformer. -func (v *version) Workloads() WorkloadInformer { +// Workloads returns a TypedWorkloadInformer. +func (v *version) Workloads() TypedWorkloadInformer { return &workloadInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/podgroup.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/podgroup.go new file mode 100644 index 000000000..3b0c4d831 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/podgroup.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + time "time" + + apischedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + schedulingv1alpha3 "k8s.io/client-go/listers/scheduling/v1alpha3" + cache "k8s.io/client-go/tools/cache" +) + +// PodGroupInformer provides access to a shared informer and lister for +// PodGroups. Prefer using the type-safe variant (see [TypedPodGroupInformer]). +type PodGroupInformer interface { + Informer() cache.SharedIndexInformer + Lister() schedulingv1alpha3.PodGroupLister +} + +// TypedPodGroupInformer provides access to a shared informer and lister for +// PodGroups, including the type-safe TypedInformer variant. +// It is a superset of PodGroupInformer. +type TypedPodGroupInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodGroupIndexInformer + Lister() schedulingv1alpha3.PodGroupLister +} + +// PodGroupIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodGroupIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1alpha3.PodGroup] + +// PodGroupHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodGroup. +type PodGroupHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1alpha3.PodGroup] + +// PodGroupDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodGroup. +type PodGroupDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1alpha3.PodGroup] + +// PodGroupFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodGroup. +type PodGroupFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1alpha3.PodGroup] + +// PodGroupIndexers is a specialization of [cache.TypedIndexers] for PodGroup. +type PodGroupIndexers = cache.TypedIndexers[*apischedulingv1alpha3.PodGroup] + +// DeletedPodGroup is a specialization of [cache.DeletedObject] for PodGroup. +type DeletedPodGroup = cache.DeletedObject[*apischedulingv1alpha3.PodGroup] + +type podGroupInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodGroupInformer]). +func NewPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodGroupIndexers) PodGroupIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodGroupInformer]). +func NewFilteredPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodGroupIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodGroupIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewPodGroupInformerWithOptions constructs a new informer for PodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodGroupInformerWithOptions]). +func NewPodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, options) +} + +// NewTypedPodGroupInformerWithOptions constructs a new informer for PodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodGroupIndexInformer { + gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1alpha3", Resource: "podgroups"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.PodGroup](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().PodGroups(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().PodGroups(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().PodGroups(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().PodGroups(namespace).Watch(ctx, opts) + }, + }, client), + &apischedulingv1alpha3.PodGroup{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *podGroupInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *podGroupInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *podGroupInformer) TypedInformer() PodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.PodGroup](f.factory.InformerFor(&apischedulingv1alpha3.PodGroup{}, f.defaultInformer)) +} + +func (f *podGroupInformer) Lister() schedulingv1alpha3.PodGroupLister { + return schedulingv1alpha3.NewPodGroupLister(f.Informer().GetIndexer()) +} + +// ToTypedPodGroupInformer converts an untyped informer into a TypedPodGroupInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodGroup. If that is not the case, calling type-safe methods of the returned +// TypedPodGroupInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodGroupInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodGroupInformer(informer PodGroupInformer) TypedPodGroupInformer { + if informer, ok := informer.(TypedPodGroupInformer); ok { + return informer + } + return &podGroupTypedInformerAdapter{informer} +} + +type podGroupTypedInformerAdapter struct { + PodGroupInformer +} + +func (a *podGroupTypedInformerAdapter) TypedInformer() PodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.PodGroup](a.Informer()) +} + +// ToPodGroupIndexInformer converts an untyped informer into a PodGroupIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodGroup. If that is not the case, calling type-safe methods of the returned +// PodGroupIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodGroupIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodGroupIndexInformer(informer cache.SharedIndexInformer) PodGroupIndexInformer { + if informer, ok := informer.(PodGroupIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.PodGroup](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/workload.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/workload.go new file mode 100644 index 000000000..991762016 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1alpha3/workload.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + time "time" + + apischedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + schedulingv1alpha3 "k8s.io/client-go/listers/scheduling/v1alpha3" + cache "k8s.io/client-go/tools/cache" +) + +// WorkloadInformer provides access to a shared informer and lister for +// Workloads. Prefer using the type-safe variant (see [TypedWorkloadInformer]). +type WorkloadInformer interface { + Informer() cache.SharedIndexInformer + Lister() schedulingv1alpha3.WorkloadLister +} + +// TypedWorkloadInformer provides access to a shared informer and lister for +// Workloads, including the type-safe TypedInformer variant. +// It is a superset of WorkloadInformer. +type TypedWorkloadInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() WorkloadIndexInformer + Lister() schedulingv1alpha3.WorkloadLister +} + +// WorkloadIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type WorkloadIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1alpha3.Workload] + +// WorkloadHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Workload. +type WorkloadHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1alpha3.Workload] + +// WorkloadDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Workload. +type WorkloadDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1alpha3.Workload] + +// WorkloadFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Workload. +type WorkloadFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1alpha3.Workload] + +// WorkloadIndexers is a specialization of [cache.TypedIndexers] for Workload. +type WorkloadIndexers = cache.TypedIndexers[*apischedulingv1alpha3.Workload] + +// DeletedWorkload is a specialization of [cache.DeletedObject] for Workload. +type DeletedWorkload = cache.DeletedObject[*apischedulingv1alpha3.Workload] + +type workloadInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedWorkloadInformer]). +func NewWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers WorkloadIndexers) WorkloadIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredWorkloadInformer]). +func NewFilteredWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers WorkloadIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) WorkloadIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewWorkloadInformerWithOptions constructs a new informer for Workload type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedWorkloadInformerWithOptions]). +func NewWorkloadInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, options) +} + +// NewTypedWorkloadInformerWithOptions constructs a new informer for Workload type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedWorkloadInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) WorkloadIndexInformer { + gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1alpha3", Resource: "workloads"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.Workload](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().Workloads(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().Workloads(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().Workloads(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1alpha3().Workloads(namespace).Watch(ctx, opts) + }, + }, client), + &apischedulingv1alpha3.Workload{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *workloadInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *workloadInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *workloadInformer) TypedInformer() WorkloadIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.Workload](f.factory.InformerFor(&apischedulingv1alpha3.Workload{}, f.defaultInformer)) +} + +func (f *workloadInformer) Lister() schedulingv1alpha3.WorkloadLister { + return schedulingv1alpha3.NewWorkloadLister(f.Informer().GetIndexer()) +} + +// ToTypedWorkloadInformer converts an untyped informer into a TypedWorkloadInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Workload. If that is not the case, calling type-safe methods of the returned +// TypedWorkloadInformer leads to runtime panics. A safer alternative is to pass +// around a TypedWorkloadInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedWorkloadInformer(informer WorkloadInformer) TypedWorkloadInformer { + if informer, ok := informer.(TypedWorkloadInformer); ok { + return informer + } + return &workloadTypedInformerAdapter{informer} +} + +type workloadTypedInformerAdapter struct { + WorkloadInformer +} + +func (a *workloadTypedInformerAdapter) TypedInformer() WorkloadIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.Workload](a.Informer()) +} + +// ToWorkloadIndexInformer converts an untyped informer into a WorkloadIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Workload. If that is not the case, calling type-safe methods of the returned +// WorkloadIndexInformer leads to runtime panics. A safer alternative is to pass +// around a WorkloadIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToWorkloadIndexInformer(informer cache.SharedIndexInformer) WorkloadIndexInformer { + if informer, ok := informer.(WorkloadIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1alpha3.Workload](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/interface.go index 52840a9ce..f57d050b1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/interface.go @@ -24,8 +24,12 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // PodGroups returns a PodGroupInformer. + PodGroups() TypedPodGroupInformer // PriorityClasses returns a PriorityClassInformer. - PriorityClasses() PriorityClassInformer + PriorityClasses() TypedPriorityClassInformer + // Workloads returns a WorkloadInformer. + Workloads() TypedWorkloadInformer } type version struct { @@ -39,7 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// PriorityClasses returns a PriorityClassInformer. -func (v *version) PriorityClasses() PriorityClassInformer { +// PodGroups returns a TypedPodGroupInformer. +func (v *version) PodGroups() TypedPodGroupInformer { + return &podGroupInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// PriorityClasses returns a TypedPriorityClassInformer. +func (v *version) PriorityClasses() TypedPriorityClassInformer { return &priorityClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } + +// Workloads returns a TypedWorkloadInformer. +func (v *version) Workloads() TypedWorkloadInformer { + return &workloadInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/podgroup.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/podgroup.go new file mode 100644 index 000000000..ed77beccd --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/podgroup.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + time "time" + + apischedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + schedulingv1beta1 "k8s.io/client-go/listers/scheduling/v1beta1" + cache "k8s.io/client-go/tools/cache" +) + +// PodGroupInformer provides access to a shared informer and lister for +// PodGroups. Prefer using the type-safe variant (see [TypedPodGroupInformer]). +type PodGroupInformer interface { + Informer() cache.SharedIndexInformer + Lister() schedulingv1beta1.PodGroupLister +} + +// TypedPodGroupInformer provides access to a shared informer and lister for +// PodGroups, including the type-safe TypedInformer variant. +// It is a superset of PodGroupInformer. +type TypedPodGroupInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PodGroupIndexInformer + Lister() schedulingv1beta1.PodGroupLister +} + +// PodGroupIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PodGroupIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1beta1.PodGroup] + +// PodGroupHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PodGroup. +type PodGroupHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1beta1.PodGroup] + +// PodGroupDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PodGroup. +type PodGroupDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1beta1.PodGroup] + +// PodGroupFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PodGroup. +type PodGroupFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1beta1.PodGroup] + +// PodGroupIndexers is a specialization of [cache.TypedIndexers] for PodGroup. +type PodGroupIndexers = cache.TypedIndexers[*apischedulingv1beta1.PodGroup] + +// DeletedPodGroup is a specialization of [cache.DeletedObject] for PodGroup. +type DeletedPodGroup = cache.DeletedObject[*apischedulingv1beta1.PodGroup] + +type podGroupInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodGroupInformer]). +func NewPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodGroupIndexers) PodGroupIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPodGroupInformer]). +func NewFilteredPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPodGroupInformer constructs a new informer for PodGroup type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPodGroupInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers PodGroupIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PodGroupIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewPodGroupInformerWithOptions constructs a new informer for PodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPodGroupInformerWithOptions]). +func NewPodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, namespace, options) +} + +// NewTypedPodGroupInformerWithOptions constructs a new informer for PodGroup type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPodGroupInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) PodGroupIndexInformer { + gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1beta1", Resource: "podgroups"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PodGroup](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().PodGroups(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().PodGroups(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().PodGroups(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().PodGroups(namespace).Watch(ctx, opts) + }, + }, client), + &apischedulingv1beta1.PodGroup{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *podGroupInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedPodGroupInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *podGroupInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *podGroupInformer) TypedInformer() PodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PodGroup](f.factory.InformerFor(&apischedulingv1beta1.PodGroup{}, f.defaultInformer)) +} + +func (f *podGroupInformer) Lister() schedulingv1beta1.PodGroupLister { + return schedulingv1beta1.NewPodGroupLister(f.Informer().GetIndexer()) +} + +// ToTypedPodGroupInformer converts an untyped informer into a TypedPodGroupInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodGroup. If that is not the case, calling type-safe methods of the returned +// TypedPodGroupInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPodGroupInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPodGroupInformer(informer PodGroupInformer) TypedPodGroupInformer { + if informer, ok := informer.(TypedPodGroupInformer); ok { + return informer + } + return &podGroupTypedInformerAdapter{informer} +} + +type podGroupTypedInformerAdapter struct { + PodGroupInformer +} + +func (a *podGroupTypedInformerAdapter) TypedInformer() PodGroupIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PodGroup](a.Informer()) +} + +// ToPodGroupIndexInformer converts an untyped informer into a PodGroupIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PodGroup. If that is not the case, calling type-safe methods of the returned +// PodGroupIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PodGroupIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPodGroupIndexInformer(informer cache.SharedIndexInformer) PodGroupIndexInformer { + if informer, ok := informer.(PodGroupIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PodGroup](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go index a5cae3ea5..74b968d26 100644 --- a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go @@ -34,12 +34,40 @@ import ( ) // PriorityClassInformer provides access to a shared informer and lister for -// PriorityClasses. +// PriorityClasses. Prefer using the type-safe variant (see [TypedPriorityClassInformer]). type PriorityClassInformer interface { Informer() cache.SharedIndexInformer Lister() schedulingv1beta1.PriorityClassLister } +// TypedPriorityClassInformer provides access to a shared informer and lister for +// PriorityClasses, including the type-safe TypedInformer variant. +// It is a superset of PriorityClassInformer. +type TypedPriorityClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() PriorityClassIndexInformer + Lister() schedulingv1beta1.PriorityClassLister +} + +// PriorityClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type PriorityClassIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1beta1.PriorityClass] + +// PriorityClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for PriorityClass. +type PriorityClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1beta1.PriorityClass] + +// PriorityClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for PriorityClass. +type PriorityClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1beta1.PriorityClass] + +// PriorityClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for PriorityClass. +type PriorityClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1beta1.PriorityClass] + +// PriorityClassIndexers is a specialization of [cache.TypedIndexers] for PriorityClass. +type PriorityClassIndexers = cache.TypedIndexers[*apischedulingv1beta1.PriorityClass] + +// DeletedPriorityClass is a specialization of [cache.DeletedObject] for PriorityClass. +type DeletedPriorityClass = cache.DeletedObject[*apischedulingv1beta1.PriorityClass] + type priorityClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type priorityClassInformer struct { // NewPriorityClassInformer constructs a new informer for PriorityClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityClassInformer]). func NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedPriorityClassInformer constructs a new informer for PriorityClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityClassIndexers) PriorityClassIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredPriorityClassInformer constructs a new informer for PriorityClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredPriorityClassInformer]). func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredPriorityClassInformer constructs a new informer for PriorityClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers PriorityClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) PriorityClassIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewPriorityClassInformerWithOptions constructs a new informer for PriorityClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedPriorityClassInformerWithOptions]). func NewPriorityClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedPriorityClassInformerWithOptions(client, options) +} + +// NewTypedPriorityClassInformerWithOptions constructs a new informer for PriorityClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedPriorityClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) PriorityClassIndexInformer { gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1beta1", Resource: "priorityclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PriorityClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewPriorityClassInformerWithOptions(client kubernetes.Interface, options in Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedPriorityClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *priorityClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apischedulingv1beta1.PriorityClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *priorityClassInformer) TypedInformer() PriorityClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PriorityClass](f.factory.InformerFor(&apischedulingv1beta1.PriorityClass{}, f.defaultInformer)) } func (f *priorityClassInformer) Lister() schedulingv1beta1.PriorityClassLister { return schedulingv1beta1.NewPriorityClassLister(f.Informer().GetIndexer()) } + +// ToTypedPriorityClassInformer converts an untyped informer into a TypedPriorityClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityClass. If that is not the case, calling type-safe methods of the returned +// TypedPriorityClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedPriorityClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedPriorityClassInformer(informer PriorityClassInformer) TypedPriorityClassInformer { + if informer, ok := informer.(TypedPriorityClassInformer); ok { + return informer + } + return &priorityClassTypedInformerAdapter{informer} +} + +type priorityClassTypedInformerAdapter struct { + PriorityClassInformer +} + +func (a *priorityClassTypedInformerAdapter) TypedInformer() PriorityClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PriorityClass](a.Informer()) +} + +// ToPriorityClassIndexInformer converts an untyped informer into a PriorityClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *PriorityClass. If that is not the case, calling type-safe methods of the returned +// PriorityClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a PriorityClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToPriorityClassIndexInformer(informer cache.SharedIndexInformer) PriorityClassIndexInformer { + if informer, ok := informer.(PriorityClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.PriorityClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/workload.go b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/workload.go new file mode 100644 index 000000000..86c30f27e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/scheduling/v1beta1/workload.go @@ -0,0 +1,208 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + time "time" + + apischedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + schedulingv1beta1 "k8s.io/client-go/listers/scheduling/v1beta1" + cache "k8s.io/client-go/tools/cache" +) + +// WorkloadInformer provides access to a shared informer and lister for +// Workloads. Prefer using the type-safe variant (see [TypedWorkloadInformer]). +type WorkloadInformer interface { + Informer() cache.SharedIndexInformer + Lister() schedulingv1beta1.WorkloadLister +} + +// TypedWorkloadInformer provides access to a shared informer and lister for +// Workloads, including the type-safe TypedInformer variant. +// It is a superset of WorkloadInformer. +type TypedWorkloadInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() WorkloadIndexInformer + Lister() schedulingv1beta1.WorkloadLister +} + +// WorkloadIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type WorkloadIndexInformer cache.TypedSharedIndexInformer[*apischedulingv1beta1.Workload] + +// WorkloadHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for Workload. +type WorkloadHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apischedulingv1beta1.Workload] + +// WorkloadDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for Workload. +type WorkloadDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apischedulingv1beta1.Workload] + +// WorkloadFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for Workload. +type WorkloadFilteringHandler = cache.TypedFilteringResourceEventHandler[*apischedulingv1beta1.Workload] + +// WorkloadIndexers is a specialization of [cache.TypedIndexers] for Workload. +type WorkloadIndexers = cache.TypedIndexers[*apischedulingv1beta1.Workload] + +// DeletedWorkload is a specialization of [cache.DeletedObject] for Workload. +type DeletedWorkload = cache.DeletedObject[*apischedulingv1beta1.Workload] + +type workloadInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedWorkloadInformer]). +func NewWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers WorkloadIndexers) WorkloadIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredWorkloadInformer]). +func NewFilteredWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredWorkloadInformer constructs a new informer for Workload type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredWorkloadInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers WorkloadIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) WorkloadIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewWorkloadInformerWithOptions constructs a new informer for Workload type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedWorkloadInformerWithOptions]). +func NewWorkloadInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, namespace, options) +} + +// NewTypedWorkloadInformerWithOptions constructs a new informer for Workload type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedWorkloadInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) WorkloadIndexInformer { + gvr := schema.GroupVersionResource{Group: "scheduling.k8s.io", Version: "v1beta1", Resource: "workloads"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.Workload](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().Workloads(namespace).List(context.Background(), opts) + }, + WatchFunc: func(opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().Workloads(namespace).Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().Workloads(namespace).List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.SchedulingV1beta1().Workloads(namespace).Watch(ctx, opts) + }, + }, client), + &apischedulingv1beta1.Workload{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *workloadInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedWorkloadInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *workloadInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *workloadInformer) TypedInformer() WorkloadIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.Workload](f.factory.InformerFor(&apischedulingv1beta1.Workload{}, f.defaultInformer)) +} + +func (f *workloadInformer) Lister() schedulingv1beta1.WorkloadLister { + return schedulingv1beta1.NewWorkloadLister(f.Informer().GetIndexer()) +} + +// ToTypedWorkloadInformer converts an untyped informer into a TypedWorkloadInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Workload. If that is not the case, calling type-safe methods of the returned +// TypedWorkloadInformer leads to runtime panics. A safer alternative is to pass +// around a TypedWorkloadInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedWorkloadInformer(informer WorkloadInformer) TypedWorkloadInformer { + if informer, ok := informer.(TypedWorkloadInformer); ok { + return informer + } + return &workloadTypedInformerAdapter{informer} +} + +type workloadTypedInformerAdapter struct { + WorkloadInformer +} + +func (a *workloadTypedInformerAdapter) TypedInformer() WorkloadIndexInformer { + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.Workload](a.Informer()) +} + +// ToWorkloadIndexInformer converts an untyped informer into a WorkloadIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *Workload. If that is not the case, calling type-safe methods of the returned +// WorkloadIndexInformer leads to runtime panics. A safer alternative is to pass +// around a WorkloadIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToWorkloadIndexInformer(informer cache.SharedIndexInformer) WorkloadIndexInformer { + if informer, ok := informer.(WorkloadIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apischedulingv1beta1.Workload](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csidriver.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csidriver.go index 56ed349e2..f7b4d393e 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csidriver.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csidriver.go @@ -34,12 +34,40 @@ import ( ) // CSIDriverInformer provides access to a shared informer and lister for -// CSIDrivers. +// CSIDrivers. Prefer using the type-safe variant (see [TypedCSIDriverInformer]). type CSIDriverInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.CSIDriverLister } +// TypedCSIDriverInformer provides access to a shared informer and lister for +// CSIDrivers, including the type-safe TypedInformer variant. +// It is a superset of CSIDriverInformer. +type TypedCSIDriverInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSIDriverIndexInformer + Lister() storagev1.CSIDriverLister +} + +// CSIDriverIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSIDriverIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.CSIDriver] + +// CSIDriverHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSIDriver. +type CSIDriverHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.CSIDriver] + +// CSIDriverDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSIDriver. +type CSIDriverDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.CSIDriver] + +// CSIDriverFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSIDriver. +type CSIDriverFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.CSIDriver] + +// CSIDriverIndexers is a specialization of [cache.TypedIndexers] for CSIDriver. +type CSIDriverIndexers = cache.TypedIndexers[*apistoragev1.CSIDriver] + +// DeletedCSIDriver is a specialization of [cache.DeletedObject] for CSIDriver. +type DeletedCSIDriver = cache.DeletedObject[*apistoragev1.CSIDriver] + type cSIDriverInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type cSIDriverInformer struct { // NewCSIDriverInformer constructs a new informer for CSIDriver type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIDriverInformer]). func NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSIDriverInformer constructs a new informer for CSIDriver type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSIDriverIndexers) CSIDriverIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSIDriverInformer constructs a new informer for CSIDriver type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSIDriverInformer]). func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSIDriverInformer constructs a new informer for CSIDriver type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSIDriverIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSIDriverIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSIDriverInformerWithOptions constructs a new informer for CSIDriver type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIDriverInformerWithOptions]). func NewCSIDriverInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, options) +} + +// NewTypedCSIDriverInformerWithOptions constructs a new informer for CSIDriver type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIDriverInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CSIDriverIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "csidrivers"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIDriver](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCSIDriverInformerWithOptions(client kubernetes.Interface, options intern Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.CSIDriver{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSIDriverInformer) TypedInformer() CSIDriverIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIDriver](f.factory.InformerFor(&apistoragev1.CSIDriver{}, f.defaultInformer)) } func (f *cSIDriverInformer) Lister() storagev1.CSIDriverLister { return storagev1.NewCSIDriverLister(f.Informer().GetIndexer()) } + +// ToTypedCSIDriverInformer converts an untyped informer into a TypedCSIDriverInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIDriver. If that is not the case, calling type-safe methods of the returned +// TypedCSIDriverInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSIDriverInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSIDriverInformer(informer CSIDriverInformer) TypedCSIDriverInformer { + if informer, ok := informer.(TypedCSIDriverInformer); ok { + return informer + } + return &cSIDriverTypedInformerAdapter{informer} +} + +type cSIDriverTypedInformerAdapter struct { + CSIDriverInformer +} + +func (a *cSIDriverTypedInformerAdapter) TypedInformer() CSIDriverIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIDriver](a.Informer()) +} + +// ToCSIDriverIndexInformer converts an untyped informer into a CSIDriverIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIDriver. If that is not the case, calling type-safe methods of the returned +// CSIDriverIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSIDriverIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSIDriverIndexInformer(informer cache.SharedIndexInformer) CSIDriverIndexInformer { + if informer, ok := informer.(CSIDriverIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIDriver](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csinode.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csinode.go index c90686bf7..8a841028b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csinode.go @@ -34,12 +34,40 @@ import ( ) // CSINodeInformer provides access to a shared informer and lister for -// CSINodes. +// CSINodes. Prefer using the type-safe variant (see [TypedCSINodeInformer]). type CSINodeInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.CSINodeLister } +// TypedCSINodeInformer provides access to a shared informer and lister for +// CSINodes, including the type-safe TypedInformer variant. +// It is a superset of CSINodeInformer. +type TypedCSINodeInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSINodeIndexInformer + Lister() storagev1.CSINodeLister +} + +// CSINodeIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSINodeIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.CSINode] + +// CSINodeHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSINode. +type CSINodeHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.CSINode] + +// CSINodeDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSINode. +type CSINodeDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.CSINode] + +// CSINodeFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSINode. +type CSINodeFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.CSINode] + +// CSINodeIndexers is a specialization of [cache.TypedIndexers] for CSINode. +type CSINodeIndexers = cache.TypedIndexers[*apistoragev1.CSINode] + +// DeletedCSINode is a specialization of [cache.DeletedObject] for CSINode. +type DeletedCSINode = cache.DeletedObject[*apistoragev1.CSINode] + type cSINodeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type cSINodeInformer struct { // NewCSINodeInformer constructs a new informer for CSINode type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSINodeInformer]). func NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSINodeInformer constructs a new informer for CSINode type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSINodeIndexers) CSINodeIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSINodeInformer constructs a new informer for CSINode type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSINodeInformer]). func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSINodeInformer constructs a new informer for CSINode type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSINodeIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSINodeIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSINodeInformerWithOptions constructs a new informer for CSINode type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSINodeInformerWithOptions]). func NewCSINodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, options) +} + +// NewTypedCSINodeInformerWithOptions constructs a new informer for CSINode type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSINodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CSINodeIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "csinodes"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSINode](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCSINodeInformerWithOptions(client kubernetes.Interface, options internal Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSINodeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.CSINode{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSINodeInformer) TypedInformer() CSINodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSINode](f.factory.InformerFor(&apistoragev1.CSINode{}, f.defaultInformer)) } func (f *cSINodeInformer) Lister() storagev1.CSINodeLister { return storagev1.NewCSINodeLister(f.Informer().GetIndexer()) } + +// ToTypedCSINodeInformer converts an untyped informer into a TypedCSINodeInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSINode. If that is not the case, calling type-safe methods of the returned +// TypedCSINodeInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSINodeInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSINodeInformer(informer CSINodeInformer) TypedCSINodeInformer { + if informer, ok := informer.(TypedCSINodeInformer); ok { + return informer + } + return &cSINodeTypedInformerAdapter{informer} +} + +type cSINodeTypedInformerAdapter struct { + CSINodeInformer +} + +func (a *cSINodeTypedInformerAdapter) TypedInformer() CSINodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSINode](a.Informer()) +} + +// ToCSINodeIndexInformer converts an untyped informer into a CSINodeIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSINode. If that is not the case, calling type-safe methods of the returned +// CSINodeIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSINodeIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSINodeIndexInformer(informer cache.SharedIndexInformer) CSINodeIndexInformer { + if informer, ok := informer.(CSINodeIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSINode](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go index 52c0e281a..3052b40d9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go @@ -34,12 +34,40 @@ import ( ) // CSIStorageCapacityInformer provides access to a shared informer and lister for -// CSIStorageCapacities. +// CSIStorageCapacities. Prefer using the type-safe variant (see [TypedCSIStorageCapacityInformer]). type CSIStorageCapacityInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.CSIStorageCapacityLister } +// TypedCSIStorageCapacityInformer provides access to a shared informer and lister for +// CSIStorageCapacities, including the type-safe TypedInformer variant. +// It is a superset of CSIStorageCapacityInformer. +type TypedCSIStorageCapacityInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSIStorageCapacityIndexInformer + Lister() storagev1.CSIStorageCapacityLister +} + +// CSIStorageCapacityIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSIStorageCapacityIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.CSIStorageCapacity] + +// CSIStorageCapacityHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSIStorageCapacity. +type CSIStorageCapacityHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.CSIStorageCapacity] + +// CSIStorageCapacityDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSIStorageCapacity. +type CSIStorageCapacityDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.CSIStorageCapacity] + +// CSIStorageCapacityFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSIStorageCapacity. +type CSIStorageCapacityFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.CSIStorageCapacity] + +// CSIStorageCapacityIndexers is a specialization of [cache.TypedIndexers] for CSIStorageCapacity. +type CSIStorageCapacityIndexers = cache.TypedIndexers[*apistoragev1.CSIStorageCapacity] + +// DeletedCSIStorageCapacity is a specialization of [cache.DeletedObject] for CSIStorageCapacity. +type DeletedCSIStorageCapacity = cache.DeletedObject[*apistoragev1.CSIStorageCapacity] + type cSIStorageCapacityInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type cSIStorageCapacityInformer struct { // NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformer]). func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSIStorageCapacityInformer]). func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformerWithOptions]). func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, options) +} + +// NewTypedCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CSIStorageCapacityIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "csistoragecapacitys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIStorageCapacity](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.CSIStorageCapacity{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSIStorageCapacityInformer) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIStorageCapacity](f.factory.InformerFor(&apistoragev1.CSIStorageCapacity{}, f.defaultInformer)) } func (f *cSIStorageCapacityInformer) Lister() storagev1.CSIStorageCapacityLister { return storagev1.NewCSIStorageCapacityLister(f.Informer().GetIndexer()) } + +// ToTypedCSIStorageCapacityInformer converts an untyped informer into a TypedCSIStorageCapacityInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// TypedCSIStorageCapacityInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSIStorageCapacityInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSIStorageCapacityInformer(informer CSIStorageCapacityInformer) TypedCSIStorageCapacityInformer { + if informer, ok := informer.(TypedCSIStorageCapacityInformer); ok { + return informer + } + return &cSIStorageCapacityTypedInformerAdapter{informer} +} + +type cSIStorageCapacityTypedInformerAdapter struct { + CSIStorageCapacityInformer +} + +func (a *cSIStorageCapacityTypedInformerAdapter) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIStorageCapacity](a.Informer()) +} + +// ToCSIStorageCapacityIndexInformer converts an untyped informer into a CSIStorageCapacityIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// CSIStorageCapacityIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSIStorageCapacityIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSIStorageCapacityIndexInformer(informer cache.SharedIndexInformer) CSIStorageCapacityIndexInformer { + if informer, ok := informer.(CSIStorageCapacityIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.CSIStorageCapacity](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/interface.go index aff778e05..532e79b5f 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/interface.go @@ -25,17 +25,17 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CSIDrivers returns a CSIDriverInformer. - CSIDrivers() CSIDriverInformer + CSIDrivers() TypedCSIDriverInformer // CSINodes returns a CSINodeInformer. - CSINodes() CSINodeInformer + CSINodes() TypedCSINodeInformer // CSIStorageCapacities returns a CSIStorageCapacityInformer. - CSIStorageCapacities() CSIStorageCapacityInformer + CSIStorageCapacities() TypedCSIStorageCapacityInformer // StorageClasses returns a StorageClassInformer. - StorageClasses() StorageClassInformer + StorageClasses() TypedStorageClassInformer // VolumeAttachments returns a VolumeAttachmentInformer. - VolumeAttachments() VolumeAttachmentInformer + VolumeAttachments() TypedVolumeAttachmentInformer // VolumeAttributesClasses returns a VolumeAttributesClassInformer. - VolumeAttributesClasses() VolumeAttributesClassInformer + VolumeAttributesClasses() TypedVolumeAttributesClassInformer } type version struct { @@ -49,32 +49,32 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CSIDrivers returns a CSIDriverInformer. -func (v *version) CSIDrivers() CSIDriverInformer { +// CSIDrivers returns a TypedCSIDriverInformer. +func (v *version) CSIDrivers() TypedCSIDriverInformer { return &cSIDriverInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// CSINodes returns a CSINodeInformer. -func (v *version) CSINodes() CSINodeInformer { +// CSINodes returns a TypedCSINodeInformer. +func (v *version) CSINodes() TypedCSINodeInformer { return &cSINodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// CSIStorageCapacities returns a CSIStorageCapacityInformer. -func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer { +// CSIStorageCapacities returns a TypedCSIStorageCapacityInformer. +func (v *version) CSIStorageCapacities() TypedCSIStorageCapacityInformer { return &cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// StorageClasses returns a StorageClassInformer. -func (v *version) StorageClasses() StorageClassInformer { +// StorageClasses returns a TypedStorageClassInformer. +func (v *version) StorageClasses() TypedStorageClassInformer { return &storageClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// VolumeAttachments returns a VolumeAttachmentInformer. -func (v *version) VolumeAttachments() VolumeAttachmentInformer { +// VolumeAttachments returns a TypedVolumeAttachmentInformer. +func (v *version) VolumeAttachments() TypedVolumeAttachmentInformer { return &volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// VolumeAttributesClasses returns a VolumeAttributesClassInformer. -func (v *version) VolumeAttributesClasses() VolumeAttributesClassInformer { +// VolumeAttributesClasses returns a TypedVolumeAttributesClassInformer. +func (v *version) VolumeAttributesClasses() TypedVolumeAttributesClassInformer { return &volumeAttributesClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/storageclass.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/storageclass.go index 533d02fc8..ea123c61a 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/storageclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/storageclass.go @@ -34,12 +34,40 @@ import ( ) // StorageClassInformer provides access to a shared informer and lister for -// StorageClasses. +// StorageClasses. Prefer using the type-safe variant (see [TypedStorageClassInformer]). type StorageClassInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.StorageClassLister } +// TypedStorageClassInformer provides access to a shared informer and lister for +// StorageClasses, including the type-safe TypedInformer variant. +// It is a superset of StorageClassInformer. +type TypedStorageClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StorageClassIndexInformer + Lister() storagev1.StorageClassLister +} + +// StorageClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StorageClassIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.StorageClass] + +// StorageClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StorageClass. +type StorageClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.StorageClass] + +// StorageClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StorageClass. +type StorageClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.StorageClass] + +// StorageClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StorageClass. +type StorageClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.StorageClass] + +// StorageClassIndexers is a specialization of [cache.TypedIndexers] for StorageClass. +type StorageClassIndexers = cache.TypedIndexers[*apistoragev1.StorageClass] + +// DeletedStorageClass is a specialization of [cache.DeletedObject] for StorageClass. +type DeletedStorageClass = cache.DeletedObject[*apistoragev1.StorageClass] + type storageClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type storageClassInformer struct { // NewStorageClassInformer constructs a new informer for StorageClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageClassInformer]). func NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStorageClassInformer constructs a new informer for StorageClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageClassIndexers) StorageClassIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStorageClassInformer constructs a new informer for StorageClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStorageClassInformer]). func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStorageClassInformer constructs a new informer for StorageClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StorageClassIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStorageClassInformerWithOptions constructs a new informer for StorageClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageClassInformerWithOptions]). func NewStorageClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, options) +} + +// NewTypedStorageClassInformerWithOptions constructs a new informer for StorageClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) StorageClassIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "storageclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.StorageClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewStorageClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *storageClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.StorageClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *storageClassInformer) TypedInformer() StorageClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.StorageClass](f.factory.InformerFor(&apistoragev1.StorageClass{}, f.defaultInformer)) } func (f *storageClassInformer) Lister() storagev1.StorageClassLister { return storagev1.NewStorageClassLister(f.Informer().GetIndexer()) } + +// ToTypedStorageClassInformer converts an untyped informer into a TypedStorageClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageClass. If that is not the case, calling type-safe methods of the returned +// TypedStorageClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStorageClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStorageClassInformer(informer StorageClassInformer) TypedStorageClassInformer { + if informer, ok := informer.(TypedStorageClassInformer); ok { + return informer + } + return &storageClassTypedInformerAdapter{informer} +} + +type storageClassTypedInformerAdapter struct { + StorageClassInformer +} + +func (a *storageClassTypedInformerAdapter) TypedInformer() StorageClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.StorageClass](a.Informer()) +} + +// ToStorageClassIndexInformer converts an untyped informer into a StorageClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageClass. If that is not the case, calling type-safe methods of the returned +// StorageClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StorageClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStorageClassIndexInformer(informer cache.SharedIndexInformer) StorageClassIndexInformer { + if informer, ok := informer.(StorageClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.StorageClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattachment.go index 49444340a..fdd91fd74 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattachment.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttachmentInformer provides access to a shared informer and lister for -// VolumeAttachments. +// VolumeAttachments. Prefer using the type-safe variant (see [TypedVolumeAttachmentInformer]). type VolumeAttachmentInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.VolumeAttachmentLister } +// TypedVolumeAttachmentInformer provides access to a shared informer and lister for +// VolumeAttachments, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttachmentInformer. +type TypedVolumeAttachmentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttachmentIndexInformer + Lister() storagev1.VolumeAttachmentLister +} + +// VolumeAttachmentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttachmentIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.VolumeAttachment] + +// VolumeAttachmentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttachment. +type VolumeAttachmentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.VolumeAttachment] + +// VolumeAttachmentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttachment. +type VolumeAttachmentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.VolumeAttachment] + +// VolumeAttachmentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttachment. +type VolumeAttachmentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.VolumeAttachment] + +// VolumeAttachmentIndexers is a specialization of [cache.TypedIndexers] for VolumeAttachment. +type VolumeAttachmentIndexers = cache.TypedIndexers[*apistoragev1.VolumeAttachment] + +// DeletedVolumeAttachment is a specialization of [cache.DeletedObject] for VolumeAttachment. +type DeletedVolumeAttachment = cache.DeletedObject[*apistoragev1.VolumeAttachment] + type volumeAttachmentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttachmentInformer struct { // NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformer]). func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttachmentInformer]). func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformerWithOptions]). func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, options) +} + +// NewTypedVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttachmentIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "volumeattachments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttachment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.VolumeAttachment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttachmentInformer) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttachment](f.factory.InformerFor(&apistoragev1.VolumeAttachment{}, f.defaultInformer)) } func (f *volumeAttachmentInformer) Lister() storagev1.VolumeAttachmentLister { return storagev1.NewVolumeAttachmentLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttachmentInformer converts an untyped informer into a TypedVolumeAttachmentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttachmentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttachmentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttachmentInformer(informer VolumeAttachmentInformer) TypedVolumeAttachmentInformer { + if informer, ok := informer.(TypedVolumeAttachmentInformer); ok { + return informer + } + return &volumeAttachmentTypedInformerAdapter{informer} +} + +type volumeAttachmentTypedInformerAdapter struct { + VolumeAttachmentInformer +} + +func (a *volumeAttachmentTypedInformerAdapter) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttachment](a.Informer()) +} + +// ToVolumeAttachmentIndexInformer converts an untyped informer into a VolumeAttachmentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// VolumeAttachmentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttachmentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttachmentIndexInformer(informer cache.SharedIndexInformer) VolumeAttachmentIndexInformer { + if informer, ok := informer.(VolumeAttachmentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttachment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattributesclass.go index fa8acccfb..e41eafe3b 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1/volumeattributesclass.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttributesClassInformer provides access to a shared informer and lister for -// VolumeAttributesClasses. +// VolumeAttributesClasses. Prefer using the type-safe variant (see [TypedVolumeAttributesClassInformer]). type VolumeAttributesClassInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1.VolumeAttributesClassLister } +// TypedVolumeAttributesClassInformer provides access to a shared informer and lister for +// VolumeAttributesClasses, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttributesClassInformer. +type TypedVolumeAttributesClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttributesClassIndexInformer + Lister() storagev1.VolumeAttributesClassLister +} + +// VolumeAttributesClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttributesClassIndexInformer cache.TypedSharedIndexInformer[*apistoragev1.VolumeAttributesClass] + +// VolumeAttributesClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttributesClass. +type VolumeAttributesClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1.VolumeAttributesClass] + +// VolumeAttributesClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttributesClass. +type VolumeAttributesClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1.VolumeAttributesClass] + +// VolumeAttributesClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttributesClass. +type VolumeAttributesClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1.VolumeAttributesClass] + +// VolumeAttributesClassIndexers is a specialization of [cache.TypedIndexers] for VolumeAttributesClass. +type VolumeAttributesClassIndexers = cache.TypedIndexers[*apistoragev1.VolumeAttributesClass] + +// DeletedVolumeAttributesClass is a specialization of [cache.DeletedObject] for VolumeAttributesClass. +type DeletedVolumeAttributesClass = cache.DeletedObject[*apistoragev1.VolumeAttributesClass] + type volumeAttributesClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttributesClassInformer struct { // NewVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformer]). func NewVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttributesClassInformer]). func NewFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformerWithOptions]). func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, options) +} + +// NewTypedVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttributesClassIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1", Resource: "volumeattributesclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttributesClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, op Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttributesClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttributesClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1.VolumeAttributesClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttributesClassInformer) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttributesClass](f.factory.InformerFor(&apistoragev1.VolumeAttributesClass{}, f.defaultInformer)) } func (f *volumeAttributesClassInformer) Lister() storagev1.VolumeAttributesClassLister { return storagev1.NewVolumeAttributesClassLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttributesClassInformer converts an untyped informer into a TypedVolumeAttributesClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttributesClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttributesClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttributesClassInformer(informer VolumeAttributesClassInformer) TypedVolumeAttributesClassInformer { + if informer, ok := informer.(TypedVolumeAttributesClassInformer); ok { + return informer + } + return &volumeAttributesClassTypedInformerAdapter{informer} +} + +type volumeAttributesClassTypedInformerAdapter struct { + VolumeAttributesClassInformer +} + +func (a *volumeAttributesClassTypedInformerAdapter) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttributesClass](a.Informer()) +} + +// ToVolumeAttributesClassIndexInformer converts an untyped informer into a VolumeAttributesClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// VolumeAttributesClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttributesClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttributesClassIndexInformer(informer cache.SharedIndexInformer) VolumeAttributesClassIndexInformer { + if informer, ok := informer.(VolumeAttributesClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1.VolumeAttributesClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go index 2f7accab3..bfdcc62e3 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go @@ -34,12 +34,40 @@ import ( ) // CSIStorageCapacityInformer provides access to a shared informer and lister for -// CSIStorageCapacities. +// CSIStorageCapacities. Prefer using the type-safe variant (see [TypedCSIStorageCapacityInformer]). type CSIStorageCapacityInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1alpha1.CSIStorageCapacityLister } +// TypedCSIStorageCapacityInformer provides access to a shared informer and lister for +// CSIStorageCapacities, including the type-safe TypedInformer variant. +// It is a superset of CSIStorageCapacityInformer. +type TypedCSIStorageCapacityInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSIStorageCapacityIndexInformer + Lister() storagev1alpha1.CSIStorageCapacityLister +} + +// CSIStorageCapacityIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSIStorageCapacityIndexInformer cache.TypedSharedIndexInformer[*apistoragev1alpha1.CSIStorageCapacity] + +// CSIStorageCapacityHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSIStorageCapacity. +type CSIStorageCapacityHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1alpha1.CSIStorageCapacity] + +// CSIStorageCapacityDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSIStorageCapacity. +type CSIStorageCapacityDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1alpha1.CSIStorageCapacity] + +// CSIStorageCapacityFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSIStorageCapacity. +type CSIStorageCapacityFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1alpha1.CSIStorageCapacity] + +// CSIStorageCapacityIndexers is a specialization of [cache.TypedIndexers] for CSIStorageCapacity. +type CSIStorageCapacityIndexers = cache.TypedIndexers[*apistoragev1alpha1.CSIStorageCapacity] + +// DeletedCSIStorageCapacity is a specialization of [cache.DeletedObject] for CSIStorageCapacity. +type DeletedCSIStorageCapacity = cache.DeletedObject[*apistoragev1alpha1.CSIStorageCapacity] + type cSIStorageCapacityInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type cSIStorageCapacityInformer struct { // NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformer]). func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSIStorageCapacityInformer]). func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformerWithOptions]). func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, options) +} + +// NewTypedCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CSIStorageCapacityIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1alpha1", Resource: "csistoragecapacitys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.CSIStorageCapacity](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1alpha1.CSIStorageCapacity{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSIStorageCapacityInformer) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.CSIStorageCapacity](f.factory.InformerFor(&apistoragev1alpha1.CSIStorageCapacity{}, f.defaultInformer)) } func (f *cSIStorageCapacityInformer) Lister() storagev1alpha1.CSIStorageCapacityLister { return storagev1alpha1.NewCSIStorageCapacityLister(f.Informer().GetIndexer()) } + +// ToTypedCSIStorageCapacityInformer converts an untyped informer into a TypedCSIStorageCapacityInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// TypedCSIStorageCapacityInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSIStorageCapacityInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSIStorageCapacityInformer(informer CSIStorageCapacityInformer) TypedCSIStorageCapacityInformer { + if informer, ok := informer.(TypedCSIStorageCapacityInformer); ok { + return informer + } + return &cSIStorageCapacityTypedInformerAdapter{informer} +} + +type cSIStorageCapacityTypedInformerAdapter struct { + CSIStorageCapacityInformer +} + +func (a *cSIStorageCapacityTypedInformerAdapter) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.CSIStorageCapacity](a.Informer()) +} + +// ToCSIStorageCapacityIndexInformer converts an untyped informer into a CSIStorageCapacityIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// CSIStorageCapacityIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSIStorageCapacityIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSIStorageCapacityIndexInformer(informer cache.SharedIndexInformer) CSIStorageCapacityIndexInformer { + if informer, ok := informer.(CSIStorageCapacityIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.CSIStorageCapacity](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/interface.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/interface.go index bda3b1add..5ed95b0ef 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/interface.go @@ -25,11 +25,11 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CSIStorageCapacities returns a CSIStorageCapacityInformer. - CSIStorageCapacities() CSIStorageCapacityInformer + CSIStorageCapacities() TypedCSIStorageCapacityInformer // VolumeAttachments returns a VolumeAttachmentInformer. - VolumeAttachments() VolumeAttachmentInformer + VolumeAttachments() TypedVolumeAttachmentInformer // VolumeAttributesClasses returns a VolumeAttributesClassInformer. - VolumeAttributesClasses() VolumeAttributesClassInformer + VolumeAttributesClasses() TypedVolumeAttributesClassInformer } type version struct { @@ -43,17 +43,17 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CSIStorageCapacities returns a CSIStorageCapacityInformer. -func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer { +// CSIStorageCapacities returns a TypedCSIStorageCapacityInformer. +func (v *version) CSIStorageCapacities() TypedCSIStorageCapacityInformer { return &cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// VolumeAttachments returns a VolumeAttachmentInformer. -func (v *version) VolumeAttachments() VolumeAttachmentInformer { +// VolumeAttachments returns a TypedVolumeAttachmentInformer. +func (v *version) VolumeAttachments() TypedVolumeAttachmentInformer { return &volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// VolumeAttributesClasses returns a VolumeAttributesClassInformer. -func (v *version) VolumeAttributesClasses() VolumeAttributesClassInformer { +// VolumeAttributesClasses returns a TypedVolumeAttributesClassInformer. +func (v *version) VolumeAttributesClasses() TypedVolumeAttributesClassInformer { return &volumeAttributesClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go index 1ab135906..f270fecec 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttachmentInformer provides access to a shared informer and lister for -// VolumeAttachments. +// VolumeAttachments. Prefer using the type-safe variant (see [TypedVolumeAttachmentInformer]). type VolumeAttachmentInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1alpha1.VolumeAttachmentLister } +// TypedVolumeAttachmentInformer provides access to a shared informer and lister for +// VolumeAttachments, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttachmentInformer. +type TypedVolumeAttachmentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttachmentIndexInformer + Lister() storagev1alpha1.VolumeAttachmentLister +} + +// VolumeAttachmentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttachmentIndexInformer cache.TypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttachment] + +// VolumeAttachmentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttachment. +type VolumeAttachmentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1alpha1.VolumeAttachment] + +// VolumeAttachmentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttachment. +type VolumeAttachmentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1alpha1.VolumeAttachment] + +// VolumeAttachmentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttachment. +type VolumeAttachmentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1alpha1.VolumeAttachment] + +// VolumeAttachmentIndexers is a specialization of [cache.TypedIndexers] for VolumeAttachment. +type VolumeAttachmentIndexers = cache.TypedIndexers[*apistoragev1alpha1.VolumeAttachment] + +// DeletedVolumeAttachment is a specialization of [cache.DeletedObject] for VolumeAttachment. +type DeletedVolumeAttachment = cache.DeletedObject[*apistoragev1alpha1.VolumeAttachment] + type volumeAttachmentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttachmentInformer struct { // NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformer]). func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttachmentInformer]). func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformerWithOptions]). func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, options) +} + +// NewTypedVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttachmentIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1alpha1", Resource: "volumeattachments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttachment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1alpha1.VolumeAttachment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttachmentInformer) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttachment](f.factory.InformerFor(&apistoragev1alpha1.VolumeAttachment{}, f.defaultInformer)) } func (f *volumeAttachmentInformer) Lister() storagev1alpha1.VolumeAttachmentLister { return storagev1alpha1.NewVolumeAttachmentLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttachmentInformer converts an untyped informer into a TypedVolumeAttachmentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttachmentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttachmentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttachmentInformer(informer VolumeAttachmentInformer) TypedVolumeAttachmentInformer { + if informer, ok := informer.(TypedVolumeAttachmentInformer); ok { + return informer + } + return &volumeAttachmentTypedInformerAdapter{informer} +} + +type volumeAttachmentTypedInformerAdapter struct { + VolumeAttachmentInformer +} + +func (a *volumeAttachmentTypedInformerAdapter) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttachment](a.Informer()) +} + +// ToVolumeAttachmentIndexInformer converts an untyped informer into a VolumeAttachmentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// VolumeAttachmentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttachmentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttachmentIndexInformer(informer cache.SharedIndexInformer) VolumeAttachmentIndexInformer { + if informer, ok := informer.(VolumeAttachmentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttachment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattributesclass.go index e649c665e..0ba63295c 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1alpha1/volumeattributesclass.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttributesClassInformer provides access to a shared informer and lister for -// VolumeAttributesClasses. +// VolumeAttributesClasses. Prefer using the type-safe variant (see [TypedVolumeAttributesClassInformer]). type VolumeAttributesClassInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1alpha1.VolumeAttributesClassLister } +// TypedVolumeAttributesClassInformer provides access to a shared informer and lister for +// VolumeAttributesClasses, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttributesClassInformer. +type TypedVolumeAttributesClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttributesClassIndexInformer + Lister() storagev1alpha1.VolumeAttributesClassLister +} + +// VolumeAttributesClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttributesClassIndexInformer cache.TypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttributesClass] + +// VolumeAttributesClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttributesClass. +type VolumeAttributesClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1alpha1.VolumeAttributesClass] + +// VolumeAttributesClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttributesClass. +type VolumeAttributesClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1alpha1.VolumeAttributesClass] + +// VolumeAttributesClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttributesClass. +type VolumeAttributesClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1alpha1.VolumeAttributesClass] + +// VolumeAttributesClassIndexers is a specialization of [cache.TypedIndexers] for VolumeAttributesClass. +type VolumeAttributesClassIndexers = cache.TypedIndexers[*apistoragev1alpha1.VolumeAttributesClass] + +// DeletedVolumeAttributesClass is a specialization of [cache.DeletedObject] for VolumeAttributesClass. +type DeletedVolumeAttributesClass = cache.DeletedObject[*apistoragev1alpha1.VolumeAttributesClass] + type volumeAttributesClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttributesClassInformer struct { // NewVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformer]). func NewVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttributesClassInformer]). func NewFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformerWithOptions]). func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, options) +} + +// NewTypedVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttributesClassIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1alpha1", Resource: "volumeattributesclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttributesClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, op Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttributesClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttributesClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1alpha1.VolumeAttributesClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttributesClassInformer) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttributesClass](f.factory.InformerFor(&apistoragev1alpha1.VolumeAttributesClass{}, f.defaultInformer)) } func (f *volumeAttributesClassInformer) Lister() storagev1alpha1.VolumeAttributesClassLister { return storagev1alpha1.NewVolumeAttributesClassLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttributesClassInformer converts an untyped informer into a TypedVolumeAttributesClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttributesClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttributesClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttributesClassInformer(informer VolumeAttributesClassInformer) TypedVolumeAttributesClassInformer { + if informer, ok := informer.(TypedVolumeAttributesClassInformer); ok { + return informer + } + return &volumeAttributesClassTypedInformerAdapter{informer} +} + +type volumeAttributesClassTypedInformerAdapter struct { + VolumeAttributesClassInformer +} + +func (a *volumeAttributesClassTypedInformerAdapter) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttributesClass](a.Informer()) +} + +// ToVolumeAttributesClassIndexInformer converts an untyped informer into a VolumeAttributesClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// VolumeAttributesClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttributesClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttributesClassIndexInformer(informer cache.SharedIndexInformer) VolumeAttributesClassIndexInformer { + if informer, ok := informer.(VolumeAttributesClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1alpha1.VolumeAttributesClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csidriver.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csidriver.go index 283dc6b17..33c0f5551 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csidriver.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csidriver.go @@ -34,12 +34,40 @@ import ( ) // CSIDriverInformer provides access to a shared informer and lister for -// CSIDrivers. +// CSIDrivers. Prefer using the type-safe variant (see [TypedCSIDriverInformer]). type CSIDriverInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.CSIDriverLister } +// TypedCSIDriverInformer provides access to a shared informer and lister for +// CSIDrivers, including the type-safe TypedInformer variant. +// It is a superset of CSIDriverInformer. +type TypedCSIDriverInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSIDriverIndexInformer + Lister() storagev1beta1.CSIDriverLister +} + +// CSIDriverIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSIDriverIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.CSIDriver] + +// CSIDriverHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSIDriver. +type CSIDriverHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.CSIDriver] + +// CSIDriverDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSIDriver. +type CSIDriverDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.CSIDriver] + +// CSIDriverFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSIDriver. +type CSIDriverFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.CSIDriver] + +// CSIDriverIndexers is a specialization of [cache.TypedIndexers] for CSIDriver. +type CSIDriverIndexers = cache.TypedIndexers[*apistoragev1beta1.CSIDriver] + +// DeletedCSIDriver is a specialization of [cache.DeletedObject] for CSIDriver. +type DeletedCSIDriver = cache.DeletedObject[*apistoragev1beta1.CSIDriver] + type cSIDriverInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type cSIDriverInformer struct { // NewCSIDriverInformer constructs a new informer for CSIDriver type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIDriverInformer]). func NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSIDriverInformer constructs a new informer for CSIDriver type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSIDriverIndexers) CSIDriverIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSIDriverInformer constructs a new informer for CSIDriver type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSIDriverInformer]). func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSIDriverInformer constructs a new informer for CSIDriver type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSIDriverIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSIDriverIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSIDriverInformerWithOptions constructs a new informer for CSIDriver type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIDriverInformerWithOptions]). func NewCSIDriverInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSIDriverInformerWithOptions(client, options) +} + +// NewTypedCSIDriverInformerWithOptions constructs a new informer for CSIDriver type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIDriverInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CSIDriverIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "csidrivers"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIDriver](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCSIDriverInformerWithOptions(client kubernetes.Interface, options intern Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSIDriverInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.CSIDriver{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSIDriverInformer) TypedInformer() CSIDriverIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIDriver](f.factory.InformerFor(&apistoragev1beta1.CSIDriver{}, f.defaultInformer)) } func (f *cSIDriverInformer) Lister() storagev1beta1.CSIDriverLister { return storagev1beta1.NewCSIDriverLister(f.Informer().GetIndexer()) } + +// ToTypedCSIDriverInformer converts an untyped informer into a TypedCSIDriverInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIDriver. If that is not the case, calling type-safe methods of the returned +// TypedCSIDriverInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSIDriverInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSIDriverInformer(informer CSIDriverInformer) TypedCSIDriverInformer { + if informer, ok := informer.(TypedCSIDriverInformer); ok { + return informer + } + return &cSIDriverTypedInformerAdapter{informer} +} + +type cSIDriverTypedInformerAdapter struct { + CSIDriverInformer +} + +func (a *cSIDriverTypedInformerAdapter) TypedInformer() CSIDriverIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIDriver](a.Informer()) +} + +// ToCSIDriverIndexInformer converts an untyped informer into a CSIDriverIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIDriver. If that is not the case, calling type-safe methods of the returned +// CSIDriverIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSIDriverIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSIDriverIndexInformer(informer cache.SharedIndexInformer) CSIDriverIndexInformer { + if informer, ok := informer.(CSIDriverIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIDriver](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csinode.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csinode.go index f304906ce..4e7fa6f56 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csinode.go @@ -34,12 +34,40 @@ import ( ) // CSINodeInformer provides access to a shared informer and lister for -// CSINodes. +// CSINodes. Prefer using the type-safe variant (see [TypedCSINodeInformer]). type CSINodeInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.CSINodeLister } +// TypedCSINodeInformer provides access to a shared informer and lister for +// CSINodes, including the type-safe TypedInformer variant. +// It is a superset of CSINodeInformer. +type TypedCSINodeInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSINodeIndexInformer + Lister() storagev1beta1.CSINodeLister +} + +// CSINodeIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSINodeIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.CSINode] + +// CSINodeHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSINode. +type CSINodeHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.CSINode] + +// CSINodeDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSINode. +type CSINodeDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.CSINode] + +// CSINodeFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSINode. +type CSINodeFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.CSINode] + +// CSINodeIndexers is a specialization of [cache.TypedIndexers] for CSINode. +type CSINodeIndexers = cache.TypedIndexers[*apistoragev1beta1.CSINode] + +// DeletedCSINode is a specialization of [cache.DeletedObject] for CSINode. +type DeletedCSINode = cache.DeletedObject[*apistoragev1beta1.CSINode] + type cSINodeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type cSINodeInformer struct { // NewCSINodeInformer constructs a new informer for CSINode type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSINodeInformer]). func NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSINodeInformer constructs a new informer for CSINode type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSINodeIndexers) CSINodeIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSINodeInformer constructs a new informer for CSINode type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSINodeInformer]). func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSINodeInformer constructs a new informer for CSINode type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers CSINodeIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSINodeIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSINodeInformerWithOptions constructs a new informer for CSINode type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSINodeInformerWithOptions]). func NewCSINodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSINodeInformerWithOptions(client, options) +} + +// NewTypedCSINodeInformerWithOptions constructs a new informer for CSINode type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSINodeInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) CSINodeIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "csinodes"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSINode](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewCSINodeInformerWithOptions(client kubernetes.Interface, options internal Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSINodeInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSINodeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.CSINode{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSINodeInformer) TypedInformer() CSINodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSINode](f.factory.InformerFor(&apistoragev1beta1.CSINode{}, f.defaultInformer)) } func (f *cSINodeInformer) Lister() storagev1beta1.CSINodeLister { return storagev1beta1.NewCSINodeLister(f.Informer().GetIndexer()) } + +// ToTypedCSINodeInformer converts an untyped informer into a TypedCSINodeInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSINode. If that is not the case, calling type-safe methods of the returned +// TypedCSINodeInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSINodeInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSINodeInformer(informer CSINodeInformer) TypedCSINodeInformer { + if informer, ok := informer.(TypedCSINodeInformer); ok { + return informer + } + return &cSINodeTypedInformerAdapter{informer} +} + +type cSINodeTypedInformerAdapter struct { + CSINodeInformer +} + +func (a *cSINodeTypedInformerAdapter) TypedInformer() CSINodeIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSINode](a.Informer()) +} + +// ToCSINodeIndexInformer converts an untyped informer into a CSINodeIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSINode. If that is not the case, calling type-safe methods of the returned +// CSINodeIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSINodeIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSINodeIndexInformer(informer cache.SharedIndexInformer) CSINodeIndexInformer { + if informer, ok := informer.(CSINodeIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSINode](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go index 5b24a8c32..26c7cdb54 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go @@ -34,12 +34,40 @@ import ( ) // CSIStorageCapacityInformer provides access to a shared informer and lister for -// CSIStorageCapacities. +// CSIStorageCapacities. Prefer using the type-safe variant (see [TypedCSIStorageCapacityInformer]). type CSIStorageCapacityInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.CSIStorageCapacityLister } +// TypedCSIStorageCapacityInformer provides access to a shared informer and lister for +// CSIStorageCapacities, including the type-safe TypedInformer variant. +// It is a superset of CSIStorageCapacityInformer. +type TypedCSIStorageCapacityInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() CSIStorageCapacityIndexInformer + Lister() storagev1beta1.CSIStorageCapacityLister +} + +// CSIStorageCapacityIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type CSIStorageCapacityIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.CSIStorageCapacity] + +// CSIStorageCapacityHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for CSIStorageCapacity. +type CSIStorageCapacityHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.CSIStorageCapacity] + +// CSIStorageCapacityDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for CSIStorageCapacity. +type CSIStorageCapacityDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.CSIStorageCapacity] + +// CSIStorageCapacityFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for CSIStorageCapacity. +type CSIStorageCapacityFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.CSIStorageCapacity] + +// CSIStorageCapacityIndexers is a specialization of [cache.TypedIndexers] for CSIStorageCapacity. +type CSIStorageCapacityIndexers = cache.TypedIndexers[*apistoragev1beta1.CSIStorageCapacity] + +// DeletedCSIStorageCapacity is a specialization of [cache.DeletedObject] for CSIStorageCapacity. +type DeletedCSIStorageCapacity = cache.DeletedObject[*apistoragev1beta1.CSIStorageCapacity] + type cSIStorageCapacityInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -49,25 +77,49 @@ type cSIStorageCapacityInformer struct { // NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformer]). func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredCSIStorageCapacityInformer]). func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers CSIStorageCapacityIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) CSIStorageCapacityIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedCSIStorageCapacityInformerWithOptions]). func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedCSIStorageCapacityInformerWithOptions(client, namespace, options) +} + +// NewTypedCSIStorageCapacityInformerWithOptions constructs a new informer for CSIStorageCapacity type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, namespace string, options internalinterfaces.InformerOptions) CSIStorageCapacityIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "csistoragecapacitys"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIStorageCapacity](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -100,17 +152,57 @@ func NewCSIStorageCapacityInformerWithOptions(client kubernetes.Interface, names Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedCSIStorageCapacityInformerWithOptions(client, f.namespace, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.CSIStorageCapacity{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *cSIStorageCapacityInformer) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIStorageCapacity](f.factory.InformerFor(&apistoragev1beta1.CSIStorageCapacity{}, f.defaultInformer)) } func (f *cSIStorageCapacityInformer) Lister() storagev1beta1.CSIStorageCapacityLister { return storagev1beta1.NewCSIStorageCapacityLister(f.Informer().GetIndexer()) } + +// ToTypedCSIStorageCapacityInformer converts an untyped informer into a TypedCSIStorageCapacityInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// TypedCSIStorageCapacityInformer leads to runtime panics. A safer alternative is to pass +// around a TypedCSIStorageCapacityInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedCSIStorageCapacityInformer(informer CSIStorageCapacityInformer) TypedCSIStorageCapacityInformer { + if informer, ok := informer.(TypedCSIStorageCapacityInformer); ok { + return informer + } + return &cSIStorageCapacityTypedInformerAdapter{informer} +} + +type cSIStorageCapacityTypedInformerAdapter struct { + CSIStorageCapacityInformer +} + +func (a *cSIStorageCapacityTypedInformerAdapter) TypedInformer() CSIStorageCapacityIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIStorageCapacity](a.Informer()) +} + +// ToCSIStorageCapacityIndexInformer converts an untyped informer into a CSIStorageCapacityIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *CSIStorageCapacity. If that is not the case, calling type-safe methods of the returned +// CSIStorageCapacityIndexInformer leads to runtime panics. A safer alternative is to pass +// around a CSIStorageCapacityIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToCSIStorageCapacityIndexInformer(informer cache.SharedIndexInformer) CSIStorageCapacityIndexInformer { + if informer, ok := informer.(CSIStorageCapacityIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.CSIStorageCapacity](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/interface.go index 743395185..a1a312170 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/interface.go @@ -25,17 +25,17 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // CSIDrivers returns a CSIDriverInformer. - CSIDrivers() CSIDriverInformer + CSIDrivers() TypedCSIDriverInformer // CSINodes returns a CSINodeInformer. - CSINodes() CSINodeInformer + CSINodes() TypedCSINodeInformer // CSIStorageCapacities returns a CSIStorageCapacityInformer. - CSIStorageCapacities() CSIStorageCapacityInformer + CSIStorageCapacities() TypedCSIStorageCapacityInformer // StorageClasses returns a StorageClassInformer. - StorageClasses() StorageClassInformer + StorageClasses() TypedStorageClassInformer // VolumeAttachments returns a VolumeAttachmentInformer. - VolumeAttachments() VolumeAttachmentInformer + VolumeAttachments() TypedVolumeAttachmentInformer // VolumeAttributesClasses returns a VolumeAttributesClassInformer. - VolumeAttributesClasses() VolumeAttributesClassInformer + VolumeAttributesClasses() TypedVolumeAttributesClassInformer } type version struct { @@ -49,32 +49,32 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// CSIDrivers returns a CSIDriverInformer. -func (v *version) CSIDrivers() CSIDriverInformer { +// CSIDrivers returns a TypedCSIDriverInformer. +func (v *version) CSIDrivers() TypedCSIDriverInformer { return &cSIDriverInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// CSINodes returns a CSINodeInformer. -func (v *version) CSINodes() CSINodeInformer { +// CSINodes returns a TypedCSINodeInformer. +func (v *version) CSINodes() TypedCSINodeInformer { return &cSINodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// CSIStorageCapacities returns a CSIStorageCapacityInformer. -func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer { +// CSIStorageCapacities returns a TypedCSIStorageCapacityInformer. +func (v *version) CSIStorageCapacities() TypedCSIStorageCapacityInformer { return &cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// StorageClasses returns a StorageClassInformer. -func (v *version) StorageClasses() StorageClassInformer { +// StorageClasses returns a TypedStorageClassInformer. +func (v *version) StorageClasses() TypedStorageClassInformer { return &storageClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// VolumeAttachments returns a VolumeAttachmentInformer. -func (v *version) VolumeAttachments() VolumeAttachmentInformer { +// VolumeAttachments returns a TypedVolumeAttachmentInformer. +func (v *version) VolumeAttachments() TypedVolumeAttachmentInformer { return &volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// VolumeAttributesClasses returns a VolumeAttributesClassInformer. -func (v *version) VolumeAttributesClasses() VolumeAttributesClassInformer { +// VolumeAttributesClasses returns a TypedVolumeAttributesClassInformer. +func (v *version) VolumeAttributesClasses() TypedVolumeAttributesClassInformer { return &volumeAttributesClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/storageclass.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/storageclass.go index 2052da70e..55bbe4446 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/storageclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/storageclass.go @@ -34,12 +34,40 @@ import ( ) // StorageClassInformer provides access to a shared informer and lister for -// StorageClasses. +// StorageClasses. Prefer using the type-safe variant (see [TypedStorageClassInformer]). type StorageClassInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.StorageClassLister } +// TypedStorageClassInformer provides access to a shared informer and lister for +// StorageClasses, including the type-safe TypedInformer variant. +// It is a superset of StorageClassInformer. +type TypedStorageClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StorageClassIndexInformer + Lister() storagev1beta1.StorageClassLister +} + +// StorageClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StorageClassIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.StorageClass] + +// StorageClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StorageClass. +type StorageClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.StorageClass] + +// StorageClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StorageClass. +type StorageClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.StorageClass] + +// StorageClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StorageClass. +type StorageClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.StorageClass] + +// StorageClassIndexers is a specialization of [cache.TypedIndexers] for StorageClass. +type StorageClassIndexers = cache.TypedIndexers[*apistoragev1beta1.StorageClass] + +// DeletedStorageClass is a specialization of [cache.DeletedObject] for StorageClass. +type DeletedStorageClass = cache.DeletedObject[*apistoragev1beta1.StorageClass] + type storageClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type storageClassInformer struct { // NewStorageClassInformer constructs a new informer for StorageClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageClassInformer]). func NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStorageClassInformer constructs a new informer for StorageClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageClassIndexers) StorageClassIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStorageClassInformer constructs a new informer for StorageClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStorageClassInformer]). func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStorageClassInformer constructs a new informer for StorageClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StorageClassIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStorageClassInformerWithOptions constructs a new informer for StorageClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageClassInformerWithOptions]). func NewStorageClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStorageClassInformerWithOptions(client, options) +} + +// NewTypedStorageClassInformerWithOptions constructs a new informer for StorageClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) StorageClassIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "storageclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.StorageClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewStorageClassInformerWithOptions(client kubernetes.Interface, options int Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStorageClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *storageClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.StorageClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *storageClassInformer) TypedInformer() StorageClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.StorageClass](f.factory.InformerFor(&apistoragev1beta1.StorageClass{}, f.defaultInformer)) } func (f *storageClassInformer) Lister() storagev1beta1.StorageClassLister { return storagev1beta1.NewStorageClassLister(f.Informer().GetIndexer()) } + +// ToTypedStorageClassInformer converts an untyped informer into a TypedStorageClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageClass. If that is not the case, calling type-safe methods of the returned +// TypedStorageClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStorageClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStorageClassInformer(informer StorageClassInformer) TypedStorageClassInformer { + if informer, ok := informer.(TypedStorageClassInformer); ok { + return informer + } + return &storageClassTypedInformerAdapter{informer} +} + +type storageClassTypedInformerAdapter struct { + StorageClassInformer +} + +func (a *storageClassTypedInformerAdapter) TypedInformer() StorageClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.StorageClass](a.Informer()) +} + +// ToStorageClassIndexInformer converts an untyped informer into a StorageClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageClass. If that is not the case, calling type-safe methods of the returned +// StorageClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StorageClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStorageClassIndexInformer(informer cache.SharedIndexInformer) StorageClassIndexInformer { + if informer, ok := informer.(StorageClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.StorageClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go index 11f9840b0..d288cba13 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttachmentInformer provides access to a shared informer and lister for -// VolumeAttachments. +// VolumeAttachments. Prefer using the type-safe variant (see [TypedVolumeAttachmentInformer]). type VolumeAttachmentInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.VolumeAttachmentLister } +// TypedVolumeAttachmentInformer provides access to a shared informer and lister for +// VolumeAttachments, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttachmentInformer. +type TypedVolumeAttachmentInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttachmentIndexInformer + Lister() storagev1beta1.VolumeAttachmentLister +} + +// VolumeAttachmentIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttachmentIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.VolumeAttachment] + +// VolumeAttachmentHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttachment. +type VolumeAttachmentHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.VolumeAttachment] + +// VolumeAttachmentDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttachment. +type VolumeAttachmentDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.VolumeAttachment] + +// VolumeAttachmentFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttachment. +type VolumeAttachmentFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.VolumeAttachment] + +// VolumeAttachmentIndexers is a specialization of [cache.TypedIndexers] for VolumeAttachment. +type VolumeAttachmentIndexers = cache.TypedIndexers[*apistoragev1beta1.VolumeAttachment] + +// DeletedVolumeAttachment is a specialization of [cache.DeletedObject] for VolumeAttachment. +type DeletedVolumeAttachment = cache.DeletedObject[*apistoragev1beta1.VolumeAttachment] + type volumeAttachmentInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttachmentInformer struct { // NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformer]). func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttachmentInformer]). func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttachmentIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttachmentIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttachmentInformerWithOptions]). func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttachmentInformerWithOptions(client, options) +} + +// NewTypedVolumeAttachmentInformerWithOptions constructs a new informer for VolumeAttachment type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttachmentIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "volumeattachments"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttachment](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttachmentInformerWithOptions(client kubernetes.Interface, options Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttachmentInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.VolumeAttachment{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttachmentInformer) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttachment](f.factory.InformerFor(&apistoragev1beta1.VolumeAttachment{}, f.defaultInformer)) } func (f *volumeAttachmentInformer) Lister() storagev1beta1.VolumeAttachmentLister { return storagev1beta1.NewVolumeAttachmentLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttachmentInformer converts an untyped informer into a TypedVolumeAttachmentInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttachmentInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttachmentInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttachmentInformer(informer VolumeAttachmentInformer) TypedVolumeAttachmentInformer { + if informer, ok := informer.(TypedVolumeAttachmentInformer); ok { + return informer + } + return &volumeAttachmentTypedInformerAdapter{informer} +} + +type volumeAttachmentTypedInformerAdapter struct { + VolumeAttachmentInformer +} + +func (a *volumeAttachmentTypedInformerAdapter) TypedInformer() VolumeAttachmentIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttachment](a.Informer()) +} + +// ToVolumeAttachmentIndexInformer converts an untyped informer into a VolumeAttachmentIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttachment. If that is not the case, calling type-safe methods of the returned +// VolumeAttachmentIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttachmentIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttachmentIndexInformer(informer cache.SharedIndexInformer) VolumeAttachmentIndexInformer { + if informer, ok := informer.(VolumeAttachmentIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttachment](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattributesclass.go b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattributesclass.go index c91dfff0d..c37a0a22d 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattributesclass.go +++ b/constraint/vendor/k8s.io/client-go/informers/storage/v1beta1/volumeattributesclass.go @@ -34,12 +34,40 @@ import ( ) // VolumeAttributesClassInformer provides access to a shared informer and lister for -// VolumeAttributesClasses. +// VolumeAttributesClasses. Prefer using the type-safe variant (see [TypedVolumeAttributesClassInformer]). type VolumeAttributesClassInformer interface { Informer() cache.SharedIndexInformer Lister() storagev1beta1.VolumeAttributesClassLister } +// TypedVolumeAttributesClassInformer provides access to a shared informer and lister for +// VolumeAttributesClasses, including the type-safe TypedInformer variant. +// It is a superset of VolumeAttributesClassInformer. +type TypedVolumeAttributesClassInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() VolumeAttributesClassIndexInformer + Lister() storagev1beta1.VolumeAttributesClassLister +} + +// VolumeAttributesClassIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type VolumeAttributesClassIndexInformer cache.TypedSharedIndexInformer[*apistoragev1beta1.VolumeAttributesClass] + +// VolumeAttributesClassHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for VolumeAttributesClass. +type VolumeAttributesClassHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragev1beta1.VolumeAttributesClass] + +// VolumeAttributesClassDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for VolumeAttributesClass. +type VolumeAttributesClassDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragev1beta1.VolumeAttributesClass] + +// VolumeAttributesClassFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for VolumeAttributesClass. +type VolumeAttributesClassFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragev1beta1.VolumeAttributesClass] + +// VolumeAttributesClassIndexers is a specialization of [cache.TypedIndexers] for VolumeAttributesClass. +type VolumeAttributesClassIndexers = cache.TypedIndexers[*apistoragev1beta1.VolumeAttributesClass] + +// DeletedVolumeAttributesClass is a specialization of [cache.DeletedObject] for VolumeAttributesClass. +type DeletedVolumeAttributesClass = cache.DeletedObject[*apistoragev1beta1.VolumeAttributesClass] + type volumeAttributesClassInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type volumeAttributesClassInformer struct { // NewVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformer]). func NewVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredVolumeAttributesClassInformer]). func NewFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredVolumeAttributesClassInformer constructs a new informer for VolumeAttributesClass type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredVolumeAttributesClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers VolumeAttributesClassIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) VolumeAttributesClassIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedVolumeAttributesClassInformerWithOptions]). func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedVolumeAttributesClassInformerWithOptions(client, options) +} + +// NewTypedVolumeAttributesClassInformerWithOptions constructs a new informer for VolumeAttributesClass type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) VolumeAttributesClassIndexInformer { gvr := schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "volumeattributesclasss"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttributesClass](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewVolumeAttributesClassInformerWithOptions(client kubernetes.Interface, op Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *volumeAttributesClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedVolumeAttributesClassInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *volumeAttributesClassInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragev1beta1.VolumeAttributesClass{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *volumeAttributesClassInformer) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttributesClass](f.factory.InformerFor(&apistoragev1beta1.VolumeAttributesClass{}, f.defaultInformer)) } func (f *volumeAttributesClassInformer) Lister() storagev1beta1.VolumeAttributesClassLister { return storagev1beta1.NewVolumeAttributesClassLister(f.Informer().GetIndexer()) } + +// ToTypedVolumeAttributesClassInformer converts an untyped informer into a TypedVolumeAttributesClassInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// TypedVolumeAttributesClassInformer leads to runtime panics. A safer alternative is to pass +// around a TypedVolumeAttributesClassInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedVolumeAttributesClassInformer(informer VolumeAttributesClassInformer) TypedVolumeAttributesClassInformer { + if informer, ok := informer.(TypedVolumeAttributesClassInformer); ok { + return informer + } + return &volumeAttributesClassTypedInformerAdapter{informer} +} + +type volumeAttributesClassTypedInformerAdapter struct { + VolumeAttributesClassInformer +} + +func (a *volumeAttributesClassTypedInformerAdapter) TypedInformer() VolumeAttributesClassIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttributesClass](a.Informer()) +} + +// ToVolumeAttributesClassIndexInformer converts an untyped informer into a VolumeAttributesClassIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *VolumeAttributesClass. If that is not the case, calling type-safe methods of the returned +// VolumeAttributesClassIndexInformer leads to runtime panics. A safer alternative is to pass +// around a VolumeAttributesClassIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToVolumeAttributesClassIndexInformer(informer cache.SharedIndexInformer) VolumeAttributesClassIndexInformer { + if informer, ok := informer.(VolumeAttributesClassIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragev1beta1.VolumeAttributesClass](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storagemigration/interface.go b/constraint/vendor/k8s.io/client-go/informers/storagemigration/interface.go index 426e50fd5..5996e3652 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storagemigration/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/storagemigration/interface.go @@ -20,11 +20,14 @@ package storagemigration import ( internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + v1 "k8s.io/client-go/informers/storagemigration/v1" v1beta1 "k8s.io/client-go/informers/storagemigration/v1beta1" ) // Interface provides access to each of this group's versions. type Interface interface { + // V1 provides access to shared informers for resources in V1. + V1() v1.Interface // V1beta1 provides access to shared informers for resources in V1beta1. V1beta1() v1beta1.Interface } @@ -40,6 +43,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// V1 returns a new v1.Interface. +func (g *group) V1() v1.Interface { + return v1.New(g.factory, g.namespace, g.tweakListOptions) +} + // V1beta1 returns a new v1beta1.Interface. func (g *group) V1beta1() v1beta1.Interface { return v1beta1.New(g.factory, g.namespace, g.tweakListOptions) diff --git a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/interface.go b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/interface.go new file mode 100644 index 000000000..41854207c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/interface.go @@ -0,0 +1,45 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // StorageVersionMigrations returns a StorageVersionMigrationInformer. + StorageVersionMigrations() TypedStorageVersionMigrationInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// StorageVersionMigrations returns a TypedStorageVersionMigrationInformer. +func (v *version) StorageVersionMigrations() TypedStorageVersionMigrationInformer { + return &storageVersionMigrationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/storageversionmigration.go new file mode 100644 index 000000000..8036df40b --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1/storageversionmigration.go @@ -0,0 +1,207 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + time "time" + + apistoragemigrationv1 "k8s.io/api/storagemigration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + internalinterfaces "k8s.io/client-go/informers/internalinterfaces" + kubernetes "k8s.io/client-go/kubernetes" + storagemigrationv1 "k8s.io/client-go/listers/storagemigration/v1" + cache "k8s.io/client-go/tools/cache" +) + +// StorageVersionMigrationInformer provides access to a shared informer and lister for +// StorageVersionMigrations. Prefer using the type-safe variant (see [TypedStorageVersionMigrationInformer]). +type StorageVersionMigrationInformer interface { + Informer() cache.SharedIndexInformer + Lister() storagemigrationv1.StorageVersionMigrationLister +} + +// TypedStorageVersionMigrationInformer provides access to a shared informer and lister for +// StorageVersionMigrations, including the type-safe TypedInformer variant. +// It is a superset of StorageVersionMigrationInformer. +type TypedStorageVersionMigrationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StorageVersionMigrationIndexInformer + Lister() storagemigrationv1.StorageVersionMigrationLister +} + +// StorageVersionMigrationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StorageVersionMigrationIndexInformer cache.TypedSharedIndexInformer[*apistoragemigrationv1.StorageVersionMigration] + +// StorageVersionMigrationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StorageVersionMigration. +type StorageVersionMigrationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragemigrationv1.StorageVersionMigration] + +// StorageVersionMigrationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StorageVersionMigration. +type StorageVersionMigrationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragemigrationv1.StorageVersionMigration] + +// StorageVersionMigrationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StorageVersionMigration. +type StorageVersionMigrationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragemigrationv1.StorageVersionMigration] + +// StorageVersionMigrationIndexers is a specialization of [cache.TypedIndexers] for StorageVersionMigration. +type StorageVersionMigrationIndexers = cache.TypedIndexers[*apistoragemigrationv1.StorageVersionMigration] + +// DeletedStorageVersionMigration is a specialization of [cache.DeletedObject] for StorageVersionMigration. +type DeletedStorageVersionMigration = cache.DeletedObject[*apistoragemigrationv1.StorageVersionMigration] + +type storageVersionMigrationInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionMigrationInformer]). +func NewStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) +} + +// NewTypedStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionMigrationIndexers) StorageVersionMigrationIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + +// NewFilteredStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStorageVersionMigrationInformer]). +func NewFilteredStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionMigrationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StorageVersionMigrationIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) +} + +// NewStorageVersionMigrationInformerWithOptions constructs a new informer for StorageVersionMigration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionMigrationInformerWithOptions]). +func NewStorageVersionMigrationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, options) +} + +// NewTypedStorageVersionMigrationInformerWithOptions constructs a new informer for StorageVersionMigration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionMigrationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) StorageVersionMigrationIndexInformer { + gvr := schema.GroupVersionResource{Group: "storagemigration.k8s.io", Version: "v1", Resource: "storageversionmigrations"} + identifier := options.InformerName.WithResource(gvr) + tweakListOptions := options.TweakListOptions + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1.StorageVersionMigration](cache.NewSharedIndexInformerWithOptions( + cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ + ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.StoragemigrationV1().StorageVersionMigrations().List(context.Background(), opts) + }, + WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.StoragemigrationV1().StorageVersionMigrations().Watch(context.Background(), opts) + }, + ListWithContextFunc: func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.StoragemigrationV1().StorageVersionMigrations().List(ctx, opts) + }, + WatchFuncWithContext: func(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&opts) + } + return client.StoragemigrationV1().StorageVersionMigrations().Watch(ctx, opts) + }, + }, client), + &apistoragemigrationv1.StorageVersionMigration{}, + cache.SharedIndexInformerOptions{ + ResyncPeriod: options.ResyncPeriod, + Indexers: options.Indexers, + Identifier: identifier, + }, + )) +} + +func (f *storageVersionMigrationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) +} + +func (f *storageVersionMigrationInformer) Informer() cache.SharedIndexInformer { + return f.TypedInformer() +} + +func (f *storageVersionMigrationInformer) TypedInformer() StorageVersionMigrationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1.StorageVersionMigration](f.factory.InformerFor(&apistoragemigrationv1.StorageVersionMigration{}, f.defaultInformer)) +} + +func (f *storageVersionMigrationInformer) Lister() storagemigrationv1.StorageVersionMigrationLister { + return storagemigrationv1.NewStorageVersionMigrationLister(f.Informer().GetIndexer()) +} + +// ToTypedStorageVersionMigrationInformer converts an untyped informer into a TypedStorageVersionMigrationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersionMigration. If that is not the case, calling type-safe methods of the returned +// TypedStorageVersionMigrationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStorageVersionMigrationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStorageVersionMigrationInformer(informer StorageVersionMigrationInformer) TypedStorageVersionMigrationInformer { + if informer, ok := informer.(TypedStorageVersionMigrationInformer); ok { + return informer + } + return &storageVersionMigrationTypedInformerAdapter{informer} +} + +type storageVersionMigrationTypedInformerAdapter struct { + StorageVersionMigrationInformer +} + +func (a *storageVersionMigrationTypedInformerAdapter) TypedInformer() StorageVersionMigrationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1.StorageVersionMigration](a.Informer()) +} + +// ToStorageVersionMigrationIndexInformer converts an untyped informer into a StorageVersionMigrationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersionMigration. If that is not the case, calling type-safe methods of the returned +// StorageVersionMigrationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StorageVersionMigrationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStorageVersionMigrationIndexInformer(informer cache.SharedIndexInformer) StorageVersionMigrationIndexInformer { + if informer, ok := informer.(StorageVersionMigrationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1.StorageVersionMigration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/interface.go b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/interface.go index 220e1f5c8..0035d43b1 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/interface.go +++ b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/interface.go @@ -25,7 +25,7 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { // StorageVersionMigrations returns a StorageVersionMigrationInformer. - StorageVersionMigrations() StorageVersionMigrationInformer + StorageVersionMigrations() TypedStorageVersionMigrationInformer } type version struct { @@ -39,7 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// StorageVersionMigrations returns a StorageVersionMigrationInformer. -func (v *version) StorageVersionMigrations() StorageVersionMigrationInformer { +// StorageVersionMigrations returns a TypedStorageVersionMigrationInformer. +func (v *version) StorageVersionMigrations() TypedStorageVersionMigrationInformer { return &storageVersionMigrationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } diff --git a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/storageversionmigration.go index 50e271e6f..3b8d5f7c9 100644 --- a/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/storageversionmigration.go +++ b/constraint/vendor/k8s.io/client-go/informers/storagemigration/v1beta1/storageversionmigration.go @@ -34,12 +34,40 @@ import ( ) // StorageVersionMigrationInformer provides access to a shared informer and lister for -// StorageVersionMigrations. +// StorageVersionMigrations. Prefer using the type-safe variant (see [TypedStorageVersionMigrationInformer]). type StorageVersionMigrationInformer interface { Informer() cache.SharedIndexInformer Lister() storagemigrationv1beta1.StorageVersionMigrationLister } +// TypedStorageVersionMigrationInformer provides access to a shared informer and lister for +// StorageVersionMigrations, including the type-safe TypedInformer variant. +// It is a superset of StorageVersionMigrationInformer. +type TypedStorageVersionMigrationInformer interface { + Informer() cache.SharedIndexInformer + TypedInformer() StorageVersionMigrationIndexInformer + Lister() storagemigrationv1beta1.StorageVersionMigrationLister +} + +// StorageVersionMigrationIndexInformer is a wrapper around the underlying [cache.SharedIndexInformer] +// with type-safe variants of several methods. +type StorageVersionMigrationIndexInformer cache.TypedSharedIndexInformer[*apistoragemigrationv1beta1.StorageVersionMigration] + +// StorageVersionMigrationHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerFuncs] for StorageVersionMigration. +type StorageVersionMigrationHandlerFuncs = cache.TypedResourceEventHandlerFuncs[*apistoragemigrationv1beta1.StorageVersionMigration] + +// StorageVersionMigrationDetailedHandlerFuncs is a specialization of [cache.TypedResourceEventHandlerDetailedFuncs] for StorageVersionMigration. +type StorageVersionMigrationDetailedHandlerFuncs = cache.TypedResourceEventHandlerDetailedFuncs[*apistoragemigrationv1beta1.StorageVersionMigration] + +// StorageVersionMigrationFilteringHandler is a specialization of [cache.TypedFilteringResourceEventHandler] for StorageVersionMigration. +type StorageVersionMigrationFilteringHandler = cache.TypedFilteringResourceEventHandler[*apistoragemigrationv1beta1.StorageVersionMigration] + +// StorageVersionMigrationIndexers is a specialization of [cache.TypedIndexers] for StorageVersionMigration. +type StorageVersionMigrationIndexers = cache.TypedIndexers[*apistoragemigrationv1beta1.StorageVersionMigration] + +// DeletedStorageVersionMigration is a specialization of [cache.DeletedObject] for StorageVersionMigration. +type DeletedStorageVersionMigration = cache.DeletedObject[*apistoragemigrationv1beta1.StorageVersionMigration] + type storageVersionMigrationInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc @@ -48,25 +76,49 @@ type storageVersionMigrationInformer struct { // NewStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionMigrationInformer]). func NewStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers}) } +// NewTypedStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionMigrationIndexers) StorageVersionMigrationIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers)}) +} + // NewFilteredStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedFilteredStorageVersionMigrationInformer]). func NewFilteredStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return NewStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: indexers, TweakListOptions: tweakListOptions}) +} + +// NewTypedFilteredStorageVersionMigrationInformer constructs a new informer for StorageVersionMigration type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedFilteredStorageVersionMigrationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers StorageVersionMigrationIndexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) StorageVersionMigrationIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.TypedIndexersToIndexers(indexers), TweakListOptions: tweakListOptions}) } // NewStorageVersionMigrationInformerWithOptions constructs a new informer for StorageVersionMigration type with additional options. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. +// If you really need an independent one, prefer using the type-safe variant (see [NewTypedStorageVersionMigrationInformerWithOptions]). func NewStorageVersionMigrationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) cache.SharedIndexInformer { + return NewTypedStorageVersionMigrationInformerWithOptions(client, options) +} + +// NewTypedStorageVersionMigrationInformerWithOptions constructs a new informer for StorageVersionMigration type with additional options. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewTypedStorageVersionMigrationInformerWithOptions(client kubernetes.Interface, options internalinterfaces.InformerOptions) StorageVersionMigrationIndexInformer { gvr := schema.GroupVersionResource{Group: "storagemigration.k8s.io", Version: "v1beta1", Resource: "storageversionmigrations"} identifier := options.InformerName.WithResource(gvr) tweakListOptions := options.TweakListOptions - return cache.NewSharedIndexInformerWithOptions( + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1beta1.StorageVersionMigration](cache.NewSharedIndexInformerWithOptions( cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ ListFunc: func(opts v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { @@ -99,17 +151,57 @@ func NewStorageVersionMigrationInformerWithOptions(client kubernetes.Interface, Indexers: options.Indexers, Identifier: identifier, }, - ) + )) } func (f *storageVersionMigrationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) + return NewTypedStorageVersionMigrationInformerWithOptions(client, internalinterfaces.InformerOptions{ResyncPeriod: resyncPeriod, Indexers: cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, InformerName: f.factory.InformerName(), TweakListOptions: f.tweakListOptions}) } func (f *storageVersionMigrationInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apistoragemigrationv1beta1.StorageVersionMigration{}, f.defaultInformer) + return f.TypedInformer() +} + +func (f *storageVersionMigrationInformer) TypedInformer() StorageVersionMigrationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1beta1.StorageVersionMigration](f.factory.InformerFor(&apistoragemigrationv1beta1.StorageVersionMigration{}, f.defaultInformer)) } func (f *storageVersionMigrationInformer) Lister() storagemigrationv1beta1.StorageVersionMigrationLister { return storagemigrationv1beta1.NewStorageVersionMigrationLister(f.Informer().GetIndexer()) } + +// ToTypedStorageVersionMigrationInformer converts an untyped informer into a TypedStorageVersionMigrationInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersionMigration. If that is not the case, calling type-safe methods of the returned +// TypedStorageVersionMigrationInformer leads to runtime panics. A safer alternative is to pass +// around a TypedStorageVersionMigrationInformer instances that was obtained from a +// SharedInformerFactory. +func ToTypedStorageVersionMigrationInformer(informer StorageVersionMigrationInformer) TypedStorageVersionMigrationInformer { + if informer, ok := informer.(TypedStorageVersionMigrationInformer); ok { + return informer + } + return &storageVersionMigrationTypedInformerAdapter{informer} +} + +type storageVersionMigrationTypedInformerAdapter struct { + StorageVersionMigrationInformer +} + +func (a *storageVersionMigrationTypedInformerAdapter) TypedInformer() StorageVersionMigrationIndexInformer { + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1beta1.StorageVersionMigration](a.Informer()) +} + +// ToStorageVersionMigrationIndexInformer converts an untyped informer into a StorageVersionMigrationIndexInformer. +// +// WARNING: this conversion is only safe if the informer handles objects of type +// *StorageVersionMigration. If that is not the case, calling type-safe methods of the returned +// StorageVersionMigrationIndexInformer leads to runtime panics. A safer alternative is to pass +// around a StorageVersionMigrationIndexInformer instances that was obtained from a +// SharedInformerFactory. +func ToStorageVersionMigrationIndexInformer(informer cache.SharedIndexInformer) StorageVersionMigrationIndexInformer { + if informer, ok := informer.(StorageVersionMigrationIndexInformer); ok { + return informer + } + return cache.NewTypedSharedIndexInformer[*apistoragemigrationv1beta1.StorageVersionMigration](informer) +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/clientset.go b/constraint/vendor/k8s.io/client-go/kubernetes/clientset.go index 537609b71..4bc28060a 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/clientset.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/clientset.go @@ -55,6 +55,7 @@ import ( flowcontrolv1beta1 "k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1" flowcontrolv1beta2 "k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2" flowcontrolv1beta3 "k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3" + lifecyclev1alpha1 "k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1" networkingv1 "k8s.io/client-go/kubernetes/typed/networking/v1" networkingv1beta1 "k8s.io/client-go/kubernetes/typed/networking/v1beta1" nodev1 "k8s.io/client-go/kubernetes/typed/node/v1" @@ -70,18 +71,19 @@ import ( resourcev1beta1 "k8s.io/client-go/kubernetes/typed/resource/v1beta1" resourcev1beta2 "k8s.io/client-go/kubernetes/typed/resource/v1beta2" schedulingv1 "k8s.io/client-go/kubernetes/typed/scheduling/v1" - schedulingv1alpha2 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3" schedulingv1beta1 "k8s.io/client-go/kubernetes/typed/scheduling/v1beta1" storagev1 "k8s.io/client-go/kubernetes/typed/storage/v1" storagev1alpha1 "k8s.io/client-go/kubernetes/typed/storage/v1alpha1" storagev1beta1 "k8s.io/client-go/kubernetes/typed/storage/v1beta1" + storagemigrationv1 "k8s.io/client-go/kubernetes/typed/storagemigration/v1" storagemigrationv1beta1 "k8s.io/client-go/kubernetes/typed/storagemigration/v1beta1" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" ) type Interface interface { - Discovery() discovery.DiscoveryInterface + Discovery() discovery.DiscoveryInterfaces AdmissionregistrationV1() admissionregistrationv1.AdmissionregistrationV1Interface AdmissionregistrationV1alpha1() admissionregistrationv1alpha1.AdmissionregistrationV1alpha1Interface AdmissionregistrationV1beta1() admissionregistrationv1beta1.AdmissionregistrationV1beta1Interface @@ -114,6 +116,7 @@ type Interface interface { FlowcontrolV1beta1() flowcontrolv1beta1.FlowcontrolV1beta1Interface FlowcontrolV1beta2() flowcontrolv1beta2.FlowcontrolV1beta2Interface FlowcontrolV1beta3() flowcontrolv1beta3.FlowcontrolV1beta3Interface + LifecycleV1alpha1() lifecyclev1alpha1.LifecycleV1alpha1Interface NetworkingV1() networkingv1.NetworkingV1Interface NetworkingV1beta1() networkingv1beta1.NetworkingV1beta1Interface NodeV1() nodev1.NodeV1Interface @@ -128,12 +131,13 @@ type Interface interface { ResourceV1beta2() resourcev1beta2.ResourceV1beta2Interface ResourceV1beta1() resourcev1beta1.ResourceV1beta1Interface ResourceV1alpha3() resourcev1alpha3.ResourceV1alpha3Interface - SchedulingV1alpha2() schedulingv1alpha2.SchedulingV1alpha2Interface + SchedulingV1alpha3() schedulingv1alpha3.SchedulingV1alpha3Interface SchedulingV1beta1() schedulingv1beta1.SchedulingV1beta1Interface SchedulingV1() schedulingv1.SchedulingV1Interface StorageV1beta1() storagev1beta1.StorageV1beta1Interface StorageV1() storagev1.StorageV1Interface StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface + StoragemigrationV1() storagemigrationv1.StoragemigrationV1Interface StoragemigrationV1beta1() storagemigrationv1beta1.StoragemigrationV1beta1Interface } @@ -172,6 +176,7 @@ type Clientset struct { flowcontrolV1beta1 *flowcontrolv1beta1.FlowcontrolV1beta1Client flowcontrolV1beta2 *flowcontrolv1beta2.FlowcontrolV1beta2Client flowcontrolV1beta3 *flowcontrolv1beta3.FlowcontrolV1beta3Client + lifecycleV1alpha1 *lifecyclev1alpha1.LifecycleV1alpha1Client networkingV1 *networkingv1.NetworkingV1Client networkingV1beta1 *networkingv1beta1.NetworkingV1beta1Client nodeV1 *nodev1.NodeV1Client @@ -186,12 +191,13 @@ type Clientset struct { resourceV1beta2 *resourcev1beta2.ResourceV1beta2Client resourceV1beta1 *resourcev1beta1.ResourceV1beta1Client resourceV1alpha3 *resourcev1alpha3.ResourceV1alpha3Client - schedulingV1alpha2 *schedulingv1alpha2.SchedulingV1alpha2Client + schedulingV1alpha3 *schedulingv1alpha3.SchedulingV1alpha3Client schedulingV1beta1 *schedulingv1beta1.SchedulingV1beta1Client schedulingV1 *schedulingv1.SchedulingV1Client storageV1beta1 *storagev1beta1.StorageV1beta1Client storageV1 *storagev1.StorageV1Client storageV1alpha1 *storagev1alpha1.StorageV1alpha1Client + storagemigrationV1 *storagemigrationv1.StoragemigrationV1Client storagemigrationV1beta1 *storagemigrationv1beta1.StoragemigrationV1beta1Client } @@ -355,6 +361,11 @@ func (c *Clientset) FlowcontrolV1beta3() flowcontrolv1beta3.FlowcontrolV1beta3In return c.flowcontrolV1beta3 } +// LifecycleV1alpha1 retrieves the LifecycleV1alpha1Client +func (c *Clientset) LifecycleV1alpha1() lifecyclev1alpha1.LifecycleV1alpha1Interface { + return c.lifecycleV1alpha1 +} + // NetworkingV1 retrieves the NetworkingV1Client func (c *Clientset) NetworkingV1() networkingv1.NetworkingV1Interface { return c.networkingV1 @@ -425,9 +436,9 @@ func (c *Clientset) ResourceV1alpha3() resourcev1alpha3.ResourceV1alpha3Interfac return c.resourceV1alpha3 } -// SchedulingV1alpha2 retrieves the SchedulingV1alpha2Client -func (c *Clientset) SchedulingV1alpha2() schedulingv1alpha2.SchedulingV1alpha2Interface { - return c.schedulingV1alpha2 +// SchedulingV1alpha3 retrieves the SchedulingV1alpha3Client +func (c *Clientset) SchedulingV1alpha3() schedulingv1alpha3.SchedulingV1alpha3Interface { + return c.schedulingV1alpha3 } // SchedulingV1beta1 retrieves the SchedulingV1beta1Client @@ -455,13 +466,18 @@ func (c *Clientset) StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface { return c.storageV1alpha1 } +// StoragemigrationV1 retrieves the StoragemigrationV1Client +func (c *Clientset) StoragemigrationV1() storagemigrationv1.StoragemigrationV1Interface { + return c.storagemigrationV1 +} + // StoragemigrationV1beta1 retrieves the StoragemigrationV1beta1Client func (c *Clientset) StoragemigrationV1beta1() storagemigrationv1beta1.StoragemigrationV1beta1Interface { return c.storagemigrationV1beta1 } // Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { +func (c *Clientset) Discovery() discovery.DiscoveryInterfaces { if c == nil { return nil } @@ -632,6 +648,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } + cs.lifecycleV1alpha1, err = lifecyclev1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.networkingV1, err = networkingv1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err @@ -688,7 +708,7 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } - cs.schedulingV1alpha2, err = schedulingv1alpha2.NewForConfigAndClient(&configShallowCopy, httpClient) + cs.schedulingV1alpha3, err = schedulingv1alpha3.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err } @@ -712,6 +732,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } + cs.storagemigrationV1, err = storagemigrationv1.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.storagemigrationV1beta1, err = storagemigrationv1beta1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err @@ -769,6 +793,7 @@ func New(c rest.Interface) *Clientset { cs.flowcontrolV1beta1 = flowcontrolv1beta1.New(c) cs.flowcontrolV1beta2 = flowcontrolv1beta2.New(c) cs.flowcontrolV1beta3 = flowcontrolv1beta3.New(c) + cs.lifecycleV1alpha1 = lifecyclev1alpha1.New(c) cs.networkingV1 = networkingv1.New(c) cs.networkingV1beta1 = networkingv1beta1.New(c) cs.nodeV1 = nodev1.New(c) @@ -783,12 +808,13 @@ func New(c rest.Interface) *Clientset { cs.resourceV1beta2 = resourcev1beta2.New(c) cs.resourceV1beta1 = resourcev1beta1.New(c) cs.resourceV1alpha3 = resourcev1alpha3.New(c) - cs.schedulingV1alpha2 = schedulingv1alpha2.New(c) + cs.schedulingV1alpha3 = schedulingv1alpha3.New(c) cs.schedulingV1beta1 = schedulingv1beta1.New(c) cs.schedulingV1 = schedulingv1.New(c) cs.storageV1beta1 = storagev1beta1.New(c) cs.storageV1 = storagev1.New(c) cs.storageV1alpha1 = storagev1alpha1.New(c) + cs.storagemigrationV1 = storagemigrationv1.New(c) cs.storagemigrationV1beta1 = storagemigrationv1beta1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/scheme/register.go b/constraint/vendor/k8s.io/client-go/kubernetes/scheme/register.go index c36fe7eda..d2304c94f 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/scheme/register.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/scheme/register.go @@ -51,6 +51,7 @@ import ( flowcontrolv1beta1 "k8s.io/api/flowcontrol/v1beta1" flowcontrolv1beta2 "k8s.io/api/flowcontrol/v1beta2" flowcontrolv1beta3 "k8s.io/api/flowcontrol/v1beta3" + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" networkingv1 "k8s.io/api/networking/v1" networkingv1beta1 "k8s.io/api/networking/v1beta1" nodev1 "k8s.io/api/node/v1" @@ -66,11 +67,12 @@ import ( resourcev1beta1 "k8s.io/api/resource/v1beta1" resourcev1beta2 "k8s.io/api/resource/v1beta2" schedulingv1 "k8s.io/api/scheduling/v1" - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" storagev1 "k8s.io/api/storage/v1" storagev1alpha1 "k8s.io/api/storage/v1alpha1" storagev1beta1 "k8s.io/api/storage/v1beta1" + storagemigrationv1 "k8s.io/api/storagemigration/v1" storagemigrationv1beta1 "k8s.io/api/storagemigration/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" @@ -115,6 +117,7 @@ var localSchemeBuilder = runtime.SchemeBuilder{ flowcontrolv1beta1.AddToScheme, flowcontrolv1beta2.AddToScheme, flowcontrolv1beta3.AddToScheme, + lifecyclev1alpha1.AddToScheme, networkingv1.AddToScheme, networkingv1beta1.AddToScheme, nodev1.AddToScheme, @@ -129,12 +132,13 @@ var localSchemeBuilder = runtime.SchemeBuilder{ resourcev1beta2.AddToScheme, resourcev1beta1.AddToScheme, resourcev1alpha3.AddToScheme, - schedulingv1alpha2.AddToScheme, + schedulingv1alpha3.AddToScheme, schedulingv1beta1.AddToScheme, schedulingv1.AddToScheme, storagev1beta1.AddToScheme, storagev1.AddToScheme, storagev1alpha1.AddToScheme, + storagemigrationv1.AddToScheme, storagemigrationv1beta1.AddToScheme, } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go index a13c3559d..ed84f79e8 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go @@ -29,6 +29,8 @@ import ( type CertificatesV1Interface interface { RESTClient() rest.Interface CertificateSigningRequestsGetter + ClusterTrustBundlesGetter + PodCertificateRequestsGetter } // CertificatesV1Client is used to interact with features provided by the certificates.k8s.io group. @@ -40,6 +42,14 @@ func (c *CertificatesV1Client) CertificateSigningRequests() CertificateSigningRe return newCertificateSigningRequests(c) } +func (c *CertificatesV1Client) ClusterTrustBundles() ClusterTrustBundleInterface { + return newClusterTrustBundles(c) +} + +func (c *CertificatesV1Client) PodCertificateRequests(namespace string) PodCertificateRequestInterface { + return newPodCertificateRequests(c, namespace) +} + // NewForConfig creates a new CertificatesV1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/clustertrustbundle.go new file mode 100644 index 000000000..23a5c80ba --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/clustertrustbundle.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + certificatesv1 "k8s.io/api/certificates/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationscertificatesv1 "k8s.io/client-go/applyconfigurations/certificates/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// ClusterTrustBundlesGetter has a method to return a ClusterTrustBundleInterface. +// A group's client should implement this interface. +type ClusterTrustBundlesGetter interface { + ClusterTrustBundles() ClusterTrustBundleInterface +} + +// ClusterTrustBundleInterface has methods to work with ClusterTrustBundle resources. +type ClusterTrustBundleInterface interface { + Create(ctx context.Context, clusterTrustBundle *certificatesv1.ClusterTrustBundle, opts metav1.CreateOptions) (*certificatesv1.ClusterTrustBundle, error) + Update(ctx context.Context, clusterTrustBundle *certificatesv1.ClusterTrustBundle, opts metav1.UpdateOptions) (*certificatesv1.ClusterTrustBundle, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*certificatesv1.ClusterTrustBundle, error) + List(ctx context.Context, opts metav1.ListOptions) (*certificatesv1.ClusterTrustBundleList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *certificatesv1.ClusterTrustBundle, err error) + Apply(ctx context.Context, clusterTrustBundle *applyconfigurationscertificatesv1.ClusterTrustBundleApplyConfiguration, opts metav1.ApplyOptions) (result *certificatesv1.ClusterTrustBundle, err error) + ClusterTrustBundleExpansion +} + +// clusterTrustBundles implements ClusterTrustBundleInterface +type clusterTrustBundles struct { + *gentype.ClientWithListAndApply[*certificatesv1.ClusterTrustBundle, *certificatesv1.ClusterTrustBundleList, *applyconfigurationscertificatesv1.ClusterTrustBundleApplyConfiguration] +} + +// newClusterTrustBundles returns a ClusterTrustBundles +func newClusterTrustBundles(c *CertificatesV1Client) *clusterTrustBundles { + return &clusterTrustBundles{ + gentype.NewClientWithListAndApply[*certificatesv1.ClusterTrustBundle, *certificatesv1.ClusterTrustBundleList, *applyconfigurationscertificatesv1.ClusterTrustBundleApplyConfiguration]( + "clustertrustbundles", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *certificatesv1.ClusterTrustBundle { return &certificatesv1.ClusterTrustBundle{} }, + func() *certificatesv1.ClusterTrustBundleList { return &certificatesv1.ClusterTrustBundleList{} }, + gentype.PrefersProtobuf[*certificatesv1.ClusterTrustBundle](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/generated_expansion.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/generated_expansion.go index 95fad0212..902440535 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/generated_expansion.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/generated_expansion.go @@ -19,3 +19,7 @@ limitations under the License. package v1 type CertificateSigningRequestExpansion interface{} + +type ClusterTrustBundleExpansion interface{} + +type PodCertificateRequestExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/podcertificaterequest.go new file mode 100644 index 000000000..128d1e5ff --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/certificates/v1/podcertificaterequest.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + certificatesv1 "k8s.io/api/certificates/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationscertificatesv1 "k8s.io/client-go/applyconfigurations/certificates/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// PodCertificateRequestsGetter has a method to return a PodCertificateRequestInterface. +// A group's client should implement this interface. +type PodCertificateRequestsGetter interface { + PodCertificateRequests(namespace string) PodCertificateRequestInterface +} + +// PodCertificateRequestInterface has methods to work with PodCertificateRequest resources. +type PodCertificateRequestInterface interface { + Create(ctx context.Context, podCertificateRequest *certificatesv1.PodCertificateRequest, opts metav1.CreateOptions) (*certificatesv1.PodCertificateRequest, error) + Update(ctx context.Context, podCertificateRequest *certificatesv1.PodCertificateRequest, opts metav1.UpdateOptions) (*certificatesv1.PodCertificateRequest, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, podCertificateRequest *certificatesv1.PodCertificateRequest, opts metav1.UpdateOptions) (*certificatesv1.PodCertificateRequest, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*certificatesv1.PodCertificateRequest, error) + List(ctx context.Context, opts metav1.ListOptions) (*certificatesv1.PodCertificateRequestList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *certificatesv1.PodCertificateRequest, err error) + Apply(ctx context.Context, podCertificateRequest *applyconfigurationscertificatesv1.PodCertificateRequestApplyConfiguration, opts metav1.ApplyOptions) (result *certificatesv1.PodCertificateRequest, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, podCertificateRequest *applyconfigurationscertificatesv1.PodCertificateRequestApplyConfiguration, opts metav1.ApplyOptions) (result *certificatesv1.PodCertificateRequest, err error) + PodCertificateRequestExpansion +} + +// podCertificateRequests implements PodCertificateRequestInterface +type podCertificateRequests struct { + *gentype.ClientWithListAndApply[*certificatesv1.PodCertificateRequest, *certificatesv1.PodCertificateRequestList, *applyconfigurationscertificatesv1.PodCertificateRequestApplyConfiguration] +} + +// newPodCertificateRequests returns a PodCertificateRequests +func newPodCertificateRequests(c *CertificatesV1Client, namespace string) *podCertificateRequests { + return &podCertificateRequests{ + gentype.NewClientWithListAndApply[*certificatesv1.PodCertificateRequest, *certificatesv1.PodCertificateRequestList, *applyconfigurationscertificatesv1.PodCertificateRequestApplyConfiguration]( + "podcertificaterequests", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *certificatesv1.PodCertificateRequest { return &certificatesv1.PodCertificateRequest{} }, + func() *certificatesv1.PodCertificateRequestList { return &certificatesv1.PodCertificateRequestList{} }, + gentype.PrefersProtobuf[*certificatesv1.PodCertificateRequest](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/doc.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/doc.go similarity index 97% rename from constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/doc.go rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/doc.go index baaf2d985..df51baa4d 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/doc.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. // This package has the automatically generated typed clients. -package v1alpha2 +package v1alpha1 diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/eviction.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/eviction.go new file mode 100644 index 000000000..10a359c29 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/eviction.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationslifecyclev1alpha1 "k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// EvictionsGetter has a method to return a EvictionInterface. +// A group's client should implement this interface. +type EvictionsGetter interface { + Evictions(namespace string) EvictionInterface +} + +// EvictionInterface has methods to work with Eviction resources. +type EvictionInterface interface { + Create(ctx context.Context, eviction *lifecyclev1alpha1.Eviction, opts v1.CreateOptions) (*lifecyclev1alpha1.Eviction, error) + Update(ctx context.Context, eviction *lifecyclev1alpha1.Eviction, opts v1.UpdateOptions) (*lifecyclev1alpha1.Eviction, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, eviction *lifecyclev1alpha1.Eviction, opts v1.UpdateOptions) (*lifecyclev1alpha1.Eviction, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*lifecyclev1alpha1.Eviction, error) + List(ctx context.Context, opts v1.ListOptions) (*lifecyclev1alpha1.EvictionList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *lifecyclev1alpha1.Eviction, err error) + Apply(ctx context.Context, eviction *applyconfigurationslifecyclev1alpha1.EvictionApplyConfiguration, opts v1.ApplyOptions) (result *lifecyclev1alpha1.Eviction, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, eviction *applyconfigurationslifecyclev1alpha1.EvictionApplyConfiguration, opts v1.ApplyOptions) (result *lifecyclev1alpha1.Eviction, err error) + EvictionExpansion +} + +// evictions implements EvictionInterface +type evictions struct { + *gentype.ClientWithListAndApply[*lifecyclev1alpha1.Eviction, *lifecyclev1alpha1.EvictionList, *applyconfigurationslifecyclev1alpha1.EvictionApplyConfiguration] +} + +// newEvictions returns a Evictions +func newEvictions(c *LifecycleV1alpha1Client, namespace string) *evictions { + return &evictions{ + gentype.NewClientWithListAndApply[*lifecyclev1alpha1.Eviction, *lifecyclev1alpha1.EvictionList, *applyconfigurationslifecyclev1alpha1.EvictionApplyConfiguration]( + "evictions", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *lifecyclev1alpha1.Eviction { return &lifecyclev1alpha1.Eviction{} }, + func() *lifecyclev1alpha1.EvictionList { return &lifecyclev1alpha1.EvictionList{} }, + gentype.PrefersProtobuf[*lifecyclev1alpha1.Eviction](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/evictionrequest.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/evictionrequest.go new file mode 100644 index 000000000..4a21127bb --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/evictionrequest.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationslifecyclev1alpha1 "k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// EvictionRequestsGetter has a method to return a EvictionRequestInterface. +// A group's client should implement this interface. +type EvictionRequestsGetter interface { + EvictionRequests(namespace string) EvictionRequestInterface +} + +// EvictionRequestInterface has methods to work with EvictionRequest resources. +type EvictionRequestInterface interface { + Create(ctx context.Context, evictionRequest *lifecyclev1alpha1.EvictionRequest, opts v1.CreateOptions) (*lifecyclev1alpha1.EvictionRequest, error) + Update(ctx context.Context, evictionRequest *lifecyclev1alpha1.EvictionRequest, opts v1.UpdateOptions) (*lifecyclev1alpha1.EvictionRequest, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, evictionRequest *lifecyclev1alpha1.EvictionRequest, opts v1.UpdateOptions) (*lifecyclev1alpha1.EvictionRequest, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*lifecyclev1alpha1.EvictionRequest, error) + List(ctx context.Context, opts v1.ListOptions) (*lifecyclev1alpha1.EvictionRequestList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *lifecyclev1alpha1.EvictionRequest, err error) + Apply(ctx context.Context, evictionRequest *applyconfigurationslifecyclev1alpha1.EvictionRequestApplyConfiguration, opts v1.ApplyOptions) (result *lifecyclev1alpha1.EvictionRequest, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, evictionRequest *applyconfigurationslifecyclev1alpha1.EvictionRequestApplyConfiguration, opts v1.ApplyOptions) (result *lifecyclev1alpha1.EvictionRequest, err error) + EvictionRequestExpansion +} + +// evictionRequests implements EvictionRequestInterface +type evictionRequests struct { + *gentype.ClientWithListAndApply[*lifecyclev1alpha1.EvictionRequest, *lifecyclev1alpha1.EvictionRequestList, *applyconfigurationslifecyclev1alpha1.EvictionRequestApplyConfiguration] +} + +// newEvictionRequests returns a EvictionRequests +func newEvictionRequests(c *LifecycleV1alpha1Client, namespace string) *evictionRequests { + return &evictionRequests{ + gentype.NewClientWithListAndApply[*lifecyclev1alpha1.EvictionRequest, *lifecyclev1alpha1.EvictionRequestList, *applyconfigurationslifecyclev1alpha1.EvictionRequestApplyConfiguration]( + "evictionrequests", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *lifecyclev1alpha1.EvictionRequest { return &lifecyclev1alpha1.EvictionRequest{} }, + func() *lifecyclev1alpha1.EvictionRequestList { return &lifecyclev1alpha1.EvictionRequestList{} }, + gentype.PrefersProtobuf[*lifecyclev1alpha1.EvictionRequest](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/generated_expansion.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/generated_expansion.go new file mode 100644 index 000000000..4be788fdf --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/generated_expansion.go @@ -0,0 +1,23 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +type EvictionExpansion interface{} + +type EvictionRequestExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/lifecycle_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/lifecycle_client.go new file mode 100644 index 000000000..02c050b82 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1/lifecycle_client.go @@ -0,0 +1,106 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + http "net/http" + + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + scheme "k8s.io/client-go/kubernetes/scheme" + rest "k8s.io/client-go/rest" +) + +type LifecycleV1alpha1Interface interface { + RESTClient() rest.Interface + EvictionsGetter + EvictionRequestsGetter +} + +// LifecycleV1alpha1Client is used to interact with features provided by the lifecycle.k8s.io group. +type LifecycleV1alpha1Client struct { + restClient rest.Interface +} + +func (c *LifecycleV1alpha1Client) Evictions(namespace string) EvictionInterface { + return newEvictions(c, namespace) +} + +func (c *LifecycleV1alpha1Client) EvictionRequests(namespace string) EvictionRequestInterface { + return newEvictionRequests(c, namespace) +} + +// NewForConfig creates a new LifecycleV1alpha1Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*LifecycleV1alpha1Client, error) { + config := *c + setConfigDefaults(&config) + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new LifecycleV1alpha1Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*LifecycleV1alpha1Client, error) { + config := *c + setConfigDefaults(&config) + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &LifecycleV1alpha1Client{client}, nil +} + +// NewForConfigOrDie creates a new LifecycleV1alpha1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *LifecycleV1alpha1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new LifecycleV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *LifecycleV1alpha1Client { + return &LifecycleV1alpha1Client{c} +} + +func setConfigDefaults(config *rest.Config) { + gv := lifecyclev1alpha1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *LifecycleV1alpha1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/devicetaintrule.go new file mode 100644 index 000000000..43074f75a --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/devicetaintrule.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + resourcev1 "k8s.io/api/resource/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsresourcev1 "k8s.io/client-go/applyconfigurations/resource/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// DeviceTaintRulesGetter has a method to return a DeviceTaintRuleInterface. +// A group's client should implement this interface. +type DeviceTaintRulesGetter interface { + DeviceTaintRules() DeviceTaintRuleInterface +} + +// DeviceTaintRuleInterface has methods to work with DeviceTaintRule resources. +type DeviceTaintRuleInterface interface { + Create(ctx context.Context, deviceTaintRule *resourcev1.DeviceTaintRule, opts metav1.CreateOptions) (*resourcev1.DeviceTaintRule, error) + Update(ctx context.Context, deviceTaintRule *resourcev1.DeviceTaintRule, opts metav1.UpdateOptions) (*resourcev1.DeviceTaintRule, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, deviceTaintRule *resourcev1.DeviceTaintRule, opts metav1.UpdateOptions) (*resourcev1.DeviceTaintRule, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*resourcev1.DeviceTaintRule, error) + List(ctx context.Context, opts metav1.ListOptions) (*resourcev1.DeviceTaintRuleList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *resourcev1.DeviceTaintRule, err error) + Apply(ctx context.Context, deviceTaintRule *applyconfigurationsresourcev1.DeviceTaintRuleApplyConfiguration, opts metav1.ApplyOptions) (result *resourcev1.DeviceTaintRule, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, deviceTaintRule *applyconfigurationsresourcev1.DeviceTaintRuleApplyConfiguration, opts metav1.ApplyOptions) (result *resourcev1.DeviceTaintRule, err error) + DeviceTaintRuleExpansion +} + +// deviceTaintRules implements DeviceTaintRuleInterface +type deviceTaintRules struct { + *gentype.ClientWithListAndApply[*resourcev1.DeviceTaintRule, *resourcev1.DeviceTaintRuleList, *applyconfigurationsresourcev1.DeviceTaintRuleApplyConfiguration] +} + +// newDeviceTaintRules returns a DeviceTaintRules +func newDeviceTaintRules(c *ResourceV1Client) *deviceTaintRules { + return &deviceTaintRules{ + gentype.NewClientWithListAndApply[*resourcev1.DeviceTaintRule, *resourcev1.DeviceTaintRuleList, *applyconfigurationsresourcev1.DeviceTaintRuleApplyConfiguration]( + "devicetaintrules", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *resourcev1.DeviceTaintRule { return &resourcev1.DeviceTaintRule{} }, + func() *resourcev1.DeviceTaintRuleList { return &resourcev1.DeviceTaintRuleList{} }, + gentype.PrefersProtobuf[*resourcev1.DeviceTaintRule](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/generated_expansion.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/generated_expansion.go index ea3096858..6cd11a805 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/generated_expansion.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/generated_expansion.go @@ -20,6 +20,8 @@ package v1 type DeviceClassExpansion interface{} +type DeviceTaintRuleExpansion interface{} + type ResourceClaimExpansion interface{} type ResourceClaimTemplateExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/resource_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/resource_client.go index e610012dd..0267cb68a 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/resource_client.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/resource/v1/resource_client.go @@ -29,6 +29,7 @@ import ( type ResourceV1Interface interface { RESTClient() rest.Interface DeviceClassesGetter + DeviceTaintRulesGetter ResourceClaimsGetter ResourceClaimTemplatesGetter ResourceSlicesGetter @@ -43,6 +44,10 @@ func (c *ResourceV1Client) DeviceClasses() DeviceClassInterface { return newDeviceClasses(c) } +func (c *ResourceV1Client) DeviceTaintRules() DeviceTaintRuleInterface { + return newDeviceTaintRules(c) +} + func (c *ResourceV1Client) ResourceClaims(namespace string) ResourceClaimInterface { return newResourceClaims(c, namespace) } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/compositepodgroup.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/compositepodgroup.go new file mode 100644 index 000000000..a301cbd35 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/compositepodgroup.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + context "context" + + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsschedulingv1alpha3 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha3" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// CompositePodGroupsGetter has a method to return a CompositePodGroupInterface. +// A group's client should implement this interface. +type CompositePodGroupsGetter interface { + CompositePodGroups(namespace string) CompositePodGroupInterface +} + +// CompositePodGroupInterface has methods to work with CompositePodGroup resources. +type CompositePodGroupInterface interface { + Create(ctx context.Context, compositePodGroup *schedulingv1alpha3.CompositePodGroup, opts v1.CreateOptions) (*schedulingv1alpha3.CompositePodGroup, error) + Update(ctx context.Context, compositePodGroup *schedulingv1alpha3.CompositePodGroup, opts v1.UpdateOptions) (*schedulingv1alpha3.CompositePodGroup, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, compositePodGroup *schedulingv1alpha3.CompositePodGroup, opts v1.UpdateOptions) (*schedulingv1alpha3.CompositePodGroup, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1alpha3.CompositePodGroup, error) + List(ctx context.Context, opts v1.ListOptions) (*schedulingv1alpha3.CompositePodGroupList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1alpha3.CompositePodGroup, err error) + Apply(ctx context.Context, compositePodGroup *applyconfigurationsschedulingv1alpha3.CompositePodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha3.CompositePodGroup, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, compositePodGroup *applyconfigurationsschedulingv1alpha3.CompositePodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha3.CompositePodGroup, err error) + CompositePodGroupExpansion +} + +// compositePodGroups implements CompositePodGroupInterface +type compositePodGroups struct { + *gentype.ClientWithListAndApply[*schedulingv1alpha3.CompositePodGroup, *schedulingv1alpha3.CompositePodGroupList, *applyconfigurationsschedulingv1alpha3.CompositePodGroupApplyConfiguration] +} + +// newCompositePodGroups returns a CompositePodGroups +func newCompositePodGroups(c *SchedulingV1alpha3Client, namespace string) *compositePodGroups { + return &compositePodGroups{ + gentype.NewClientWithListAndApply[*schedulingv1alpha3.CompositePodGroup, *schedulingv1alpha3.CompositePodGroupList, *applyconfigurationsschedulingv1alpha3.CompositePodGroupApplyConfiguration]( + "compositepodgroups", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *schedulingv1alpha3.CompositePodGroup { return &schedulingv1alpha3.CompositePodGroup{} }, + func() *schedulingv1alpha3.CompositePodGroupList { return &schedulingv1alpha3.CompositePodGroupList{} }, + gentype.PrefersProtobuf[*schedulingv1alpha3.CompositePodGroup](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/doc.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/doc.go new file mode 100644 index 000000000..fdb23fd37 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/doc.go @@ -0,0 +1,20 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1alpha3 diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/generated_expansion.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/generated_expansion.go similarity index 91% rename from constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/generated_expansion.go rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/generated_expansion.go index 60668af04..a222ec460 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/generated_expansion.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/generated_expansion.go @@ -16,7 +16,9 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 + +type CompositePodGroupExpansion interface{} type PodGroupExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/podgroup.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/podgroup.go similarity index 59% rename from constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/podgroup.go rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/podgroup.go index bbe91d35a..81024d7e6 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/podgroup.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/podgroup.go @@ -16,16 +16,16 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( context "context" - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - applyconfigurationsschedulingv1alpha2 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha2" + applyconfigurationsschedulingv1alpha3 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha3" gentype "k8s.io/client-go/gentype" scheme "k8s.io/client-go/kubernetes/scheme" ) @@ -38,38 +38,38 @@ type PodGroupsGetter interface { // PodGroupInterface has methods to work with PodGroup resources. type PodGroupInterface interface { - Create(ctx context.Context, podGroup *schedulingv1alpha2.PodGroup, opts v1.CreateOptions) (*schedulingv1alpha2.PodGroup, error) - Update(ctx context.Context, podGroup *schedulingv1alpha2.PodGroup, opts v1.UpdateOptions) (*schedulingv1alpha2.PodGroup, error) + Create(ctx context.Context, podGroup *schedulingv1alpha3.PodGroup, opts v1.CreateOptions) (*schedulingv1alpha3.PodGroup, error) + Update(ctx context.Context, podGroup *schedulingv1alpha3.PodGroup, opts v1.UpdateOptions) (*schedulingv1alpha3.PodGroup, error) // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, podGroup *schedulingv1alpha2.PodGroup, opts v1.UpdateOptions) (*schedulingv1alpha2.PodGroup, error) + UpdateStatus(ctx context.Context, podGroup *schedulingv1alpha3.PodGroup, opts v1.UpdateOptions) (*schedulingv1alpha3.PodGroup, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1alpha2.PodGroup, error) - List(ctx context.Context, opts v1.ListOptions) (*schedulingv1alpha2.PodGroupList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1alpha3.PodGroup, error) + List(ctx context.Context, opts v1.ListOptions) (*schedulingv1alpha3.PodGroupList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1alpha2.PodGroup, err error) - Apply(ctx context.Context, podGroup *applyconfigurationsschedulingv1alpha2.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha2.PodGroup, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1alpha3.PodGroup, err error) + Apply(ctx context.Context, podGroup *applyconfigurationsschedulingv1alpha3.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha3.PodGroup, err error) // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). - ApplyStatus(ctx context.Context, podGroup *applyconfigurationsschedulingv1alpha2.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha2.PodGroup, err error) + ApplyStatus(ctx context.Context, podGroup *applyconfigurationsschedulingv1alpha3.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha3.PodGroup, err error) PodGroupExpansion } // podGroups implements PodGroupInterface type podGroups struct { - *gentype.ClientWithListAndApply[*schedulingv1alpha2.PodGroup, *schedulingv1alpha2.PodGroupList, *applyconfigurationsschedulingv1alpha2.PodGroupApplyConfiguration] + *gentype.ClientWithListAndApply[*schedulingv1alpha3.PodGroup, *schedulingv1alpha3.PodGroupList, *applyconfigurationsschedulingv1alpha3.PodGroupApplyConfiguration] } // newPodGroups returns a PodGroups -func newPodGroups(c *SchedulingV1alpha2Client, namespace string) *podGroups { +func newPodGroups(c *SchedulingV1alpha3Client, namespace string) *podGroups { return &podGroups{ - gentype.NewClientWithListAndApply[*schedulingv1alpha2.PodGroup, *schedulingv1alpha2.PodGroupList, *applyconfigurationsschedulingv1alpha2.PodGroupApplyConfiguration]( + gentype.NewClientWithListAndApply[*schedulingv1alpha3.PodGroup, *schedulingv1alpha3.PodGroupList, *applyconfigurationsschedulingv1alpha3.PodGroupApplyConfiguration]( "podgroups", c.RESTClient(), scheme.ParameterCodec, namespace, - func() *schedulingv1alpha2.PodGroup { return &schedulingv1alpha2.PodGroup{} }, - func() *schedulingv1alpha2.PodGroupList { return &schedulingv1alpha2.PodGroupList{} }, - gentype.PrefersProtobuf[*schedulingv1alpha2.PodGroup](), + func() *schedulingv1alpha3.PodGroup { return &schedulingv1alpha3.PodGroup{} }, + func() *schedulingv1alpha3.PodGroupList { return &schedulingv1alpha3.PodGroupList{} }, + gentype.PrefersProtobuf[*schedulingv1alpha3.PodGroup](), ), } } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/scheduling_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/scheduling_client.go similarity index 65% rename from constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/scheduling_client.go rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/scheduling_client.go index 8ccdc178b..8c99d51ca 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/scheduling_client.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/scheduling_client.go @@ -16,39 +16,44 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( http "net/http" - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) -type SchedulingV1alpha2Interface interface { +type SchedulingV1alpha3Interface interface { RESTClient() rest.Interface + CompositePodGroupsGetter PodGroupsGetter WorkloadsGetter } -// SchedulingV1alpha2Client is used to interact with features provided by the scheduling.k8s.io group. -type SchedulingV1alpha2Client struct { +// SchedulingV1alpha3Client is used to interact with features provided by the scheduling.k8s.io group. +type SchedulingV1alpha3Client struct { restClient rest.Interface } -func (c *SchedulingV1alpha2Client) PodGroups(namespace string) PodGroupInterface { +func (c *SchedulingV1alpha3Client) CompositePodGroups(namespace string) CompositePodGroupInterface { + return newCompositePodGroups(c, namespace) +} + +func (c *SchedulingV1alpha3Client) PodGroups(namespace string) PodGroupInterface { return newPodGroups(c, namespace) } -func (c *SchedulingV1alpha2Client) Workloads(namespace string) WorkloadInterface { +func (c *SchedulingV1alpha3Client) Workloads(namespace string) WorkloadInterface { return newWorkloads(c, namespace) } -// NewForConfig creates a new SchedulingV1alpha2Client for the given config. +// NewForConfig creates a new SchedulingV1alpha3Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*SchedulingV1alpha2Client, error) { +func NewForConfig(c *rest.Config) (*SchedulingV1alpha3Client, error) { config := *c setConfigDefaults(&config) httpClient, err := rest.HTTPClientFor(&config) @@ -58,21 +63,21 @@ func NewForConfig(c *rest.Config) (*SchedulingV1alpha2Client, error) { return NewForConfigAndClient(&config, httpClient) } -// NewForConfigAndClient creates a new SchedulingV1alpha2Client for the given config and http client. +// NewForConfigAndClient creates a new SchedulingV1alpha3Client for the given config and http client. // Note the http client provided takes precedence over the configured transport values. -func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1alpha2Client, error) { +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1alpha3Client, error) { config := *c setConfigDefaults(&config) client, err := rest.RESTClientForConfigAndClient(&config, h) if err != nil { return nil, err } - return &SchedulingV1alpha2Client{client}, nil + return &SchedulingV1alpha3Client{client}, nil } -// NewForConfigOrDie creates a new SchedulingV1alpha2Client for the given config and +// NewForConfigOrDie creates a new SchedulingV1alpha3Client for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha2Client { +func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha3Client { client, err := NewForConfig(c) if err != nil { panic(err) @@ -80,13 +85,13 @@ func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha2Client { return client } -// New creates a new SchedulingV1alpha2Client for the given RESTClient. -func New(c rest.Interface) *SchedulingV1alpha2Client { - return &SchedulingV1alpha2Client{c} +// New creates a new SchedulingV1alpha3Client for the given RESTClient. +func New(c rest.Interface) *SchedulingV1alpha3Client { + return &SchedulingV1alpha3Client{c} } func setConfigDefaults(config *rest.Config) { - gv := schedulingv1alpha2.SchemeGroupVersion + gv := schedulingv1alpha3.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() @@ -98,7 +103,7 @@ func setConfigDefaults(config *rest.Config) { // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. -func (c *SchedulingV1alpha2Client) RESTClient() rest.Interface { +func (c *SchedulingV1alpha3Client) RESTClient() rest.Interface { if c == nil { return nil } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/workload.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/workload.go similarity index 62% rename from constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/workload.go rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/workload.go index 89790940b..f4c9d7cf6 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2/workload.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3/workload.go @@ -16,16 +16,16 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( context "context" - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" - applyconfigurationsschedulingv1alpha2 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha2" + applyconfigurationsschedulingv1alpha3 "k8s.io/client-go/applyconfigurations/scheduling/v1alpha3" gentype "k8s.io/client-go/gentype" scheme "k8s.io/client-go/kubernetes/scheme" ) @@ -38,34 +38,34 @@ type WorkloadsGetter interface { // WorkloadInterface has methods to work with Workload resources. type WorkloadInterface interface { - Create(ctx context.Context, workload *schedulingv1alpha2.Workload, opts v1.CreateOptions) (*schedulingv1alpha2.Workload, error) - Update(ctx context.Context, workload *schedulingv1alpha2.Workload, opts v1.UpdateOptions) (*schedulingv1alpha2.Workload, error) + Create(ctx context.Context, workload *schedulingv1alpha3.Workload, opts v1.CreateOptions) (*schedulingv1alpha3.Workload, error) + Update(ctx context.Context, workload *schedulingv1alpha3.Workload, opts v1.UpdateOptions) (*schedulingv1alpha3.Workload, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1alpha2.Workload, error) - List(ctx context.Context, opts v1.ListOptions) (*schedulingv1alpha2.WorkloadList, error) + Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1alpha3.Workload, error) + List(ctx context.Context, opts v1.ListOptions) (*schedulingv1alpha3.WorkloadList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1alpha2.Workload, err error) - Apply(ctx context.Context, workload *applyconfigurationsschedulingv1alpha2.WorkloadApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha2.Workload, err error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1alpha3.Workload, err error) + Apply(ctx context.Context, workload *applyconfigurationsschedulingv1alpha3.WorkloadApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1alpha3.Workload, err error) WorkloadExpansion } // workloads implements WorkloadInterface type workloads struct { - *gentype.ClientWithListAndApply[*schedulingv1alpha2.Workload, *schedulingv1alpha2.WorkloadList, *applyconfigurationsschedulingv1alpha2.WorkloadApplyConfiguration] + *gentype.ClientWithListAndApply[*schedulingv1alpha3.Workload, *schedulingv1alpha3.WorkloadList, *applyconfigurationsschedulingv1alpha3.WorkloadApplyConfiguration] } // newWorkloads returns a Workloads -func newWorkloads(c *SchedulingV1alpha2Client, namespace string) *workloads { +func newWorkloads(c *SchedulingV1alpha3Client, namespace string) *workloads { return &workloads{ - gentype.NewClientWithListAndApply[*schedulingv1alpha2.Workload, *schedulingv1alpha2.WorkloadList, *applyconfigurationsschedulingv1alpha2.WorkloadApplyConfiguration]( + gentype.NewClientWithListAndApply[*schedulingv1alpha3.Workload, *schedulingv1alpha3.WorkloadList, *applyconfigurationsschedulingv1alpha3.WorkloadApplyConfiguration]( "workloads", c.RESTClient(), scheme.ParameterCodec, namespace, - func() *schedulingv1alpha2.Workload { return &schedulingv1alpha2.Workload{} }, - func() *schedulingv1alpha2.WorkloadList { return &schedulingv1alpha2.WorkloadList{} }, - gentype.PrefersProtobuf[*schedulingv1alpha2.Workload](), + func() *schedulingv1alpha3.Workload { return &schedulingv1alpha3.Workload{} }, + func() *schedulingv1alpha3.WorkloadList { return &schedulingv1alpha3.WorkloadList{} }, + gentype.PrefersProtobuf[*schedulingv1alpha3.Workload](), ), } } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/generated_expansion.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/generated_expansion.go index 3bab873e6..719e1e0e5 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/generated_expansion.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/generated_expansion.go @@ -18,4 +18,8 @@ limitations under the License. package v1beta1 +type PodGroupExpansion interface{} + type PriorityClassExpansion interface{} + +type WorkloadExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/podgroup.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/podgroup.go new file mode 100644 index 000000000..4eb85b94c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/podgroup.go @@ -0,0 +1,75 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsschedulingv1beta1 "k8s.io/client-go/applyconfigurations/scheduling/v1beta1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// PodGroupsGetter has a method to return a PodGroupInterface. +// A group's client should implement this interface. +type PodGroupsGetter interface { + PodGroups(namespace string) PodGroupInterface +} + +// PodGroupInterface has methods to work with PodGroup resources. +type PodGroupInterface interface { + Create(ctx context.Context, podGroup *schedulingv1beta1.PodGroup, opts v1.CreateOptions) (*schedulingv1beta1.PodGroup, error) + Update(ctx context.Context, podGroup *schedulingv1beta1.PodGroup, opts v1.UpdateOptions) (*schedulingv1beta1.PodGroup, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, podGroup *schedulingv1beta1.PodGroup, opts v1.UpdateOptions) (*schedulingv1beta1.PodGroup, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1beta1.PodGroup, error) + List(ctx context.Context, opts v1.ListOptions) (*schedulingv1beta1.PodGroupList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1beta1.PodGroup, err error) + Apply(ctx context.Context, podGroup *applyconfigurationsschedulingv1beta1.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1beta1.PodGroup, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, podGroup *applyconfigurationsschedulingv1beta1.PodGroupApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1beta1.PodGroup, err error) + PodGroupExpansion +} + +// podGroups implements PodGroupInterface +type podGroups struct { + *gentype.ClientWithListAndApply[*schedulingv1beta1.PodGroup, *schedulingv1beta1.PodGroupList, *applyconfigurationsschedulingv1beta1.PodGroupApplyConfiguration] +} + +// newPodGroups returns a PodGroups +func newPodGroups(c *SchedulingV1beta1Client, namespace string) *podGroups { + return &podGroups{ + gentype.NewClientWithListAndApply[*schedulingv1beta1.PodGroup, *schedulingv1beta1.PodGroupList, *applyconfigurationsschedulingv1beta1.PodGroupApplyConfiguration]( + "podgroups", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *schedulingv1beta1.PodGroup { return &schedulingv1beta1.PodGroup{} }, + func() *schedulingv1beta1.PodGroupList { return &schedulingv1beta1.PodGroupList{} }, + gentype.PrefersProtobuf[*schedulingv1beta1.PodGroup](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go index 0b2aa0e1a..b2d7e6d26 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go @@ -28,7 +28,9 @@ import ( type SchedulingV1beta1Interface interface { RESTClient() rest.Interface + PodGroupsGetter PriorityClassesGetter + WorkloadsGetter } // SchedulingV1beta1Client is used to interact with features provided by the scheduling.k8s.io group. @@ -36,10 +38,18 @@ type SchedulingV1beta1Client struct { restClient rest.Interface } +func (c *SchedulingV1beta1Client) PodGroups(namespace string) PodGroupInterface { + return newPodGroups(c, namespace) +} + func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface { return newPriorityClasses(c) } +func (c *SchedulingV1beta1Client) Workloads(namespace string) WorkloadInterface { + return newWorkloads(c, namespace) +} + // NewForConfig creates a new SchedulingV1beta1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/workload.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/workload.go new file mode 100644 index 000000000..e5313ab59 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/workload.go @@ -0,0 +1,71 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + context "context" + + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsschedulingv1beta1 "k8s.io/client-go/applyconfigurations/scheduling/v1beta1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// WorkloadsGetter has a method to return a WorkloadInterface. +// A group's client should implement this interface. +type WorkloadsGetter interface { + Workloads(namespace string) WorkloadInterface +} + +// WorkloadInterface has methods to work with Workload resources. +type WorkloadInterface interface { + Create(ctx context.Context, workload *schedulingv1beta1.Workload, opts v1.CreateOptions) (*schedulingv1beta1.Workload, error) + Update(ctx context.Context, workload *schedulingv1beta1.Workload, opts v1.UpdateOptions) (*schedulingv1beta1.Workload, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*schedulingv1beta1.Workload, error) + List(ctx context.Context, opts v1.ListOptions) (*schedulingv1beta1.WorkloadList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *schedulingv1beta1.Workload, err error) + Apply(ctx context.Context, workload *applyconfigurationsschedulingv1beta1.WorkloadApplyConfiguration, opts v1.ApplyOptions) (result *schedulingv1beta1.Workload, err error) + WorkloadExpansion +} + +// workloads implements WorkloadInterface +type workloads struct { + *gentype.ClientWithListAndApply[*schedulingv1beta1.Workload, *schedulingv1beta1.WorkloadList, *applyconfigurationsschedulingv1beta1.WorkloadApplyConfiguration] +} + +// newWorkloads returns a Workloads +func newWorkloads(c *SchedulingV1beta1Client, namespace string) *workloads { + return &workloads{ + gentype.NewClientWithListAndApply[*schedulingv1beta1.Workload, *schedulingv1beta1.WorkloadList, *applyconfigurationsschedulingv1beta1.WorkloadApplyConfiguration]( + "workloads", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *schedulingv1beta1.Workload { return &schedulingv1beta1.Workload{} }, + func() *schedulingv1beta1.WorkloadList { return &schedulingv1beta1.WorkloadList{} }, + gentype.PrefersProtobuf[*schedulingv1beta1.Workload](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go index a4fe6a0ee..05d7302ba 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go @@ -40,6 +40,8 @@ type CSINodesGetter interface { type CSINodeInterface interface { Create(ctx context.Context, cSINode *storagev1.CSINode, opts metav1.CreateOptions) (*storagev1.CSINode, error) Update(ctx context.Context, cSINode *storagev1.CSINode, opts metav1.UpdateOptions) (*storagev1.CSINode, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, cSINode *storagev1.CSINode, opts metav1.UpdateOptions) (*storagev1.CSINode, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*storagev1.CSINode, error) @@ -47,6 +49,8 @@ type CSINodeInterface interface { Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *storagev1.CSINode, err error) Apply(ctx context.Context, cSINode *applyconfigurationsstoragev1.CSINodeApplyConfiguration, opts metav1.ApplyOptions) (result *storagev1.CSINode, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, cSINode *applyconfigurationsstoragev1.CSINodeApplyConfiguration, opts metav1.ApplyOptions) (result *storagev1.CSINode, err error) CSINodeExpansion } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go index 5e8eb2e37..6009d0d9a 100644 --- a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go @@ -40,6 +40,8 @@ type CSINodesGetter interface { type CSINodeInterface interface { Create(ctx context.Context, cSINode *storagev1beta1.CSINode, opts v1.CreateOptions) (*storagev1beta1.CSINode, error) Update(ctx context.Context, cSINode *storagev1beta1.CSINode, opts v1.UpdateOptions) (*storagev1beta1.CSINode, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, cSINode *storagev1beta1.CSINode, opts v1.UpdateOptions) (*storagev1beta1.CSINode, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*storagev1beta1.CSINode, error) @@ -47,6 +49,8 @@ type CSINodeInterface interface { Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *storagev1beta1.CSINode, err error) Apply(ctx context.Context, cSINode *applyconfigurationsstoragev1beta1.CSINodeApplyConfiguration, opts v1.ApplyOptions) (result *storagev1beta1.CSINode, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, cSINode *applyconfigurationsstoragev1beta1.CSINodeApplyConfiguration, opts v1.ApplyOptions) (result *storagev1beta1.CSINode, err error) CSINodeExpansion } diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/doc.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/doc.go new file mode 100644 index 000000000..3af5d054f --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1 diff --git a/constraint/vendor/gopkg.in/yaml.v3/NOTICE b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/generated_expansion.go similarity index 77% rename from constraint/vendor/gopkg.in/yaml.v3/NOTICE rename to constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/generated_expansion.go index 866d74a7a..65521b370 100644 --- a/constraint/vendor/gopkg.in/yaml.v3/NOTICE +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/generated_expansion.go @@ -1,4 +1,5 @@ -Copyright 2011-2016 Canonical Ltd. +/* +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. @@ -11,3 +12,10 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +type StorageVersionMigrationExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storagemigration_client.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storagemigration_client.go new file mode 100644 index 000000000..600e7904e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storagemigration_client.go @@ -0,0 +1,101 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + http "net/http" + + storagemigrationv1 "k8s.io/api/storagemigration/v1" + scheme "k8s.io/client-go/kubernetes/scheme" + rest "k8s.io/client-go/rest" +) + +type StoragemigrationV1Interface interface { + RESTClient() rest.Interface + StorageVersionMigrationsGetter +} + +// StoragemigrationV1Client is used to interact with features provided by the storagemigration.k8s.io group. +type StoragemigrationV1Client struct { + restClient rest.Interface +} + +func (c *StoragemigrationV1Client) StorageVersionMigrations() StorageVersionMigrationInterface { + return newStorageVersionMigrations(c) +} + +// NewForConfig creates a new StoragemigrationV1Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*StoragemigrationV1Client, error) { + config := *c + setConfigDefaults(&config) + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new StoragemigrationV1Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StoragemigrationV1Client, error) { + config := *c + setConfigDefaults(&config) + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &StoragemigrationV1Client{client}, nil +} + +// NewForConfigOrDie creates a new StoragemigrationV1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *StoragemigrationV1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new StoragemigrationV1Client for the given RESTClient. +func New(c rest.Interface) *StoragemigrationV1Client { + return &StoragemigrationV1Client{c} +} + +func setConfigDefaults(config *rest.Config) { + gv := storagemigrationv1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *StoragemigrationV1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storageversionmigration.go new file mode 100644 index 000000000..ecc5658d1 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/kubernetes/typed/storagemigration/v1/storageversionmigration.go @@ -0,0 +1,79 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + context "context" + + storagemigrationv1 "k8s.io/api/storagemigration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + applyconfigurationsstoragemigrationv1 "k8s.io/client-go/applyconfigurations/storagemigration/v1" + gentype "k8s.io/client-go/gentype" + scheme "k8s.io/client-go/kubernetes/scheme" +) + +// StorageVersionMigrationsGetter has a method to return a StorageVersionMigrationInterface. +// A group's client should implement this interface. +type StorageVersionMigrationsGetter interface { + StorageVersionMigrations() StorageVersionMigrationInterface +} + +// StorageVersionMigrationInterface has methods to work with StorageVersionMigration resources. +type StorageVersionMigrationInterface interface { + Create(ctx context.Context, storageVersionMigration *storagemigrationv1.StorageVersionMigration, opts metav1.CreateOptions) (*storagemigrationv1.StorageVersionMigration, error) + Update(ctx context.Context, storageVersionMigration *storagemigrationv1.StorageVersionMigration, opts metav1.UpdateOptions) (*storagemigrationv1.StorageVersionMigration, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, storageVersionMigration *storagemigrationv1.StorageVersionMigration, opts metav1.UpdateOptions) (*storagemigrationv1.StorageVersionMigration, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*storagemigrationv1.StorageVersionMigration, error) + List(ctx context.Context, opts metav1.ListOptions) (*storagemigrationv1.StorageVersionMigrationList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *storagemigrationv1.StorageVersionMigration, err error) + Apply(ctx context.Context, storageVersionMigration *applyconfigurationsstoragemigrationv1.StorageVersionMigrationApplyConfiguration, opts metav1.ApplyOptions) (result *storagemigrationv1.StorageVersionMigration, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, storageVersionMigration *applyconfigurationsstoragemigrationv1.StorageVersionMigrationApplyConfiguration, opts metav1.ApplyOptions) (result *storagemigrationv1.StorageVersionMigration, err error) + StorageVersionMigrationExpansion +} + +// storageVersionMigrations implements StorageVersionMigrationInterface +type storageVersionMigrations struct { + *gentype.ClientWithListAndApply[*storagemigrationv1.StorageVersionMigration, *storagemigrationv1.StorageVersionMigrationList, *applyconfigurationsstoragemigrationv1.StorageVersionMigrationApplyConfiguration] +} + +// newStorageVersionMigrations returns a StorageVersionMigrations +func newStorageVersionMigrations(c *StoragemigrationV1Client) *storageVersionMigrations { + return &storageVersionMigrations{ + gentype.NewClientWithListAndApply[*storagemigrationv1.StorageVersionMigration, *storagemigrationv1.StorageVersionMigrationList, *applyconfigurationsstoragemigrationv1.StorageVersionMigrationApplyConfiguration]( + "storageversionmigrations", + c.RESTClient(), + scheme.ParameterCodec, + "", + func() *storagemigrationv1.StorageVersionMigration { + return &storagemigrationv1.StorageVersionMigration{} + }, + func() *storagemigrationv1.StorageVersionMigrationList { + return &storagemigrationv1.StorageVersionMigrationList{} + }, + gentype.PrefersProtobuf[*storagemigrationv1.StorageVersionMigration](), + ), + } +} diff --git a/constraint/vendor/k8s.io/client-go/listers/certificates/v1/clustertrustbundle.go b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/clustertrustbundle.go new file mode 100644 index 000000000..18f6e15fc --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/clustertrustbundle.go @@ -0,0 +1,48 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + certificatesv1 "k8s.io/api/certificates/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ClusterTrustBundleLister helps list ClusterTrustBundles. +// All objects returned here must be treated as read-only. +type ClusterTrustBundleLister interface { + // List lists all ClusterTrustBundles in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*certificatesv1.ClusterTrustBundle, err error) + // Get retrieves the ClusterTrustBundle from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*certificatesv1.ClusterTrustBundle, error) + ClusterTrustBundleListerExpansion +} + +// clusterTrustBundleLister implements the ClusterTrustBundleLister interface. +type clusterTrustBundleLister struct { + listers.ResourceIndexer[*certificatesv1.ClusterTrustBundle] +} + +// NewClusterTrustBundleLister returns a new ClusterTrustBundleLister. +func NewClusterTrustBundleLister(indexer cache.Indexer) ClusterTrustBundleLister { + return &clusterTrustBundleLister{listers.New[*certificatesv1.ClusterTrustBundle](indexer, certificatesv1.Resource("clustertrustbundle"))} +} diff --git a/constraint/vendor/k8s.io/client-go/listers/certificates/v1/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/expansion_generated.go index 616a1f1a0..36a04381e 100644 --- a/constraint/vendor/k8s.io/client-go/listers/certificates/v1/expansion_generated.go +++ b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/expansion_generated.go @@ -21,3 +21,15 @@ package v1 // CertificateSigningRequestListerExpansion allows custom methods to be added to // CertificateSigningRequestLister. type CertificateSigningRequestListerExpansion interface{} + +// ClusterTrustBundleListerExpansion allows custom methods to be added to +// ClusterTrustBundleLister. +type ClusterTrustBundleListerExpansion interface{} + +// PodCertificateRequestListerExpansion allows custom methods to be added to +// PodCertificateRequestLister. +type PodCertificateRequestListerExpansion interface{} + +// PodCertificateRequestNamespaceListerExpansion allows custom methods to be added to +// PodCertificateRequestNamespaceLister. +type PodCertificateRequestNamespaceListerExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/listers/certificates/v1/podcertificaterequest.go b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/podcertificaterequest.go new file mode 100644 index 000000000..71a7a545d --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/certificates/v1/podcertificaterequest.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + certificatesv1 "k8s.io/api/certificates/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// PodCertificateRequestLister helps list PodCertificateRequests. +// All objects returned here must be treated as read-only. +type PodCertificateRequestLister interface { + // List lists all PodCertificateRequests in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*certificatesv1.PodCertificateRequest, err error) + // PodCertificateRequests returns an object that can list and get PodCertificateRequests. + PodCertificateRequests(namespace string) PodCertificateRequestNamespaceLister + PodCertificateRequestListerExpansion +} + +// podCertificateRequestLister implements the PodCertificateRequestLister interface. +type podCertificateRequestLister struct { + listers.ResourceIndexer[*certificatesv1.PodCertificateRequest] +} + +// NewPodCertificateRequestLister returns a new PodCertificateRequestLister. +func NewPodCertificateRequestLister(indexer cache.Indexer) PodCertificateRequestLister { + return &podCertificateRequestLister{listers.New[*certificatesv1.PodCertificateRequest](indexer, certificatesv1.Resource("podcertificaterequest"))} +} + +// PodCertificateRequests returns an object that can list and get PodCertificateRequests. +func (s *podCertificateRequestLister) PodCertificateRequests(namespace string) PodCertificateRequestNamespaceLister { + return podCertificateRequestNamespaceLister{listers.NewNamespaced[*certificatesv1.PodCertificateRequest](s.ResourceIndexer, namespace)} +} + +// PodCertificateRequestNamespaceLister helps list and get PodCertificateRequests. +// All objects returned here must be treated as read-only. +type PodCertificateRequestNamespaceLister interface { + // List lists all PodCertificateRequests in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*certificatesv1.PodCertificateRequest, err error) + // Get retrieves the PodCertificateRequest from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*certificatesv1.PodCertificateRequest, error) + PodCertificateRequestNamespaceListerExpansion +} + +// podCertificateRequestNamespaceLister implements the PodCertificateRequestNamespaceLister +// interface. +type podCertificateRequestNamespaceLister struct { + listers.ResourceIndexer[*certificatesv1.PodCertificateRequest] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/eviction.go b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/eviction.go new file mode 100644 index 000000000..33f3c663c --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/eviction.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// EvictionLister helps list Evictions. +// All objects returned here must be treated as read-only. +type EvictionLister interface { + // List lists all Evictions in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*lifecyclev1alpha1.Eviction, err error) + // Evictions returns an object that can list and get Evictions. + Evictions(namespace string) EvictionNamespaceLister + EvictionListerExpansion +} + +// evictionLister implements the EvictionLister interface. +type evictionLister struct { + listers.ResourceIndexer[*lifecyclev1alpha1.Eviction] +} + +// NewEvictionLister returns a new EvictionLister. +func NewEvictionLister(indexer cache.Indexer) EvictionLister { + return &evictionLister{listers.New[*lifecyclev1alpha1.Eviction](indexer, lifecyclev1alpha1.Resource("eviction"))} +} + +// Evictions returns an object that can list and get Evictions. +func (s *evictionLister) Evictions(namespace string) EvictionNamespaceLister { + return evictionNamespaceLister{listers.NewNamespaced[*lifecyclev1alpha1.Eviction](s.ResourceIndexer, namespace)} +} + +// EvictionNamespaceLister helps list and get Evictions. +// All objects returned here must be treated as read-only. +type EvictionNamespaceLister interface { + // List lists all Evictions in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*lifecyclev1alpha1.Eviction, err error) + // Get retrieves the Eviction from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*lifecyclev1alpha1.Eviction, error) + EvictionNamespaceListerExpansion +} + +// evictionNamespaceLister implements the EvictionNamespaceLister +// interface. +type evictionNamespaceLister struct { + listers.ResourceIndexer[*lifecyclev1alpha1.Eviction] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/evictionrequest.go b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/evictionrequest.go new file mode 100644 index 000000000..97caab9cd --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/evictionrequest.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + lifecyclev1alpha1 "k8s.io/api/lifecycle/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// EvictionRequestLister helps list EvictionRequests. +// All objects returned here must be treated as read-only. +type EvictionRequestLister interface { + // List lists all EvictionRequests in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*lifecyclev1alpha1.EvictionRequest, err error) + // EvictionRequests returns an object that can list and get EvictionRequests. + EvictionRequests(namespace string) EvictionRequestNamespaceLister + EvictionRequestListerExpansion +} + +// evictionRequestLister implements the EvictionRequestLister interface. +type evictionRequestLister struct { + listers.ResourceIndexer[*lifecyclev1alpha1.EvictionRequest] +} + +// NewEvictionRequestLister returns a new EvictionRequestLister. +func NewEvictionRequestLister(indexer cache.Indexer) EvictionRequestLister { + return &evictionRequestLister{listers.New[*lifecyclev1alpha1.EvictionRequest](indexer, lifecyclev1alpha1.Resource("evictionrequest"))} +} + +// EvictionRequests returns an object that can list and get EvictionRequests. +func (s *evictionRequestLister) EvictionRequests(namespace string) EvictionRequestNamespaceLister { + return evictionRequestNamespaceLister{listers.NewNamespaced[*lifecyclev1alpha1.EvictionRequest](s.ResourceIndexer, namespace)} +} + +// EvictionRequestNamespaceLister helps list and get EvictionRequests. +// All objects returned here must be treated as read-only. +type EvictionRequestNamespaceLister interface { + // List lists all EvictionRequests in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*lifecyclev1alpha1.EvictionRequest, err error) + // Get retrieves the EvictionRequest from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*lifecyclev1alpha1.EvictionRequest, error) + EvictionRequestNamespaceListerExpansion +} + +// evictionRequestNamespaceLister implements the EvictionRequestNamespaceLister +// interface. +type evictionRequestNamespaceLister struct { + listers.ResourceIndexer[*lifecyclev1alpha1.EvictionRequest] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/expansion_generated.go new file mode 100644 index 000000000..dba8bb055 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/lifecycle/v1alpha1/expansion_generated.go @@ -0,0 +1,35 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha1 + +// EvictionListerExpansion allows custom methods to be added to +// EvictionLister. +type EvictionListerExpansion interface{} + +// EvictionNamespaceListerExpansion allows custom methods to be added to +// EvictionNamespaceLister. +type EvictionNamespaceListerExpansion interface{} + +// EvictionRequestListerExpansion allows custom methods to be added to +// EvictionRequestLister. +type EvictionRequestListerExpansion interface{} + +// EvictionRequestNamespaceListerExpansion allows custom methods to be added to +// EvictionRequestNamespaceLister. +type EvictionRequestNamespaceListerExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/listers/resource/v1/devicetaintrule.go b/constraint/vendor/k8s.io/client-go/listers/resource/v1/devicetaintrule.go new file mode 100644 index 000000000..150ca4f64 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/resource/v1/devicetaintrule.go @@ -0,0 +1,48 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + resourcev1 "k8s.io/api/resource/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// DeviceTaintRuleLister helps list DeviceTaintRules. +// All objects returned here must be treated as read-only. +type DeviceTaintRuleLister interface { + // List lists all DeviceTaintRules in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*resourcev1.DeviceTaintRule, err error) + // Get retrieves the DeviceTaintRule from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*resourcev1.DeviceTaintRule, error) + DeviceTaintRuleListerExpansion +} + +// deviceTaintRuleLister implements the DeviceTaintRuleLister interface. +type deviceTaintRuleLister struct { + listers.ResourceIndexer[*resourcev1.DeviceTaintRule] +} + +// NewDeviceTaintRuleLister returns a new DeviceTaintRuleLister. +func NewDeviceTaintRuleLister(indexer cache.Indexer) DeviceTaintRuleLister { + return &deviceTaintRuleLister{listers.New[*resourcev1.DeviceTaintRule](indexer, resourcev1.Resource("devicetaintrule"))} +} diff --git a/constraint/vendor/k8s.io/client-go/listers/resource/v1/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/resource/v1/expansion_generated.go index 6e6e22dcd..53e789fee 100644 --- a/constraint/vendor/k8s.io/client-go/listers/resource/v1/expansion_generated.go +++ b/constraint/vendor/k8s.io/client-go/listers/resource/v1/expansion_generated.go @@ -22,6 +22,10 @@ package v1 // DeviceClassLister. type DeviceClassListerExpansion interface{} +// DeviceTaintRuleListerExpansion allows custom methods to be added to +// DeviceTaintRuleLister. +type DeviceTaintRuleListerExpansion interface{} + // ResourceClaimListerExpansion allows custom methods to be added to // ResourceClaimLister. type ResourceClaimListerExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/compositepodgroup.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/compositepodgroup.go new file mode 100644 index 000000000..b5cfe9752 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/compositepodgroup.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha3 + +import ( + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// CompositePodGroupLister helps list CompositePodGroups. +// All objects returned here must be treated as read-only. +type CompositePodGroupLister interface { + // List lists all CompositePodGroups in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1alpha3.CompositePodGroup, err error) + // CompositePodGroups returns an object that can list and get CompositePodGroups. + CompositePodGroups(namespace string) CompositePodGroupNamespaceLister + CompositePodGroupListerExpansion +} + +// compositePodGroupLister implements the CompositePodGroupLister interface. +type compositePodGroupLister struct { + listers.ResourceIndexer[*schedulingv1alpha3.CompositePodGroup] +} + +// NewCompositePodGroupLister returns a new CompositePodGroupLister. +func NewCompositePodGroupLister(indexer cache.Indexer) CompositePodGroupLister { + return &compositePodGroupLister{listers.New[*schedulingv1alpha3.CompositePodGroup](indexer, schedulingv1alpha3.Resource("compositepodgroup"))} +} + +// CompositePodGroups returns an object that can list and get CompositePodGroups. +func (s *compositePodGroupLister) CompositePodGroups(namespace string) CompositePodGroupNamespaceLister { + return compositePodGroupNamespaceLister{listers.NewNamespaced[*schedulingv1alpha3.CompositePodGroup](s.ResourceIndexer, namespace)} +} + +// CompositePodGroupNamespaceLister helps list and get CompositePodGroups. +// All objects returned here must be treated as read-only. +type CompositePodGroupNamespaceLister interface { + // List lists all CompositePodGroups in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1alpha3.CompositePodGroup, err error) + // Get retrieves the CompositePodGroup from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*schedulingv1alpha3.CompositePodGroup, error) + CompositePodGroupNamespaceListerExpansion +} + +// compositePodGroupNamespaceLister implements the CompositePodGroupNamespaceLister +// interface. +type compositePodGroupNamespaceLister struct { + listers.ResourceIndexer[*schedulingv1alpha3.CompositePodGroup] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/expansion_generated.go similarity index 77% rename from constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/expansion_generated.go rename to constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/expansion_generated.go index 3a63d7891..cd99f2d08 100644 --- a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/expansion_generated.go +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/expansion_generated.go @@ -16,7 +16,15 @@ limitations under the License. // Code generated by lister-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 + +// CompositePodGroupListerExpansion allows custom methods to be added to +// CompositePodGroupLister. +type CompositePodGroupListerExpansion interface{} + +// CompositePodGroupNamespaceListerExpansion allows custom methods to be added to +// CompositePodGroupNamespaceLister. +type CompositePodGroupNamespaceListerExpansion interface{} // PodGroupListerExpansion allows custom methods to be added to // PodGroupLister. diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/podgroup.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/podgroup.go similarity index 80% rename from constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/podgroup.go rename to constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/podgroup.go index 292e5d62b..0215a7e39 100644 --- a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/podgroup.go +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/podgroup.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by lister-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" labels "k8s.io/apimachinery/pkg/labels" listers "k8s.io/client-go/listers" cache "k8s.io/client-go/tools/cache" @@ -30,7 +30,7 @@ import ( type PodGroupLister interface { // List lists all PodGroups in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*schedulingv1alpha2.PodGroup, err error) + List(selector labels.Selector) (ret []*schedulingv1alpha3.PodGroup, err error) // PodGroups returns an object that can list and get PodGroups. PodGroups(namespace string) PodGroupNamespaceLister PodGroupListerExpansion @@ -38,17 +38,17 @@ type PodGroupLister interface { // podGroupLister implements the PodGroupLister interface. type podGroupLister struct { - listers.ResourceIndexer[*schedulingv1alpha2.PodGroup] + listers.ResourceIndexer[*schedulingv1alpha3.PodGroup] } // NewPodGroupLister returns a new PodGroupLister. func NewPodGroupLister(indexer cache.Indexer) PodGroupLister { - return &podGroupLister{listers.New[*schedulingv1alpha2.PodGroup](indexer, schedulingv1alpha2.Resource("podgroup"))} + return &podGroupLister{listers.New[*schedulingv1alpha3.PodGroup](indexer, schedulingv1alpha3.Resource("podgroup"))} } // PodGroups returns an object that can list and get PodGroups. func (s *podGroupLister) PodGroups(namespace string) PodGroupNamespaceLister { - return podGroupNamespaceLister{listers.NewNamespaced[*schedulingv1alpha2.PodGroup](s.ResourceIndexer, namespace)} + return podGroupNamespaceLister{listers.NewNamespaced[*schedulingv1alpha3.PodGroup](s.ResourceIndexer, namespace)} } // PodGroupNamespaceLister helps list and get PodGroups. @@ -56,15 +56,15 @@ func (s *podGroupLister) PodGroups(namespace string) PodGroupNamespaceLister { type PodGroupNamespaceLister interface { // List lists all PodGroups in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*schedulingv1alpha2.PodGroup, err error) + List(selector labels.Selector) (ret []*schedulingv1alpha3.PodGroup, err error) // Get retrieves the PodGroup from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*schedulingv1alpha2.PodGroup, error) + Get(name string) (*schedulingv1alpha3.PodGroup, error) PodGroupNamespaceListerExpansion } // podGroupNamespaceLister implements the PodGroupNamespaceLister // interface. type podGroupNamespaceLister struct { - listers.ResourceIndexer[*schedulingv1alpha2.PodGroup] + listers.ResourceIndexer[*schedulingv1alpha3.PodGroup] } diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/workload.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/workload.go similarity index 80% rename from constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/workload.go rename to constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/workload.go index 9526da3b5..4919ca4ad 100644 --- a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha2/workload.go +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1alpha3/workload.go @@ -16,10 +16,10 @@ limitations under the License. // Code generated by lister-gen. DO NOT EDIT. -package v1alpha2 +package v1alpha3 import ( - schedulingv1alpha2 "k8s.io/api/scheduling/v1alpha2" + schedulingv1alpha3 "k8s.io/api/scheduling/v1alpha3" labels "k8s.io/apimachinery/pkg/labels" listers "k8s.io/client-go/listers" cache "k8s.io/client-go/tools/cache" @@ -30,7 +30,7 @@ import ( type WorkloadLister interface { // List lists all Workloads in the indexer. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*schedulingv1alpha2.Workload, err error) + List(selector labels.Selector) (ret []*schedulingv1alpha3.Workload, err error) // Workloads returns an object that can list and get Workloads. Workloads(namespace string) WorkloadNamespaceLister WorkloadListerExpansion @@ -38,17 +38,17 @@ type WorkloadLister interface { // workloadLister implements the WorkloadLister interface. type workloadLister struct { - listers.ResourceIndexer[*schedulingv1alpha2.Workload] + listers.ResourceIndexer[*schedulingv1alpha3.Workload] } // NewWorkloadLister returns a new WorkloadLister. func NewWorkloadLister(indexer cache.Indexer) WorkloadLister { - return &workloadLister{listers.New[*schedulingv1alpha2.Workload](indexer, schedulingv1alpha2.Resource("workload"))} + return &workloadLister{listers.New[*schedulingv1alpha3.Workload](indexer, schedulingv1alpha3.Resource("workload"))} } // Workloads returns an object that can list and get Workloads. func (s *workloadLister) Workloads(namespace string) WorkloadNamespaceLister { - return workloadNamespaceLister{listers.NewNamespaced[*schedulingv1alpha2.Workload](s.ResourceIndexer, namespace)} + return workloadNamespaceLister{listers.NewNamespaced[*schedulingv1alpha3.Workload](s.ResourceIndexer, namespace)} } // WorkloadNamespaceLister helps list and get Workloads. @@ -56,15 +56,15 @@ func (s *workloadLister) Workloads(namespace string) WorkloadNamespaceLister { type WorkloadNamespaceLister interface { // List lists all Workloads in the indexer for a given namespace. // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*schedulingv1alpha2.Workload, err error) + List(selector labels.Selector) (ret []*schedulingv1alpha3.Workload, err error) // Get retrieves the Workload from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. - Get(name string) (*schedulingv1alpha2.Workload, error) + Get(name string) (*schedulingv1alpha3.Workload, error) WorkloadNamespaceListerExpansion } // workloadNamespaceLister implements the WorkloadNamespaceLister // interface. type workloadNamespaceLister struct { - listers.ResourceIndexer[*schedulingv1alpha2.Workload] + listers.ResourceIndexer[*schedulingv1alpha3.Workload] } diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/expansion_generated.go index b806e8cf8..449ba455b 100644 --- a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/expansion_generated.go +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/expansion_generated.go @@ -18,6 +18,22 @@ limitations under the License. package v1beta1 +// PodGroupListerExpansion allows custom methods to be added to +// PodGroupLister. +type PodGroupListerExpansion interface{} + +// PodGroupNamespaceListerExpansion allows custom methods to be added to +// PodGroupNamespaceLister. +type PodGroupNamespaceListerExpansion interface{} + // PriorityClassListerExpansion allows custom methods to be added to // PriorityClassLister. type PriorityClassListerExpansion interface{} + +// WorkloadListerExpansion allows custom methods to be added to +// WorkloadLister. +type WorkloadListerExpansion interface{} + +// WorkloadNamespaceListerExpansion allows custom methods to be added to +// WorkloadNamespaceLister. +type WorkloadNamespaceListerExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/podgroup.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/podgroup.go new file mode 100644 index 000000000..32ef1ac6e --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/podgroup.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// PodGroupLister helps list PodGroups. +// All objects returned here must be treated as read-only. +type PodGroupLister interface { + // List lists all PodGroups in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1beta1.PodGroup, err error) + // PodGroups returns an object that can list and get PodGroups. + PodGroups(namespace string) PodGroupNamespaceLister + PodGroupListerExpansion +} + +// podGroupLister implements the PodGroupLister interface. +type podGroupLister struct { + listers.ResourceIndexer[*schedulingv1beta1.PodGroup] +} + +// NewPodGroupLister returns a new PodGroupLister. +func NewPodGroupLister(indexer cache.Indexer) PodGroupLister { + return &podGroupLister{listers.New[*schedulingv1beta1.PodGroup](indexer, schedulingv1beta1.Resource("podgroup"))} +} + +// PodGroups returns an object that can list and get PodGroups. +func (s *podGroupLister) PodGroups(namespace string) PodGroupNamespaceLister { + return podGroupNamespaceLister{listers.NewNamespaced[*schedulingv1beta1.PodGroup](s.ResourceIndexer, namespace)} +} + +// PodGroupNamespaceLister helps list and get PodGroups. +// All objects returned here must be treated as read-only. +type PodGroupNamespaceLister interface { + // List lists all PodGroups in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1beta1.PodGroup, err error) + // Get retrieves the PodGroup from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*schedulingv1beta1.PodGroup, error) + PodGroupNamespaceListerExpansion +} + +// podGroupNamespaceLister implements the PodGroupNamespaceLister +// interface. +type podGroupNamespaceLister struct { + listers.ResourceIndexer[*schedulingv1beta1.PodGroup] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/workload.go b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/workload.go new file mode 100644 index 000000000..9f20d5a06 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/scheduling/v1beta1/workload.go @@ -0,0 +1,70 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// WorkloadLister helps list Workloads. +// All objects returned here must be treated as read-only. +type WorkloadLister interface { + // List lists all Workloads in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1beta1.Workload, err error) + // Workloads returns an object that can list and get Workloads. + Workloads(namespace string) WorkloadNamespaceLister + WorkloadListerExpansion +} + +// workloadLister implements the WorkloadLister interface. +type workloadLister struct { + listers.ResourceIndexer[*schedulingv1beta1.Workload] +} + +// NewWorkloadLister returns a new WorkloadLister. +func NewWorkloadLister(indexer cache.Indexer) WorkloadLister { + return &workloadLister{listers.New[*schedulingv1beta1.Workload](indexer, schedulingv1beta1.Resource("workload"))} +} + +// Workloads returns an object that can list and get Workloads. +func (s *workloadLister) Workloads(namespace string) WorkloadNamespaceLister { + return workloadNamespaceLister{listers.NewNamespaced[*schedulingv1beta1.Workload](s.ResourceIndexer, namespace)} +} + +// WorkloadNamespaceLister helps list and get Workloads. +// All objects returned here must be treated as read-only. +type WorkloadNamespaceLister interface { + // List lists all Workloads in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*schedulingv1beta1.Workload, err error) + // Get retrieves the Workload from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*schedulingv1beta1.Workload, error) + WorkloadNamespaceListerExpansion +} + +// workloadNamespaceLister implements the WorkloadNamespaceLister +// interface. +type workloadNamespaceLister struct { + listers.ResourceIndexer[*schedulingv1beta1.Workload] +} diff --git a/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/expansion_generated.go b/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/expansion_generated.go new file mode 100644 index 000000000..324da1ffa --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/expansion_generated.go @@ -0,0 +1,23 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1 + +// StorageVersionMigrationListerExpansion allows custom methods to be added to +// StorageVersionMigrationLister. +type StorageVersionMigrationListerExpansion interface{} diff --git a/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/storageversionmigration.go b/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/storageversionmigration.go new file mode 100644 index 000000000..37f7afb07 --- /dev/null +++ b/constraint/vendor/k8s.io/client-go/listers/storagemigration/v1/storageversionmigration.go @@ -0,0 +1,48 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + storagemigrationv1 "k8s.io/api/storagemigration/v1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// StorageVersionMigrationLister helps list StorageVersionMigrations. +// All objects returned here must be treated as read-only. +type StorageVersionMigrationLister interface { + // List lists all StorageVersionMigrations in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*storagemigrationv1.StorageVersionMigration, err error) + // Get retrieves the StorageVersionMigration from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*storagemigrationv1.StorageVersionMigration, error) + StorageVersionMigrationListerExpansion +} + +// storageVersionMigrationLister implements the StorageVersionMigrationLister interface. +type storageVersionMigrationLister struct { + listers.ResourceIndexer[*storagemigrationv1.StorageVersionMigration] +} + +// NewStorageVersionMigrationLister returns a new StorageVersionMigrationLister. +func NewStorageVersionMigrationLister(indexer cache.Indexer) StorageVersionMigrationLister { + return &storageVersionMigrationLister{listers.New[*storagemigrationv1.StorageVersionMigration](indexer, storagemigrationv1.Resource("storageversionmigration"))} +} diff --git a/constraint/vendor/k8s.io/client-go/openapi/OWNERS b/constraint/vendor/k8s.io/client-go/openapi/OWNERS index e61009424..8bea129e9 100644 --- a/constraint/vendor/k8s.io/client-go/openapi/OWNERS +++ b/constraint/vendor/k8s.io/client-go/openapi/OWNERS @@ -1,4 +1,7 @@ # See the OWNERS docs at https://go.k8s.io/owners approvers: + - jpbetz + - api-approvers +emeritus_approvers: - apelisse diff --git a/constraint/vendor/k8s.io/client-go/openapi/client.go b/constraint/vendor/k8s.io/client-go/openapi/client.go index d32895a2f..6e9a55e84 100644 --- a/constraint/vendor/k8s.io/client-go/openapi/client.go +++ b/constraint/vendor/k8s.io/client-go/openapi/client.go @@ -25,25 +25,81 @@ import ( "k8s.io/kube-openapi/pkg/handler3" ) +// ClientWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ClientWithContext instead. type Client interface { Paths() (map[string]GroupVersion, error) } +type ClientWithContext interface { + PathsWithContext(ctx context.Context) (map[string]GroupVersionWithContext, error) +} + +func ToClientWithContext(c Client) ClientWithContext { + if c == nil { + return nil + } + if c, ok := c.(ClientWithContext); ok { + return c + } + return &clientWrapper{ + delegate: c, + } +} + +type clientWrapper struct { + delegate Client +} + +func (c *clientWrapper) PathsWithContext(ctx context.Context) (map[string]GroupVersionWithContext, error) { + resultWithoutContext, err := c.delegate.Paths() + result := make(map[string]GroupVersionWithContext, len(resultWithoutContext)) + for key, entry := range resultWithoutContext { + result[key] = ToGroupVersionWithContext(entry) + } + return result, err +} + type client struct { // URL includes the `hash` query param to take advantage of cache busting restClient rest.Interface } +// NewClientWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use NewClientWithContext instead. func NewClient(restClient rest.Interface) Client { + return newClient(restClient) +} + +func NewClientWithContext(restClient rest.Interface) ClientWithContext { + return newClient(restClient) +} + +func newClient(restClient rest.Interface) *client { return &client{ restClient: restClient, } } +// PathsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use PathsWithContext instead. func (c *client) Paths() (map[string]GroupVersion, error) { + resultWithContext, err := c.PathsWithContext(context.Background()) + result := make(map[string]GroupVersion, len(resultWithContext)) + for key, entry := range resultWithContext { + // We know that this is a *groupversion which implements GroupVersion. + result[key] = entry.(GroupVersion) + } + return result, err +} + +func (c *client) PathsWithContext(ctx context.Context) (map[string]GroupVersionWithContext, error) { data, err := c.restClient.Get(). AbsPath("/openapi/v3"). - Do(context.TODO()). + Do(ctx). Raw() if err != nil { @@ -59,7 +115,7 @@ func (c *client) Paths() (map[string]GroupVersion, error) { // Calculate the client-side prefix for a "root" request rootPrefix := strings.TrimSuffix(c.restClient.Get().AbsPath("/").URL().Path, "/") // Create GroupVersions for each element of the result - result := map[string]GroupVersion{} + result := make(map[string]GroupVersionWithContext, len(discoMap.Paths)) for k, v := range discoMap.Paths { // Trim off the prefix that will always be added in client-side v.ServerRelativeURL = strings.TrimPrefix(v.ServerRelativeURL, rootPrefix) diff --git a/constraint/vendor/k8s.io/client-go/openapi/groupversion.go b/constraint/vendor/k8s.io/client-go/openapi/groupversion.go index 40d91b9a5..0e0b59399 100644 --- a/constraint/vendor/k8s.io/client-go/openapi/groupversion.go +++ b/constraint/vendor/k8s.io/client-go/openapi/groupversion.go @@ -25,6 +25,9 @@ import ( const ContentTypeOpenAPIV3PB = "application/com.github.proto-openapi.spec.v3@v1.0+protobuf" +// GroupVersionWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use GroupVersionWithContext instead. type GroupVersion interface { Schema(contentType string) ([]byte, error) @@ -35,22 +38,61 @@ type GroupVersion interface { ServerRelativeURL() string } +type GroupVersionWithContext interface { + SchemaWithContext(ctx context.Context, contentType string) ([]byte, error) + + // ServerRelativeURL. Returns the path and parameters used to fetch the schema. + // You should use the Schema method to fetch it, but this value can be used + // to key the current version of the schema in a cache since it contains a + // hash string which changes upon schema update. + ServerRelativeURL() string +} + +func ToGroupVersionWithContext(gv GroupVersion) GroupVersionWithContext { + if gv == nil { + return nil + } + if gv, ok := gv.(GroupVersionWithContext); ok { + return gv + } + return &groupVersionWrapper{ + GroupVersion: gv, + } +} + +type groupVersionWrapper struct { + GroupVersion +} + +func (gv *groupVersionWrapper) SchemaWithContext(ctx context.Context, contentType string) ([]byte, error) { + return gv.Schema(contentType) +} + type groupversion struct { client *client item handler3.OpenAPIV3DiscoveryGroupVersion useClientPrefix bool } +var ( + _ GroupVersion = &groupversion{} + _ GroupVersionWithContext = &groupversion{} +) + func newGroupVersion(client *client, item handler3.OpenAPIV3DiscoveryGroupVersion, useClientPrefix bool) *groupversion { return &groupversion{client: client, item: item, useClientPrefix: useClientPrefix} } func (g *groupversion) Schema(contentType string) ([]byte, error) { + return g.SchemaWithContext(context.Background(), contentType) +} + +func (g *groupversion) SchemaWithContext(ctx context.Context, contentType string) ([]byte, error) { if !g.useClientPrefix { return g.client.restClient.Get(). RequestURI(g.item.ServerRelativeURL). SetHeader("Accept", contentType). - Do(context.TODO()). + Do(ctx). Raw() } @@ -72,7 +114,7 @@ func (g *groupversion) Schema(contentType string) ([]byte, error) { } } - return path.Do(context.TODO()).Raw() + return path.Do(ctx).Raw() } // URL used for fetching the schema. The URL includes a hash and can be used diff --git a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/types.go b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/types.go index b9082e814..6e0c84aea 100644 --- a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/types.go +++ b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/types.go @@ -26,7 +26,7 @@ import ( // ExecCredential is used by exec-based plugins to communicate credentials to // HTTP transports. type ExecCredential struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Spec holds information passed to the plugin by the transport. Spec ExecCredentialSpec `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/zz_generated.conversion.go b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/zz_generated.conversion.go index 9c3f63fca..bec865c48 100644 --- a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1/zz_generated.conversion.go @@ -24,7 +24,6 @@ package v1 import ( unsafe "unsafe" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication" @@ -181,10 +180,7 @@ func Convert_clientauthentication_ExecCredentialSpec_To_v1_ExecCredentialSpec(in } func autoConvert_v1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error { - out.ExpirationTimestamp = (*metav1.Time)(unsafe.Pointer(in.ExpirationTimestamp)) - out.Token = in.Token - out.ClientCertificateData = in.ClientCertificateData - out.ClientKeyData = in.ClientKeyData + *out = *(*clientauthentication.ExecCredentialStatus)(unsafe.Pointer(in)) return nil } @@ -194,10 +190,7 @@ func Convert_v1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatu } func autoConvert_clientauthentication_ExecCredentialStatus_To_v1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error { - out.ExpirationTimestamp = (*metav1.Time)(unsafe.Pointer(in.ExpirationTimestamp)) - out.Token = in.Token - out.ClientCertificateData = in.ClientCertificateData - out.ClientKeyData = in.ClientKeyData + *out = *(*ExecCredentialStatus)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go index 918eb11e1..d2f2b5079 100644 --- a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go +++ b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/types.go @@ -26,7 +26,7 @@ import ( // ExecCredential is used by exec-based plugins to communicate credentials to // HTTP transports. type ExecCredential struct { - metav1.TypeMeta `json:",inline"` + metav1.TypeMeta `json:""` // Spec holds information passed to the plugin by the transport. Spec ExecCredentialSpec `json:"spec,omitempty"` diff --git a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go index 5372da151..4e7be3515 100644 --- a/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/zz_generated.conversion.go @@ -24,7 +24,6 @@ package v1beta1 import ( unsafe "unsafe" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" clientauthentication "k8s.io/client-go/pkg/apis/clientauthentication" @@ -181,10 +180,7 @@ func Convert_clientauthentication_ExecCredentialSpec_To_v1beta1_ExecCredentialSp } func autoConvert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredentialStatus(in *ExecCredentialStatus, out *clientauthentication.ExecCredentialStatus, s conversion.Scope) error { - out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp)) - out.Token = in.Token - out.ClientCertificateData = in.ClientCertificateData - out.ClientKeyData = in.ClientKeyData + *out = *(*clientauthentication.ExecCredentialStatus)(unsafe.Pointer(in)) return nil } @@ -194,10 +190,7 @@ func Convert_v1beta1_ExecCredentialStatus_To_clientauthentication_ExecCredential } func autoConvert_clientauthentication_ExecCredentialStatus_To_v1beta1_ExecCredentialStatus(in *clientauthentication.ExecCredentialStatus, out *ExecCredentialStatus, s conversion.Scope) error { - out.ExpirationTimestamp = (*v1.Time)(unsafe.Pointer(in.ExpirationTimestamp)) - out.Token = in.Token - out.ClientCertificateData = in.ClientCertificateData - out.ClientKeyData = in.ClientKeyData + *out = *(*ExecCredentialStatus)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go b/constraint/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go index b2393f4dd..60f9da50d 100644 --- a/constraint/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go +++ b/constraint/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go @@ -159,6 +159,7 @@ func (s *sometimes) Do(f func()) { // GetAuthenticator returns an exec-based plugin for providing client credentials. func GetAuthenticator(config *api.ExecConfig, cluster *clientauthentication.Cluster) (*Authenticator, error) { + metrics.EnsureRegistered() return newAuthenticator(globalCache, term.IsTerminal, config, cluster) } diff --git a/constraint/vendor/k8s.io/client-go/rest/OWNERS b/constraint/vendor/k8s.io/client-go/rest/OWNERS index 7b23294c4..c057852b7 100644 --- a/constraint/vendor/k8s.io/client-go/rest/OWNERS +++ b/constraint/vendor/k8s.io/client-go/rest/OWNERS @@ -3,7 +3,6 @@ reviewers: - thockin - smarterclayton - - caesarxuchao - wojtek-t - deads2k - liggitt diff --git a/constraint/vendor/k8s.io/client-go/rest/client.go b/constraint/vendor/k8s.io/client-go/rest/client.go index a085c334f..d92c1b647 100644 --- a/constraint/vendor/k8s.io/client-go/rest/client.go +++ b/constraint/vendor/k8s.io/client-go/rest/client.go @@ -32,6 +32,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" clientfeatures "k8s.io/client-go/features" + "k8s.io/client-go/tools/metrics" "k8s.io/client-go/util/flowcontrol" ) @@ -110,6 +111,8 @@ type RESTClient struct { // NewRESTClient creates a new RESTClient. This client performs generic REST functions // such as Get, Put, Post, and Delete on specified paths. func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) { + metrics.EnsureRegistered() + base := *baseURL if !strings.HasSuffix(base.Path, "/") { base.Path += "/" diff --git a/constraint/vendor/k8s.io/client-go/rest/config.go b/constraint/vendor/k8s.io/client-go/rest/config.go index 82d4f7136..3d4fb720c 100644 --- a/constraint/vendor/k8s.io/client-go/rest/config.go +++ b/constraint/vendor/k8s.io/client-go/rest/config.go @@ -37,6 +37,7 @@ import ( "k8s.io/client-go/features" "k8s.io/client-go/pkg/version" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "k8s.io/client-go/tools/metrics" "k8s.io/client-go/transport" certutil "k8s.io/client-go/util/cert" "k8s.io/client-go/util/flowcontrol" @@ -355,6 +356,8 @@ func RESTClientFor(config *Config) (*RESTClient, error) { // Note that the http client takes precedence over the transport values configured. // The http client defaults to the `http.DefaultClient` if nil. func RESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error) { + metrics.EnsureRegistered() + if config.GroupVersion == nil { return nil, fmt.Errorf("GroupVersion is required when initializing a RESTClient") } diff --git a/constraint/vendor/k8s.io/client-go/rest/request.go b/constraint/vendor/k8s.io/client-go/rest/request.go index fb5721692..fe3c06672 100644 --- a/constraint/vendor/k8s.io/client-go/rest/request.go +++ b/constraint/vendor/k8s.io/client-go/rest/request.go @@ -20,6 +20,7 @@ import ( "bytes" "context" "encoding/hex" + stderrors "errors" "fmt" "io" "mime" @@ -671,7 +672,8 @@ func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) err now := time.Now() err := r.rateLimiter.Wait(ctx) - if err != nil { + // Don't wrap context errors as caller initiated ctx cancellations is not a rate limiter error. + if err != nil && !stderrors.Is(err, context.Canceled) && !stderrors.Is(err, context.DeadlineExceeded) { err = fmt.Errorf("client rate limiter Wait returned an error: %w", err) } latency := time.Since(now) diff --git a/constraint/vendor/k8s.io/client-go/rest/transport.go b/constraint/vendor/k8s.io/client-go/rest/transport.go index 53f986cbf..c95824040 100644 --- a/constraint/vendor/k8s.io/client-go/rest/transport.go +++ b/constraint/vendor/k8s.io/client-go/rest/transport.go @@ -23,6 +23,7 @@ import ( "k8s.io/client-go/pkg/apis/clientauthentication" "k8s.io/client-go/plugin/pkg/client/auth/exec" + "k8s.io/client-go/tools/metrics" "k8s.io/client-go/transport" ) @@ -82,6 +83,7 @@ func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTrip // TransportConfig converts a client config to an appropriate transport config. func (c *Config) TransportConfig() (*transport.Config, error) { + metrics.EnsureRegistered() conf := &transport.Config{ UserAgent: c.UserAgent, Transport: c.Transport, diff --git a/constraint/vendor/k8s.io/client-go/restmapper/category_expansion.go b/constraint/vendor/k8s.io/client-go/restmapper/category_expansion.go index 484e4c839..265cc7c6a 100644 --- a/constraint/vendor/k8s.io/client-go/restmapper/category_expansion.go +++ b/constraint/vendor/k8s.io/client-go/restmapper/category_expansion.go @@ -17,38 +17,97 @@ limitations under the License. package restmapper import ( + "context" + "iter" + "slices" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/discovery" ) // CategoryExpander maps category strings to GroupResources. // Categories are classification or 'tag' of a group of resources. +// +// CategoryExpanderWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use CategoryExpanderWithContext instead. type CategoryExpander interface { Expand(category string) ([]schema.GroupResource, bool) } -// SimpleCategoryExpander implements CategoryExpander interface +// CategoryExpanderWithContext maps category strings to GroupResources. +// Categories are classification or 'tag' of a group of resources. +type CategoryExpanderWithContext interface { + ExpandWithContext(ctx context.Context, category string) ([]schema.GroupResource, bool) +} + +func ToCategoryExpanderWithContext(c CategoryExpander) CategoryExpanderWithContext { + if c == nil { + return nil + } + if c, ok := c.(CategoryExpanderWithContext); ok { + return c + } + return &categoryExpanderWrapper{ + delegate: c, + } +} + +type categoryExpanderWrapper struct { + delegate CategoryExpander +} + +func (c *categoryExpanderWrapper) ExpandWithContext(ctx context.Context, category string) ([]schema.GroupResource, bool) { + return c.delegate.Expand(category) +} + +// SimpleCategoryExpander implements CategoryExpander and CategoryExpanderWithContext interface // using a static mapping of categories to GroupResource mapping. type SimpleCategoryExpander struct { Expansions map[string][]schema.GroupResource } +var ( + _ CategoryExpander = SimpleCategoryExpander{} + _ CategoryExpanderWithContext = SimpleCategoryExpander{} +) + // Expand fulfills CategoryExpander func (e SimpleCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) { ret, ok := e.Expansions[category] return ret, ok } +// ExpandWithContext fulfills CategoryExpanderWithContext +func (e SimpleCategoryExpander) ExpandWithContext(ctx context.Context, category string) ([]schema.GroupResource, bool) { + return e.Expand(category) +} + // discoveryCategoryExpander struct lets a REST Client wrapper (discoveryClient) to retrieve list of APIResourceList, // and then convert to fallbackExpander type discoveryCategoryExpander struct { - discoveryClient discovery.DiscoveryInterface + discoveryClient discovery.DiscoveryInterfaceWithContext } // NewDiscoveryCategoryExpander returns a category expander that makes use of the "categories" fields from // the API, found through the discovery client. In case of any error or no category found (which likely // means we're at a cluster prior to categories support, fallback to the expander provided. +// +// NewDiscoveryCategoryExpanderWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use NewDiscoveryCategoryExpanderWithContext instead. func NewDiscoveryCategoryExpander(client discovery.DiscoveryInterface) CategoryExpander { + return newDiscoveryCategoryExpander(discovery.ToDiscoveryInterfaceWithContext(client)) +} + +// NewDiscoveryCategoryExpanderWithContext returns a category expander that makes use of the "categories" fields from +// the API, found through the discovery client. In case of any error or no category found (which likely +// means we're at a cluster prior to categories support, fallback to the expander provided. +func NewDiscoveryCategoryExpanderWithContext(client discovery.DiscoveryInterfaceWithContext) CategoryExpanderWithContext { + return newDiscoveryCategoryExpander(client) +} + +func newDiscoveryCategoryExpander(client discovery.DiscoveryInterfaceWithContext) discoveryCategoryExpander { if client == nil { panic("Please provide discovery client to shortcut expander") } @@ -56,9 +115,18 @@ func NewDiscoveryCategoryExpander(client discovery.DiscoveryInterface) CategoryE } // Expand fulfills CategoryExpander +// +// ExpandWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ExpandWithContext instead. func (e discoveryCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) { + return e.ExpandWithContext(context.Background(), category) +} + +// ExpandWithContext fulfills CategoryExpanderWithContext +func (e discoveryCategoryExpander) ExpandWithContext(ctx context.Context, category string) ([]schema.GroupResource, bool) { // Get all supported resources for groups and versions from server, if no resource found, fallback anyway. - _, apiResourceLists, _ := e.discoveryClient.ServerGroupsAndResources() + _, apiResourceLists, _ := e.discoveryClient.ServerGroupsAndResourcesWithContext(ctx) if len(apiResourceLists) == 0 { return nil, false } @@ -89,16 +157,43 @@ func (e discoveryCategoryExpander) Expand(category string) ([]schema.GroupResour // UnionCategoryExpander implements CategoryExpander interface. // It maps given category string to union of expansions returned by all the CategoryExpanders in the list. +// +// UnionCategoryExpanderWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use UnionCategoryExpanderWithContext instead. type UnionCategoryExpander []CategoryExpander +var _ CategoryExpander = UnionCategoryExpander{} + // Expand fulfills CategoryExpander func (u UnionCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) { + return unionExpand(context.Background(), func(yield func(i int, expander CategoryExpanderWithContext) bool) { + for i, expander := range u { + if !yield(i, ToCategoryExpanderWithContext(expander)) { + break + } + } + }, category) +} + +// UnionCategoryExpanderWithContext implements CategoryExpanderWithContext interface. +// It maps given category string to union of expansions returned by all the CategoryExpanders in the list. +type UnionCategoryExpanderWithContext []CategoryExpanderWithContext + +var _ CategoryExpanderWithContext = UnionCategoryExpanderWithContext{} + +// ExpandWithContext fulfills CategoryExpanderWithContext +func (u UnionCategoryExpanderWithContext) ExpandWithContext(ctx context.Context, category string) ([]schema.GroupResource, bool) { + return unionExpand(ctx, slices.All(u), category) +} + +func unionExpand(ctx context.Context, expanders iter.Seq2[int, CategoryExpanderWithContext], category string) ([]schema.GroupResource, bool) { ret := []schema.GroupResource{} ok := false // Expand the category for each CategoryExpander in the list and merge/combine the results. - for _, expansion := range u { - curr, currOk := expansion.Expand(category) + for _, expansion := range expanders { + curr, currOk := expansion.ExpandWithContext(ctx, category) for _, currGR := range curr { found := false diff --git a/constraint/vendor/k8s.io/client-go/restmapper/discovery.go b/constraint/vendor/k8s.io/client-go/restmapper/discovery.go index 3505178b6..9457cccd3 100644 --- a/constraint/vendor/k8s.io/client-go/restmapper/discovery.go +++ b/constraint/vendor/k8s.io/client-go/restmapper/discovery.go @@ -17,6 +17,7 @@ limitations under the License. package restmapper import ( + "context" "fmt" "strings" "sync" @@ -40,8 +41,40 @@ type APIGroupResources struct { // NewDiscoveryRESTMapper returns a PriorityRESTMapper based on the discovered // groups and resources passed in. +// +// NewDiscoveryRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use NewDiscoveryRESTMapperWithContext instead. func NewDiscoveryRESTMapper(groupResources []*APIGroupResources) meta.RESTMapper { - unionMapper := meta.MultiRESTMapper{} + mappers, resourcePriority, kindPriority := newDiscoveryRESTMapper(groupResources) + multiMapper := make(meta.MultiRESTMapper, len(mappers)) + for i, m := range mappers { + multiMapper[i] = m + } + return &meta.PriorityRESTMapper{ + Delegate: multiMapper, + ResourcePriority: resourcePriority, + KindPriority: kindPriority, + } +} + +// NewDiscoveryRESTMapperWithContext returns a PriorityRESTMapper based on the discovered +// groups and resources passed in. +func NewDiscoveryRESTMapperWithContext(groupResources []*APIGroupResources) meta.RESTMapperWithContext { + mappers, resourcePriority, kindPriority := newDiscoveryRESTMapper(groupResources) + multiMapper := make(meta.MultiRESTMapperWithContext, len(mappers)) + for i, m := range mappers { + multiMapper[i] = m + } + return &meta.PriorityRESTMapperWithContext{ + Delegate: multiMapper, + ResourcePriority: resourcePriority, + KindPriority: kindPriority, + } +} + +func newDiscoveryRESTMapper(groupResources []*APIGroupResources) ([]*meta.DefaultRESTMapper, []schema.GroupVersionResource, []schema.GroupVersionKind) { + var unionMapper []*meta.DefaultRESTMapper var groupPriority []string // /v1 is special. It should always come first @@ -135,17 +168,23 @@ func NewDiscoveryRESTMapper(groupResources []*APIGroupResources) meta.RESTMapper }) } - return meta.PriorityRESTMapper{ - Delegate: unionMapper, - ResourcePriority: resourcePriority, - KindPriority: kindPriority, - } + return unionMapper, resourcePriority, kindPriority } // GetAPIGroupResources uses the provided discovery client to gather // discovery information and populate a slice of APIGroupResources. +// +// GetAPIGroupResourcesWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use GetAPIGroupResourcesWithContext instead. func GetAPIGroupResources(cl discovery.DiscoveryInterface) ([]*APIGroupResources, error) { - gs, rs, err := cl.ServerGroupsAndResources() + return GetAPIGroupResourcesWithContext(context.Background(), discovery.ToDiscoveryInterfaceWithContext(cl)) +} + +// GetAPIGroupResourcesWithContext uses the provided discovery client to gather +// discovery information and populate a slice of APIGroupResources. +func GetAPIGroupResourcesWithContext(ctx context.Context, cl discovery.DiscoveryInterfaceWithContext) ([]*APIGroupResources, error) { + gs, rs, err := cl.ServerGroupsAndResourcesWithContext(ctx) if rs == nil || gs == nil { return nil, err // TODO track the errors and update callers to handle partial errors. @@ -173,25 +212,45 @@ func GetAPIGroupResources(cl discovery.DiscoveryInterface) ([]*APIGroupResources return result, nil } -// DeferredDiscoveryRESTMapper is a RESTMapper that will defer +// DeferredDiscoveryRESTMapper is a RESTMapper and RESTMapperContext that will defer // initialization of the RESTMapper until the first mapping is // requested. type DeferredDiscoveryRESTMapper struct { initMu sync.Mutex - delegate meta.RESTMapper - cl discovery.CachedDiscoveryInterface + delegate meta.RESTMapperWithContext + cl discovery.CachedDiscoveryInterfaceWithContext } +var ( + //nolint:staticcheck // Intentionally using the old interface here. + _ meta.ResettableRESTMapper = &DeferredDiscoveryRESTMapper{} + _ meta.ResettableRESTMapperWithContext = &DeferredDiscoveryRESTMapper{} + _ fmt.Stringer = &DeferredDiscoveryRESTMapper{} +) + // NewDeferredDiscoveryRESTMapper returns a // DeferredDiscoveryRESTMapper that will lazily query the provided // client for discovery information to do REST mappings. +// +// NewDeferredDiscoveryRESTMapperWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use NewDeferredDiscoveryRESTMapperWithContext instead. NewDeferredDiscoveryRESTMapper will try to convert cl to discovery.CachedDiscoveryInterfaceWithContext and use a wrapper if that is not possible, but NewDeferredDiscoveryRESTMapperWithContext ensures that no such conversion is necessary. func NewDeferredDiscoveryRESTMapper(cl discovery.CachedDiscoveryInterface) *DeferredDiscoveryRESTMapper { + return &DeferredDiscoveryRESTMapper{ + cl: discovery.ToCachedDiscoveryInterfaceWithContext(cl), + } +} + +// NewDeferredDiscoveryRESTMapperWithContext returns a +// DeferredDiscoveryRESTMapper that will lazily query the provided +// client for discovery information to do REST mappings. +func NewDeferredDiscoveryRESTMapperWithContext(cl discovery.CachedDiscoveryInterfaceWithContext) *DeferredDiscoveryRESTMapper { return &DeferredDiscoveryRESTMapper{ cl: cl, } } -func (d *DeferredDiscoveryRESTMapper) getDelegate() (meta.RESTMapper, error) { +func (d *DeferredDiscoveryRESTMapper) getDelegate(ctx context.Context) (meta.RESTMapperWithContext, error) { d.initMu.Lock() defer d.initMu.Unlock() @@ -199,98 +258,154 @@ func (d *DeferredDiscoveryRESTMapper) getDelegate() (meta.RESTMapper, error) { return d.delegate, nil } - groupResources, err := GetAPIGroupResources(d.cl) + groupResources, err := GetAPIGroupResourcesWithContext(ctx, d.cl) if err != nil { return nil, err } - d.delegate = NewDiscoveryRESTMapper(groupResources) + d.delegate = NewDiscoveryRESTMapperWithContext(groupResources) return d.delegate, nil } // Reset resets the internally cached Discovery information and will // cause the next mapping request to re-discover. func (d *DeferredDiscoveryRESTMapper) Reset() { - klog.V(5).Info("Invalidating discovery information") + d.ResetWithContext(context.Background()) +} + +// ResetWithContext resets the internally cached Discovery information and will +// cause the next mapping request to re-discover. +func (d *DeferredDiscoveryRESTMapper) ResetWithContext(ctx context.Context) { + klog.FromContext(ctx).V(5).Info("Invalidating discovery information") d.initMu.Lock() defer d.initMu.Unlock() - d.cl.Invalidate() + d.cl.InvalidateWithContext(ctx) d.delegate = nil } // KindFor takes a partial resource and returns back the single match. // It returns an error if there are multiple matches. +// +// KindForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use KindForWithContext instead. func (d *DeferredDiscoveryRESTMapper) KindFor(resource schema.GroupVersionResource) (gvk schema.GroupVersionKind, err error) { - del, err := d.getDelegate() + return d.KindForWithContext(context.Background(), resource) +} + +// KindForWithContext takes a partial resource and returns back the single match. +// It returns an error if there are multiple matches. +func (d *DeferredDiscoveryRESTMapper) KindForWithContext(ctx context.Context, resource schema.GroupVersionResource) (gvk schema.GroupVersionKind, err error) { + del, err := d.getDelegate(ctx) if err != nil { return schema.GroupVersionKind{}, err } - gvk, err = del.KindFor(resource) - if err != nil && !d.cl.Fresh() { - d.Reset() - gvk, err = d.KindFor(resource) + gvk, err = del.KindForWithContext(ctx, resource) + if err != nil && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + gvk, err = d.KindForWithContext(ctx, resource) } return } // KindsFor takes a partial resource and returns back the list of // potential kinds in priority order. +// +// KindsForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use KindsForWithContext instead. func (d *DeferredDiscoveryRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvks []schema.GroupVersionKind, err error) { - del, err := d.getDelegate() + return d.KindsForWithContext(context.Background(), resource) +} + +// KindsForWithContext takes a partial resource and returns back the list of +// potential kinds in priority order. +func (d *DeferredDiscoveryRESTMapper) KindsForWithContext(ctx context.Context, resource schema.GroupVersionResource) (gvks []schema.GroupVersionKind, err error) { + del, err := d.getDelegate(ctx) if err != nil { return nil, err } - gvks, err = del.KindsFor(resource) - if len(gvks) == 0 && !d.cl.Fresh() { - d.Reset() - gvks, err = d.KindsFor(resource) + gvks, err = del.KindsForWithContext(ctx, resource) + if len(gvks) == 0 && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + gvks, err = d.KindsForWithContext(ctx, resource) } return } // ResourceFor takes a partial resource and returns back the single // match. It returns an error if there are multiple matches. +// +// ResourceForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourceForWithContext instead. func (d *DeferredDiscoveryRESTMapper) ResourceFor(input schema.GroupVersionResource) (gvr schema.GroupVersionResource, err error) { - del, err := d.getDelegate() + return d.ResourceForWithContext(context.Background(), input) +} + +// ResourceForWithContext takes a partial resource and returns back the single +// match. It returns an error if there are multiple matches. +func (d *DeferredDiscoveryRESTMapper) ResourceForWithContext(ctx context.Context, input schema.GroupVersionResource) (gvr schema.GroupVersionResource, err error) { + del, err := d.getDelegate(ctx) if err != nil { return schema.GroupVersionResource{}, err } - gvr, err = del.ResourceFor(input) - if err != nil && !d.cl.Fresh() { - d.Reset() - gvr, err = d.ResourceFor(input) + gvr, err = del.ResourceForWithContext(ctx, input) + if err != nil && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + gvr, err = d.ResourceForWithContext(ctx, input) } return } // ResourcesFor takes a partial resource and returns back the list of // potential resource in priority order. +// +// ResourcesForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourcesForWithContext instead. func (d *DeferredDiscoveryRESTMapper) ResourcesFor(input schema.GroupVersionResource) (gvrs []schema.GroupVersionResource, err error) { - del, err := d.getDelegate() + return d.ResourcesForWithContext(context.Background(), input) +} + +// ResourcesForWithContext takes a partial resource and returns back the list of +// potential resource in priority order. +func (d *DeferredDiscoveryRESTMapper) ResourcesForWithContext(ctx context.Context, input schema.GroupVersionResource) (gvrs []schema.GroupVersionResource, err error) { + del, err := d.getDelegate(ctx) if err != nil { return nil, err } - gvrs, err = del.ResourcesFor(input) - if len(gvrs) == 0 && !d.cl.Fresh() { - d.Reset() - gvrs, err = d.ResourcesFor(input) + gvrs, err = del.ResourcesForWithContext(ctx, input) + if len(gvrs) == 0 && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + gvrs, err = d.ResourcesForWithContext(ctx, input) } return } // RESTMapping identifies a preferred resource mapping for the // provided group kind. +// +// RESTMappingWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use RESTMappingWithContext instead. func (d *DeferredDiscoveryRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (m *meta.RESTMapping, err error) { - del, err := d.getDelegate() + return d.RESTMappingWithContext(context.Background(), gk, versions...) +} + +// RESTMappingWithContext identifies a preferred resource mapping for the +// provided group kind. +func (d *DeferredDiscoveryRESTMapper) RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (m *meta.RESTMapping, err error) { + del, err := d.getDelegate(ctx) if err != nil { return nil, err } - m, err = del.RESTMapping(gk, versions...) - if err != nil && !d.cl.Fresh() { - d.Reset() - m, err = d.RESTMapping(gk, versions...) + m, err = del.RESTMappingWithContext(ctx, gk, versions...) + if err != nil && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + m, err = d.RESTMappingWithContext(ctx, gk, versions...) } return } @@ -298,41 +413,59 @@ func (d *DeferredDiscoveryRESTMapper) RESTMapping(gk schema.GroupKind, versions // RESTMappings returns the RESTMappings for the provided group kind // in a rough internal preferred order. If no kind is found, it will // return a NoResourceMatchError. +// +// RESTMappingsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use RESTMappingsWithContext instead. func (d *DeferredDiscoveryRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) (ms []*meta.RESTMapping, err error) { - del, err := d.getDelegate() + return d.RESTMappingsWithContext(context.Background(), gk, versions...) +} + +// RESTMappingsWithContext returns the RESTMappings for the provided group kind +// in a rough internal preferred order. If no kind is found, it will +// return a NoResourceMatchError. +func (d *DeferredDiscoveryRESTMapper) RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (ms []*meta.RESTMapping, err error) { + del, err := d.getDelegate(ctx) if err != nil { return nil, err } - ms, err = del.RESTMappings(gk, versions...) - if len(ms) == 0 && !d.cl.Fresh() { - d.Reset() - ms, err = d.RESTMappings(gk, versions...) + ms, err = del.RESTMappingsWithContext(ctx, gk, versions...) + if len(ms) == 0 && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + ms, err = d.RESTMappingsWithContext(ctx, gk, versions...) } return } // ResourceSingularizer converts a resource name from plural to // singular (e.g., from pods to pod). +// +// ResourceSingularizerWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourceSingularizerWithContext instead. func (d *DeferredDiscoveryRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { - del, err := d.getDelegate() + return d.ResourceSingularizerWithContext(context.Background(), resource) +} + +// ResourceSingularizerWithContext converts a resource name from plural to +// singular (e.g., from pods to pod). +func (d *DeferredDiscoveryRESTMapper) ResourceSingularizerWithContext(ctx context.Context, resource string) (singular string, err error) { + del, err := d.getDelegate(ctx) if err != nil { return resource, err } - singular, err = del.ResourceSingularizer(resource) - if err != nil && !d.cl.Fresh() { - d.Reset() - singular, err = d.ResourceSingularizer(resource) + singular, err = del.ResourceSingularizerWithContext(ctx, resource) + if err != nil && !d.cl.FreshWithContext(ctx) { + d.ResetWithContext(ctx) + singular, err = d.ResourceSingularizerWithContext(ctx, resource) } return } func (d *DeferredDiscoveryRESTMapper) String() string { - del, err := d.getDelegate() + del, err := d.getDelegate(context.Background() /* hopefully we already have a delegate and don't need the context */) if err != nil { return fmt.Sprintf("DeferredDiscoveryRESTMapper{%v}", err) } return fmt.Sprintf("DeferredDiscoveryRESTMapper{\n\t%v\n}", del) } - -// Make sure it satisfies the interface -var _ meta.ResettableRESTMapper = &DeferredDiscoveryRESTMapper{} diff --git a/constraint/vendor/k8s.io/client-go/restmapper/shortcut.go b/constraint/vendor/k8s.io/client-go/restmapper/shortcut.go index 0afc8689d..4dbeea07d 100644 --- a/constraint/vendor/k8s.io/client-go/restmapper/shortcut.go +++ b/constraint/vendor/k8s.io/client-go/restmapper/shortcut.go @@ -17,6 +17,7 @@ limitations under the License. package restmapper import ( + "context" "fmt" "strings" @@ -30,22 +31,41 @@ import ( // shortcutExpander is a RESTMapper that can be used for Kubernetes resources. It expands the resource first, then invokes the wrapped type shortcutExpander struct { - RESTMapper meta.RESTMapper + RESTMapper meta.RESTMapperWithContext - discoveryClient discovery.DiscoveryInterface + discoveryClient discovery.DiscoveryInterfaceWithContext warningHandler func(string) } var _ meta.ResettableRESTMapper = shortcutExpander{} +var _ meta.ResettableRESTMapperWithContext = shortcutExpander{} // NewShortcutExpander wraps a restmapper in a layer that expands shortcuts found via discovery +// +// NewShortcutExpanderWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use NewShortcutExpanderWithContext instead. func NewShortcutExpander(delegate meta.RESTMapper, client discovery.DiscoveryInterface, warningHandler func(string)) meta.RESTMapper { + return newShortcutExpander(meta.ToRESTMapperWithContext(delegate), discovery.ToDiscoveryInterfaceWithContext(client), warningHandler) +} + +// NewShortcutExpanderWithContext wraps a restmapper in a layer that expands shortcuts found via discovery +func NewShortcutExpanderWithContext(delegate meta.RESTMapperWithContext, client discovery.DiscoveryInterfaceWithContext, warningHandler func(string)) meta.RESTMapperWithContext { + return newShortcutExpander(delegate, client, warningHandler) +} + +func newShortcutExpander(delegate meta.RESTMapperWithContext, client discovery.DiscoveryInterfaceWithContext, warningHandler func(string)) shortcutExpander { return shortcutExpander{RESTMapper: delegate, discoveryClient: client, warningHandler: warningHandler} } // KindFor fulfills meta.RESTMapper func (e shortcutExpander) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return e.KindForWithContext(context.Background(), resource) +} + +// KindForWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) KindForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { // expandResourceShortcut works with current API resources as read from discovery cache. // In case of new CRDs this means we potentially don't have current state of discovery. // In the current wiring in k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#toRESTMapper, @@ -53,59 +73,113 @@ func (e shortcutExpander) KindFor(resource schema.GroupVersionResource) (schema. // cache and fetch all data from a cluster (see k8s.io/client-go/restmapper/discovery.go#KindFor). // Thus another call to expandResourceShortcut, after a NoMatchError should successfully // read Kind to the user or an error. - gvk, err := e.RESTMapper.KindFor(e.expandResourceShortcut(resource)) + gvk, err := e.RESTMapper.KindForWithContext(ctx, e.expandResourceShortcut(ctx, resource)) if meta.IsNoMatchError(err) { - return e.RESTMapper.KindFor(e.expandResourceShortcut(resource)) + return e.RESTMapper.KindForWithContext(ctx, e.expandResourceShortcut(ctx, resource)) } return gvk, err } // KindsFor fulfills meta.RESTMapper +// +// KindsForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use KindsForWithContext instead. func (e shortcutExpander) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { - return e.RESTMapper.KindsFor(e.expandResourceShortcut(resource)) + return e.KindsForWithContext(context.Background(), resource) +} + +// KindsForWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) KindsForWithContext(ctx context.Context, resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { + return e.RESTMapper.KindsForWithContext(ctx, e.expandResourceShortcut(ctx, resource)) } // ResourcesFor fulfills meta.RESTMapper +// +// ResourcesForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourcesForWithContext instead. func (e shortcutExpander) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { - return e.RESTMapper.ResourcesFor(e.expandResourceShortcut(resource)) + return e.ResourcesForWithContext(context.Background(), resource) +} + +// ResourcesForWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) ResourcesForWithContext(ctx context.Context, resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + return e.RESTMapper.ResourcesForWithContext(ctx, e.expandResourceShortcut(ctx, resource)) } // ResourceFor fulfills meta.RESTMapper +// +// ResourceForWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourceForWithContext instead. func (e shortcutExpander) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { - return e.RESTMapper.ResourceFor(e.expandResourceShortcut(resource)) + return e.ResourceForWithContext(context.Background(), resource) +} + +// ResourceForWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) ResourceForWithContext(ctx context.Context, resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { + return e.RESTMapper.ResourceForWithContext(ctx, e.expandResourceShortcut(ctx, resource)) } // ResourceSingularizer fulfills meta.RESTMapper +// +// ResourceSingularizerWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResourceSingularizerWithContext instead. func (e shortcutExpander) ResourceSingularizer(resource string) (string, error) { - return e.RESTMapper.ResourceSingularizer(e.expandResourceShortcut(schema.GroupVersionResource{Resource: resource}).Resource) + return e.ResourceSingularizerWithContext(context.Background(), resource) +} + +// ResourceSingularizerWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) ResourceSingularizerWithContext(ctx context.Context, resource string) (string, error) { + return e.RESTMapper.ResourceSingularizerWithContext(ctx, e.expandResourceShortcut(ctx, schema.GroupVersionResource{Resource: resource}).Resource) } // RESTMapping fulfills meta.RESTMapper +// +// RESTMappingWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use RESTMappingWithContext instead. func (e shortcutExpander) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) { - return e.RESTMapper.RESTMapping(gk, versions...) + return e.RESTMappingWithContext(context.Background(), gk, versions...) +} + +// RESTMappingWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) RESTMappingWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) { + return e.RESTMapper.RESTMappingWithContext(ctx, gk, versions...) } // RESTMappings fulfills meta.RESTMapper +// +// RESTMappingsWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use RESTMappingsWithContext instead. func (e shortcutExpander) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) { - return e.RESTMapper.RESTMappings(gk, versions...) + return e.RESTMappingsWithContext(context.Background(), gk, versions...) +} + +// RESTMappingsWithContext fulfills meta.RESTMapperWithContext +func (e shortcutExpander) RESTMappingsWithContext(ctx context.Context, gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) { + return e.RESTMapper.RESTMappingsWithContext(ctx, gk, versions...) } // getShortcutMappings returns a set of tuples which holds short names for resources. // First the list of potential resources will be taken from the API server. // Next we will append the hardcoded list of resources - to be backward compatible with old servers. // NOTE that the list is ordered by group priority. -func (e shortcutExpander) getShortcutMappings() ([]*metav1.APIResourceList, []resourceShortcuts, error) { +func (e shortcutExpander) getShortcutMappings(ctx context.Context) ([]*metav1.APIResourceList, []resourceShortcuts, error) { res := []resourceShortcuts{} // get server resources // This can return an error *and* the results it was able to find. We don't need to fail on the error. - _, apiResList, err := e.discoveryClient.ServerGroupsAndResources() + _, apiResList, err := e.discoveryClient.ServerGroupsAndResourcesWithContext(ctx) if err != nil { - klog.V(1).Infof("Error loading discovery information: %v", err) + klog.FromContext(ctx).V(1).Info("Error loading discovery information", "err", err) } for _, apiResources := range apiResList { gv, err := schema.ParseGroupVersion(apiResources.GroupVersion) if err != nil { - klog.V(1).Infof("Unable to parse groupversion = %s due to = %s", apiResources.GroupVersion, err.Error()) + klog.FromContext(ctx).V(1).Info("Unable to parse group/version", "groupVersion", apiResources.GroupVersion, "err", err.Error()) continue } for _, apiRes := range apiResources.APIResources { @@ -126,9 +200,9 @@ func (e shortcutExpander) getShortcutMappings() ([]*metav1.APIResourceList, []re // (something that a pkg/api/meta.RESTMapper can understand), if it is // indeed a shortcut. If no match has been found, we will match on group prefixing. // Lastly we will return resource unmodified. -func (e shortcutExpander) expandResourceShortcut(resource schema.GroupVersionResource) schema.GroupVersionResource { +func (e shortcutExpander) expandResourceShortcut(ctx context.Context, resource schema.GroupVersionResource) schema.GroupVersionResource { // get the shortcut mappings and return on first match. - if allResources, shortcutResources, err := e.getShortcutMappings(); err == nil { + if allResources, shortcutResources, err := e.getShortcutMappings(ctx); err == nil { // avoid expanding if there's an exact match to a full resource name for _, apiResources := range allResources { gv, err := schema.ParseGroupVersion(apiResources.GroupVersion) @@ -199,8 +273,15 @@ func (e shortcutExpander) expandResourceShortcut(resource schema.GroupVersionRes return resource } +// ResetWithContext is a better alternative because it supports contextual logging and cancellation. +// +// Contextual logging: Use ResetWithContext instead. func (e shortcutExpander) Reset() { - meta.MaybeResetRESTMapper(e.RESTMapper) + e.ResetWithContext(context.Background()) +} + +func (e shortcutExpander) ResetWithContext(ctx context.Context) { + meta.MaybeResetRESTMapperWithContext(ctx, e.RESTMapper) } // ResourceShortcuts represents a structure that holds the information how to diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/OWNERS b/constraint/vendor/k8s.io/client-go/tools/cache/OWNERS index 77d7e4d28..f62d5e3c5 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/OWNERS +++ b/constraint/vendor/k8s.io/client-go/tools/cache/OWNERS @@ -5,7 +5,6 @@ approvers: - smarterclayton - wojtek-t - deads2k - - caesarxuchao - liggitt reviewers: - thockin @@ -13,8 +12,6 @@ reviewers: - wojtek-t - deads2k - derekwaynecarr - - caesarxuchao - - mikedanese - liggitt - janetkuo - justinsb @@ -24,5 +21,6 @@ reviewers: - ingvagabund - michaelasp emeritus_approvers: + - caesarxuchao - lavalamp - ncdc diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/controller.go b/constraint/vendor/k8s.io/client-go/tools/cache/controller.go index b78ed522e..adb1fb930 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/controller.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/controller.go @@ -20,9 +20,11 @@ import ( "context" "errors" "fmt" + "strings" "sync" "time" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" @@ -282,6 +284,126 @@ type ResourceEventHandler interface { OnDelete(obj interface{}) } +// Object is the subset of metav1.Object that is needed to determine the +// name and, if applicable, namespace of an object. All standard Kubernetes +// API types satisfy this interface through their embedded ObjectMeta. +// +// comparable is required so that a zero T can be compared against +// OptionalObj to detect a missing object (e.g. a nil pointer). +type Object interface { + comparable + + GetName() string + GetNamespace() string +} + +// TypedResourceEventHandler is a type-safe variant of ResourceEventHandler. +type TypedResourceEventHandler[T Object] interface { + OnAdd(obj T, isInInitialList bool) + OnUpdate(oldObj, newObj T) + OnDelete(obj DeletedObject[T]) +} + +// DeletedObject provides information about a deleted object. +// +// It implements GetObjectName and GetKey, which replace +// [DeletionHandlingObjectToName] and [DeletionHandlingMetaNamespaceKeyFunc] +// +// It implements the GetName and GetNamespace methods for use +// with klog.KObj: an OnDelete event handler can log +// it's parameter directly and is guaranteed to produce the same +// log output as with klog.KObj applied to the actual object. +// +// All of these methods work regardless whether DeletedObject actually has +// the deleted object. +type DeletedObject[T Object] struct { + // OptionalObj is the deleted object. + // + // It can be: + // - stale: it is some *older* revision, not the one which got deleted + // - nil: the informer noticed a deletion without finding *any* copy of the deleted object + // + // The only guaranteed information is the key under which the deleted + // object was stored in the informer cache. Use [DeletedObject.GetObjectName] + // and [DeletedObject.GetKey] to extract the namespace and name resp. + // the key under which the deleted object was stored. They work in + // all cases. + OptionalObj T + + // FinalStateUnknown is nil if the deleted object is available and up-to-date. + // Otherwise FinalStateUnknown is non-nil to provide the key. + // The untyped object inside it matches OptionalObj. + FinalStateUnknown *DeletedFinalStateUnknown +} + +// GetObjectName returns the object name (= namespace if available and name) +// for the deleted object. Note that this is slightly different from +// GetName which returns just that name without the namespace. +// +// This is a type-safe variant of [DeletionHandlingObjectToName] which +// cannot fail because T is guaranteed to have a name and namespace and +// the key of FinalStateUnknown, if invalid, is simply treated as a +// name without a namespace. +func (d DeletedObject[T]) GetObjectName() ObjectName { + if d.FinalStateUnknown != nil { + // Same splitting as SplitMetaNamespaceKey and ParseObjectName, + // except that a key with more than one "/" is not treated as an error: + // the extra "/" become part of the name. + namespace, name, found := strings.Cut(d.FinalStateUnknown.Key, "/") + if !found { + return ObjectName{Name: namespace} + } + return ObjectName{Namespace: namespace, Name: name} + } + var null T + if d.OptionalObj == null { + // Avoid calling GetName/GetNamespace on a zero OptionalObj (e.g. a + // nil pointer), which could panic. A nil pointer boxed behind a + // further layer of indirection is not detected here and is not + // handled. + return ObjectName{} + } + // Same logic as MetaObjectToName, adapted to use T's own + // GetNamespace and GetName methods instead of going through + // meta.Accessor as ObjectToName does. + if namespace := d.OptionalObj.GetNamespace(); len(namespace) > 0 { + return ObjectName{Namespace: namespace, Name: d.OptionalObj.GetName()} + } + return ObjectName{Name: d.OptionalObj.GetName()} +} + +// GetName returns the name without the namespace. Note that this is slightly +// different from GetObjectName which returns the combination of namespace and name in a +// struct. +func (d DeletedObject[T]) GetName() string { + return d.GetObjectName().Name +} + +// GetNamespace returns the namespace if there is one, otherwise the empty string. +func (d DeletedObject[T]) GetNamespace() string { + return d.GetObjectName().Namespace +} + +// GetKey returns the key under which the deleted object was stored. +// +// This is a type-safe variant of [DeletionHandlingMetaNamespaceKeyFunc] +// which cannot fail because T is guaranteed to have a name and namespace. +func (d DeletedObject[T]) GetKey() string { + if d.FinalStateUnknown != nil { + return d.FinalStateUnknown.Key + } + var null T + if d.OptionalObj == null { + return "" + } + // Same encoding as MetaNamespaceKeyFunc via ObjectName.String, + // adapted to use T's own GetNamespace and GetName methods. + if namespace := d.OptionalObj.GetNamespace(); len(namespace) > 0 { + return namespace + "/" + d.OptionalObj.GetName() + } + return d.OptionalObj.GetName() +} + // ResourceEventHandlerFuncs is an adaptor to let you easily specify as many or // as few of the notification functions as you want while still implementing // ResourceEventHandler. This adapter does not remove the prohibition against @@ -316,6 +438,32 @@ func (r ResourceEventHandlerFuncs) OnDelete(obj interface{}) { } } +type TypedResourceEventHandlerFuncs[T Object] struct { + AddFunc func(obj T) + UpdateFunc func(oldObj, newObj T) + DeleteFunc func(obj DeletedObject[T]) +} + +var _ TypedResourceEventHandler[*metav1.ObjectMeta] = TypedResourceEventHandlerFuncs[*metav1.ObjectMeta]{} + +func (r TypedResourceEventHandlerFuncs[T]) OnAdd(obj T, isInInitialList bool) { + if r.AddFunc != nil { + r.AddFunc(obj) + } +} + +func (r TypedResourceEventHandlerFuncs[T]) OnUpdate(oldObj, newObj T) { + if r.UpdateFunc != nil { + r.UpdateFunc(oldObj, newObj) + } +} + +func (r TypedResourceEventHandlerFuncs[T]) OnDelete(obj DeletedObject[T]) { + if r.DeleteFunc != nil { + r.DeleteFunc(obj) + } +} + // ResourceEventHandlerDetailedFuncs is exactly like ResourceEventHandlerFuncs // except its AddFunc accepts the isInInitialList parameter, for propagating // HasSynced. @@ -346,6 +494,32 @@ func (r ResourceEventHandlerDetailedFuncs) OnDelete(obj interface{}) { } } +type TypedResourceEventHandlerDetailedFuncs[T Object] struct { + AddFunc func(obj T, isInInitialList bool) + UpdateFunc func(oldObj, newObj T) + DeleteFunc func(obj DeletedObject[T]) +} + +var _ TypedResourceEventHandler[*metav1.ObjectMeta] = TypedResourceEventHandlerDetailedFuncs[*metav1.ObjectMeta]{} + +func (r TypedResourceEventHandlerDetailedFuncs[T]) OnAdd(obj T, isInInitialList bool) { + if r.AddFunc != nil { + r.AddFunc(obj, isInInitialList) + } +} + +func (r TypedResourceEventHandlerDetailedFuncs[T]) OnUpdate(oldObj, newObj T) { + if r.UpdateFunc != nil { + r.UpdateFunc(oldObj, newObj) + } +} + +func (r TypedResourceEventHandlerDetailedFuncs[T]) OnDelete(obj DeletedObject[T]) { + if r.DeleteFunc != nil { + r.DeleteFunc(obj) + } +} + // FilteringResourceEventHandler applies the provided filter to all events coming // in, ensuring the appropriate nested handler method is invoked. An object // that starts passing the filter after an update is considered an add, and an @@ -388,6 +562,48 @@ func (r FilteringResourceEventHandler) OnDelete(obj interface{}) { r.Handler.OnDelete(obj) } +// TypedFilteringResourceEventHandler is a type-safe variant of +// [FilteringResourceEventHandler]. +type TypedFilteringResourceEventHandler[T Object] struct { + FilterFunc func(obj T) bool + Handler TypedResourceEventHandler[T] +} + +// OnAdd calls the nested handler only if the filter succeeds +func (r TypedFilteringResourceEventHandler[T]) OnAdd(obj T, isInInitialList bool) { + if !r.FilterFunc(obj) { + return + } + r.Handler.OnAdd(obj, isInInitialList) +} + +// OnUpdate ensures the proper handler is called depending on whether the filter matches +func (r TypedFilteringResourceEventHandler[T]) OnUpdate(oldObj, newObj T) { + newer := r.FilterFunc(newObj) + older := r.FilterFunc(oldObj) + switch { + case newer && older: + r.Handler.OnUpdate(oldObj, newObj) + case newer && !older: + r.Handler.OnAdd(newObj, false) + case !newer && older: + r.Handler.OnDelete(DeletedObject[T]{OptionalObj: oldObj}) + default: + // do nothing + } +} + +// OnDelete calls the nested handler only if the filter succeeds. The filter +// is applied to [DeletedObject.OptionalObj], which may be the zero value of T +// if the deleted object could not be recovered; a FilterFunc that relies on T +// having a valid state must handle that case itself. +func (r TypedFilteringResourceEventHandler[T]) OnDelete(obj DeletedObject[T]) { + if !r.FilterFunc(obj.OptionalObj) { + return + } + r.Handler.OnDelete(obj) +} + // DeletionHandlingMetaNamespaceKeyFunc checks for // DeletedFinalStateUnknown objects before calling // MetaNamespaceKeyFunc. diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/index.go b/constraint/vendor/k8s.io/client-go/tools/cache/index.go index 395268f68..ca0d904e6 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/index.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/index.go @@ -98,3 +98,37 @@ type Indexers map[string]IndexFunc // Indices maps a name to an Index type Indices map[string]index + +type TypedIndexers[T any] map[string]TypedIndexFunc[T] +type TypedIndexFunc[T any] func(obj T) ([]string, error) +type TypedIndexer[T any] interface { + Indexer + + TypedIndex(indexName string, obj T) ([]T, error) + ByTypedIndex(indexName, indexedValue string) ([]T, error) + AddTypedIndexers(newIndexers TypedIndexers[T]) error +} + +// TypedIndexersToIndexers wraps several indexer functions which expect objects +// of a certain type so that they can be used in an [Indexer]. +// This is needed primarily for setting up [SharedIndexInformerOptions.Indexers]. +// When using one of the typed APIs for installing an indexer function +// the conversion is done automatically. +func TypedIndexersToIndexers[T any](indexers TypedIndexers[T]) Indexers { + untyped := make(Indexers, len(indexers)) + for i, indexer := range indexers { + untyped[i] = TypedIndexerFuncToIndexerFunc(indexer) + } + return untyped +} + +// TypedIndexersFuncToIndexerFunc wraps one indexer function which expect objects +// of a certain type so that they can be used in an [Indexer]. +// This is needed primarily for setting up [SharedIndexInformerOptions.Indexers]. +// When using one of the typed APIs for installing an indexer function +// the conversion is done automatically. +func TypedIndexerFuncToIndexerFunc[T any](indexer TypedIndexFunc[T]) IndexFunc { + return func(obj any) ([]string, error) { + return indexer(obj.(T)) + } +} diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/fifo_metrics.go b/constraint/vendor/k8s.io/client-go/tools/cache/informer_metrics.go similarity index 98% rename from constraint/vendor/k8s.io/client-go/tools/cache/fifo_metrics.go rename to constraint/vendor/k8s.io/client-go/tools/cache/informer_metrics.go index 7a6781724..e0d3b6e93 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/fifo_metrics.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/informer_metrics.go @@ -70,7 +70,7 @@ type storeMetrics struct { } // SetInformerMetricsProvider sets the metrics provider for all subsequently created -// FIFOs. Only the first call has an effect. +// informers. Only the first call has an effect. func SetInformerMetricsProvider(metricsProvider InformerMetricsProvider) { setInformerMetricsProviderOnce.Do(func() { globalInformerMetricsProvider = metricsProvider diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/mutation_cache.go b/constraint/vendor/k8s.io/client-go/tools/cache/mutation_cache.go index 6800a6250..e70b721a8 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/mutation_cache.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/mutation_cache.go @@ -25,7 +25,10 @@ import ( "k8s.io/klog/v2" "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" utilcache "k8s.io/apimachinery/pkg/util/cache" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" @@ -35,11 +38,19 @@ import ( // that can be used to provide a more current view of a requested object. It requires interpreting // resourceVersions for comparisons. // Implementations must be thread-safe. -// TODO find a way to layer this into an informer/lister +// OnAddOrupdate and OnDelete should be called from informer event handlers to increase +// the accuracy of the cache. type MutationCache interface { GetByKey(key string) (interface{}, bool, error) ByIndex(indexName, indexKey string) ([]interface{}, error) Mutation(interface{}) + OnAddOrUpdate(obj runtime.Object) + OnDelete(obj runtime.Object) + + // This interface is not meant to be implemented elsewhere. + // Marking it as internal enables future changes without + // triggering apidiff. + internal() } // ResourceVersionComparator is able to compare object versions. @@ -47,7 +58,28 @@ type ResourceVersionComparator interface { CompareResourceVersion(lhs, rhs runtime.Object) int } -// NewIntegerResourceVersionMutationCache returns a MutationCache that understands how to +// MutationCacheOptions configures the MutationCache returned by NewIntegerResourceVersionMutationCacheWithOptions. +type MutationCacheOptions struct { + // Indexer is used by ByIndex to look up objects. May be nil, in which case ByIndex returns an error. + Indexer Indexer + + // TTL controls how long an item remains in the mutation cache before it is removed. + // Zero means the default of 5 minutes. + TTL time.Duration + + // IncludeAdds makes the cache return objects even if they don't exist + // in the underlying store. This is only safe if your use of the cache + // can handle mutation entries remaining in the cache for up to TTL + // when mutations and deletes occur very closely in time. + IncludeAdds bool + + // MaxCacheSize limits how many mutated objects are tracked; the least + // recently used entries are evicted once the limit is reached. + // Zero means the default of 100. + MaxCacheSize int +} + +// NewIntegerResourceVersionMutationCacheWithOptions returns a MutationCache that understands how to // deal with objects that have a resource version that: // // - is an integer @@ -60,18 +92,55 @@ type ResourceVersionComparator interface { // If includeAdds is true, objects in the mutation cache will be returned even if they don't exist // in the underlying store. This is only safe if your use of the cache can handle mutation entries // remaining in the cache for up to ttl when mutations and deletes occur very closely in time. -func NewIntegerResourceVersionMutationCache(logger klog.Logger, backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache { +// +// Note that this also applies to objects updated by the caller, not just +// objects added by it. That's because the MutationCache may hold an updated +// object at a time when the underlying store already removed it because it was +// deleted in the apiserver after the update. To address this, the caller +// can call OnAddOrUpdate and OnDelete from informer event handlers. +// +// This informs the MutationCache about all changes observed by the store +// and enables it to remove a locally added or updated object immediately once +// it appears in the store, which prevents the "stale updated object" problem. +// +// This does not solve the "stale added object" problem reliably because +// the informer might never see the added object when the add is followed +// quickly by a delete. The caller has to handle stale added objects by +// checking whether they still exist once the TTL is over. +func NewIntegerResourceVersionMutationCacheWithOptions(logger klog.Logger, backingCache Store, options MutationCacheOptions) MutationCache { + var ( + maxCacheSize = 100 + ttl = 5 * time.Minute + ) + + if options.MaxCacheSize != 0 { + maxCacheSize = options.MaxCacheSize + } + if options.TTL != 0 { + ttl = options.TTL + } + return &mutationCache{ backingCache: backingCache, - indexer: indexer, - mutationCache: utilcache.NewLRUExpireCache(100), + indexer: options.Indexer, + mutationCache: utilcache.NewLRUExpireCache(maxCacheSize), comparator: etcdObjectVersioner{}, ttl: ttl, - includeAdds: includeAdds, + includeAdds: options.IncludeAdds, logger: logger, } } +// NewIntegerResourceVersionMutationCache is like NewIntegerResourceVersionMutationCacheWithOptions with a fixed cache size of 100. +func NewIntegerResourceVersionMutationCache(logger klog.Logger, backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache { + return NewIntegerResourceVersionMutationCacheWithOptions(logger, backingCache, MutationCacheOptions{ + TTL: ttl, + Indexer: indexer, + IncludeAdds: includeAdds, + MaxCacheSize: 100, + }) +} + // mutationCache doesn't guarantee that it returns values added via Mutation since they can page out and // since you can't distinguish between, "didn't observe create" and "was deleted after create", // if the key is missing from the backing cache, we always return it as missing @@ -108,11 +177,24 @@ func (c *mutationCache) GetByKey(key string) (interface{}, bool, error) { if !exists { return nil, false, nil } + // Don't return the tombstone. + if _, ok := obj.(*tombstone); ok { + return nil, false, nil + } } objRuntime, ok := obj.(runtime.Object) if !ok { return obj, true, nil } + // If the object is from the store, + // then this will remove the obsolete tombstone. + // + // The newer object can never be the tombstone + // because a) we don't get here if only the tombstone + // exists (early return above) and b) the store's + // object must be more recent than the tombstone + // (the tombstone was created by an earlier store + // deletion). return c.newerObject(key, objRuntime), true, nil } @@ -157,6 +239,9 @@ func (c *mutationCache) ByIndex(name string, indexKey string) ([]interface{}, er if keySet.Has(key.(string)) { continue } + if _, ok := updated.(*tombstone); ok { + continue + } elements, err := fn(updated) if err != nil { c.logger.V(4).Info("Unable to calculate an index entry for mutation cache entry", "key", key, "err", err) @@ -213,15 +298,114 @@ func (c *mutationCache) Mutation(obj interface{}) { if objRuntime, ok := obj.(runtime.Object); ok { if mutatedObj, exists := c.mutationCache.Get(key); exists { if mutatedObjRuntime, ok := mutatedObj.(runtime.Object); ok { - if c.comparator.CompareResourceVersion(objRuntime, mutatedObjRuntime) < 0 { + cmp := c.comparator.CompareResourceVersion(objRuntime, mutatedObjRuntime) + if cmp < 0 { return } + if t, ok := mutatedObj.(*tombstone); ok { + if cmp == 0 { + // Exactly this object instance is known to be deleted. + // Don't store it, keep the tombstone. + return + } + objMeta, err := meta.Accessor(obj) + if err == nil && t.GetUID() == objMeta.GetUID() { + // Some other revision of this object instance + // is known to be deleted. Also don't store it. + return + } + } } } } c.mutationCache.Add(key, obj, c.ttl) } +// OnAddOrUpdate can be called to informer the cache about an object added to +// the store or updated in in. If the object is as recent as the cached object +// or newer, the cached object gets removed because it is no longer +// needed. This keeps the cache smaller. +func (c *mutationCache) OnAddOrUpdate(obj runtime.Object) { + key, err := DeletionHandlingMetaNamespaceKeyFunc(obj) + if err != nil { + // this is a "nice to have", so failures shouldn't do anything weird + utilruntime.HandleErrorWithLogger(c.logger, err, "DeletionHandlingMetaNamespaceKeyFunc") + return + } + + c.lock.Lock() + defer c.lock.Unlock() + + if mutatedObj, exists := c.mutationCache.Get(key); exists { + if mutatedObj, ok := mutatedObj.(runtime.Object); ok { + // No need to compare the UID here: resource versions can be compared + // between different instances. If it's newer or equal, then the mutation + // cache is out-dated. + if c.comparator.CompareResourceVersion(obj, mutatedObj) >= 0 { + c.mutationCache.Remove(key) + } + } + } +} + +// OnDelete can be called to informer the cache about an object deleted in the store. +// If there is a cached object with the same UID or an older RV, it gets removed. +func (c *mutationCache) OnDelete(obj runtime.Object) { + objMeta, err := meta.Accessor(obj) + if err != nil { + return + } + + key, err := DeletionHandlingMetaNamespaceKeyFunc(obj) + if err != nil { + // this is a "nice to have", so failures shouldn't do anything weird + utilruntime.HandleErrorWithLogger(c.logger, err, "DeletionHandlingMetaNamespaceKeyFunc") + return + } + + c.lock.Lock() + defer c.lock.Unlock() + + if mutatedObj, exists := c.mutationCache.Get(key); exists { + if mutatedObj, ok := mutatedObj.(runtime.Object); ok { + mutatedObjMeta, err := meta.Accessor(mutatedObj) + if err != nil { + return + } + // If the deleted object is known to be more recent than the + // mutated one, then the mutated one must have been removed + // because resource versions are incremented by type, not by + // object instance. + // + // If the UID matches, then we can also be sure that it got + // removed. + // + // If neither of this is true, then the caller has added + // a mutated object that may or may not still exist. They + // have to check after the TTL. + if c.comparator.CompareResourceVersion(obj, mutatedObj) >= 0 || + mutatedObjMeta.GetUID() == objMeta.GetUID() { + c.mutationCache.Remove(key) + } else { + return + } + } + } + + // Store a tombstone object in the mutation cache. + // A future Mutation call is outdated if it has a RV + // which is lower or equal or has the same UID. + t := &tombstone{ + namespace: objMeta.GetNamespace(), + name: objMeta.GetName(), + uid: objMeta.GetUID(), + rv: objMeta.GetResourceVersion(), + } + c.mutationCache.Add(key, t, c.ttl) +} + +func (c *mutationCache) internal() {} + // etcdObjectVersioner implements versioning and extracting etcd node information // for objects that have an embedded ObjectMeta or ListMeta field. type etcdObjectVersioner struct{} @@ -262,3 +446,57 @@ func (a etcdObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int return 1 } + +// tombstone is a replacement for a deleted object. It has the same key as it +// and the ResourceVersion at which the deletion was detected. +// +// It implements GetName, GetNamespace, GetResourceVersion and GetUID and thus +// the code above can compare it against other, normal objects. The difference +// is that it never gets returned by ByIndex or GetByKey. +type tombstone struct { + namespace, name, rv string + uid types.UID +} + +var _ metav1.Object = &tombstone{} +var _ runtime.Object = &tombstone{} + +func (t *tombstone) DeepCopyObject() runtime.Object { + clone := *t + return &clone +} + +func (t *tombstone) GetObjectKind() schema.ObjectKind { panic("not implemented") } + +func (t *tombstone) GetNamespace() string { return t.namespace } +func (t *tombstone) SetNamespace(namespace string) { panic("not implemented") } +func (t *tombstone) GetName() string { return t.name } +func (t *tombstone) SetName(name string) { panic("not implemented") } +func (t *tombstone) GetGenerateName() string { panic("not implemented") } +func (t *tombstone) SetGenerateName(name string) { panic("not implemented") } +func (t *tombstone) GetUID() types.UID { return t.uid } +func (t *tombstone) SetUID(uid types.UID) { panic("not implemented") } +func (t *tombstone) GetResourceVersion() string { return t.rv } +func (t *tombstone) SetResourceVersion(version string) { panic("not implemented") } +func (t *tombstone) GetGeneration() int64 { panic("not implemented") } +func (t *tombstone) SetGeneration(generation int64) { panic("not implemented") } +func (t *tombstone) GetSelfLink() string { panic("not implemented") } +func (t *tombstone) SetSelfLink(selfLink string) { panic("not implemented") } +func (t *tombstone) GetCreationTimestamp() metav1.Time { panic("not implemented") } +func (t *tombstone) SetCreationTimestamp(timestamp metav1.Time) { panic("not implemented") } +func (t *tombstone) GetDeletionTimestamp() *metav1.Time { panic("not implemented") } +func (t *tombstone) SetDeletionTimestamp(timestamp *metav1.Time) { panic("not implemented") } +func (t *tombstone) GetDeletionGracePeriodSeconds() *int64 { panic("not implemented") } +func (t *tombstone) SetDeletionGracePeriodSeconds(*int64) { panic("not implemented") } +func (t *tombstone) GetLabels() map[string]string { panic("not implemented") } +func (t *tombstone) SetLabels(labels map[string]string) { panic("not implemented") } +func (t *tombstone) GetAnnotations() map[string]string { panic("not implemented") } +func (t *tombstone) SetAnnotations(annotations map[string]string) { panic("not implemented") } +func (t *tombstone) GetFinalizers() []string { panic("not implemented") } +func (t *tombstone) SetFinalizers(finalizers []string) { panic("not implemented") } +func (t *tombstone) GetOwnerReferences() []metav1.OwnerReference { panic("not implemented") } +func (t *tombstone) SetOwnerReferences([]metav1.OwnerReference) { panic("not implemented") } +func (t *tombstone) GetManagedFields() []metav1.ManagedFieldsEntry { panic("not implemented") } +func (t *tombstone) SetManagedFields(managedFields []metav1.ManagedFieldsEntry) { + panic("not implemented") +} diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/reflector.go b/constraint/vendor/k8s.io/client-go/tools/cache/reflector.go index a0e3a701c..82de01f9a 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/reflector.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/reflector.go @@ -742,7 +742,7 @@ func (r *Reflector) list(ctx context.Context) error { case <-listCh: } - initTrace.Step("Objects listed", trace.Field{Key: "error", Value: err}) + initTrace.Step("Objects listed", trace.Field{Key: "error", Value: err}, trace.Field{Key: "count", Value: meta.LenList(list)}) if err != nil { return fmt.Errorf("failed to list %v: %w", r.typeDescription, err) } diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/shared_informer.go b/constraint/vendor/k8s.io/client-go/tools/cache/shared_informer.go index 4cec4283f..c259cdd9a 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/shared_informer.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/shared_informer.go @@ -28,6 +28,7 @@ import ( "time" "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" @@ -177,6 +178,15 @@ type SharedInformer interface { // RemoveEventHandler removes a formerly added event handler given by // its registration handle. // This function is guaranteed to be idempotent, and thread-safe. + // + // Note: RemoveEventHandler is asynchronous. It stops queueing new events + // but does not wait for already-queued events to finish executing. + // Goroutines processing the remaining events may still be running and + // invoking callbacks after this function returns. + // + // If the caller needs to wait for all handlers to finish executing (for + // example, to safely close channels or release resources used by the handler), + // they should use [ShutDownEventHandler]. RemoveEventHandler(handle ResourceEventHandlerRegistration) error // GetStore returns the informer's local cache as a Store. GetStore() Store @@ -287,6 +297,118 @@ type SharedIndexInformer interface { GetIndexer() Indexer } +// TypedSharedIndexInformer adds type-safe variants for non-type-safe methods +// in SharedIndexInformer. No type casts are needed when using those variants. +type TypedSharedIndexInformer[T Object] interface { + SharedIndexInformer + + // AddTypedEventHandler is a type-safe replacement for + // SharedIndexInformer.AddEventHandlerWithOptions + // and SharedIndexInformer.AddEventHandler. + // + // Without options, it uses the same defaults as AddEventHandler + // or AddEventHandlerWithOptions with empty HandlerOptions. + // Passing one instance corresponds to AddEventHandlerWithOptions. + // Passing more than one is invalid and returns an error. + AddTypedEventHandler(handler TypedResourceEventHandler[T], options ...HandlerOptions) (ResourceEventHandlerRegistration, error) + AddTypedIndexers(indexers TypedIndexers[T]) error + GetTypedIndexer() TypedIndexer[T] +} + +func NewTypedSharedIndexInformer[T Object](informer SharedIndexInformer) TypedSharedIndexInformer[T] { + return &typedSharedIndexInformer[T]{SharedIndexInformer: informer} +} + +type typedSharedIndexInformer[T Object] struct { + SharedIndexInformer +} + +func (s typedSharedIndexInformer[T]) AddTypedEventHandler(handler TypedResourceEventHandler[T], options ...HandlerOptions) (ResourceEventHandlerRegistration, error) { + var o HandlerOptions + switch len(options) { + case 0: + case 1: + o = options[0] + default: + return nil, fmt.Errorf("at most one HandlerOptions may be passed, got %d", len(options)) + } + return s.AddEventHandlerWithOptions(&typedResourceEventHandler[T]{handler}, o) +} + +func (s typedSharedIndexInformer[T]) AddTypedIndexers(indexers TypedIndexers[T]) error { + return s.AddIndexers(TypedIndexersToIndexers(indexers)) +} + +func (s typedSharedIndexInformer[T]) GetTypedIndexer() TypedIndexer[T] { + return &typedIndexer[T]{s.GetIndexer()} +} + +// typedResourceEventHandler implements the untyped ResourceEventHandler interface +// by invoking the methods of a TypedResourceEventHandler instance. +type typedResourceEventHandler[T Object] struct { + handler TypedResourceEventHandler[T] +} + +var _ ResourceEventHandler = &typedResourceEventHandler[*metav1.ObjectMeta]{} + +func (h *typedResourceEventHandler[T]) OnAdd(obj any, isInitialList bool) { + h.handler.OnAdd(obj.(T), isInitialList) +} + +func (h *typedResourceEventHandler[T]) OnUpdate(oldObj, newObj any) { + h.handler.OnUpdate(oldObj.(T), newObj.(T)) +} + +func (h *typedResourceEventHandler[T]) OnDelete(obj any) { + if tomb, ok := obj.(DeletedFinalStateUnknown); ok { + if tomb.Obj == nil { + h.handler.OnDelete(DeletedObject[T]{FinalStateUnknown: &tomb}) + return + } + h.handler.OnDelete(DeletedObject[T]{OptionalObj: tomb.Obj.(T), FinalStateUnknown: &tomb}) + return + } + h.handler.OnDelete(DeletedObject[T]{OptionalObj: obj.(T)}) +} + +type typedIndexer[T any] struct { + Indexer +} + +func (i typedIndexer[T]) TypedIndex(indexName string, obj T) ([]T, error) { + untyped, err := i.Index(indexName, obj) + if err != nil { + return nil, err + } + typed := make([]T, len(untyped)) + for i, obj := range untyped { + typed[i] = obj.(T) + } + return typed, nil +} + +func (i typedIndexer[T]) ByTypedIndex(indexName, indexedValue string) ([]T, error) { + untyped, err := i.ByIndex(indexName, indexedValue) + if err != nil { + return nil, err + } + typed := make([]T, len(untyped)) + for i, obj := range untyped { + typed[i] = obj.(T) + } + return typed, nil +} + +func (i typedIndexer[T]) AddTypedIndexers(newIndexers TypedIndexers[T]) error { + untyped := make(Indexers, len(newIndexers)) + for i, indexer := range newIndexers { + untyped[i] = func(obj any) ([]string, error) { + return indexer(obj.(T)) + } + } + return i.AddIndexers(untyped) +} + // NewSharedInformer creates a new instance for the ListerWatcher. See NewSharedIndexInformerWithOptions for full details. func NewSharedInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration) SharedInformer { return NewSharedIndexInformer(lw, exampleObject, defaultEventHandlerResyncPeriod, Indexers{}) @@ -1014,6 +1136,24 @@ func (s *sharedIndexInformer) RemoveEventHandler(handle ResourceEventHandlerRegi return s.processor.removeListener(handle) } +// ShutDownEventHandler removes the event handler and blocks until it has fully +// stopped processing events. +// +// Like RemoveEventHandler, it is idempotent and thread-safe. However, it MUST NOT +// be called from within the event handler's own callbacks, as that will result +// in a deadlock. +func ShutDownEventHandler(informer SharedInformer, handle ResourceEventHandlerRegistration) error { + if err := informer.RemoveEventHandler(handle); err != nil { + return err + } + if s, ok := handle.(interface{ ShutdownChan() <-chan struct{} }); ok { + <-s.ShutdownChan() + } else { + return fmt.Errorf("handle does not support ShutdownChan()") + } + return nil +} + // sharedProcessor has a collection of processorListener and can // distribute a notification object to its listeners. There are two // kinds of distribute operations. The sync distributions go to a @@ -1086,6 +1226,8 @@ func (p *sharedProcessor) removeListener(handle ResourceEventHandlerRegistration if p.listenersStarted { close(listener.addCh) + } else { + close(listener.runFinished) } return nil @@ -1209,10 +1351,11 @@ func (p *sharedProcessor) resyncCheckPeriodChanged(logger klog.Logger, resyncChe // processorListener also keeps track of the adjusted requested resync // period of the listener. type processorListener struct { - logger klog.Logger - nextCh chan interface{} - addCh chan interface{} - done chan struct{} + logger klog.Logger + nextCh chan interface{} + addCh chan interface{} + done chan struct{} + runFinished chan struct{} handler ResourceEventHandler handlerName string @@ -1265,6 +1408,10 @@ func (p *processorListener) HasSyncedChecker() DoneChecker { return p.syncTracker } +func (p *processorListener) ShutdownChan() <-chan struct{} { + return p.runFinished +} + func newProcessListener(logger klog.Logger, handler ResourceEventHandler, requestedResyncPeriod, resyncPeriod time.Duration, now time.Time, bufferSize int, hasSynced DoneChecker) *processorListener { handlerName := nameForHandler(handler) ret := &processorListener{ @@ -1272,6 +1419,7 @@ func newProcessListener(logger klog.Logger, handler ResourceEventHandler, reques nextCh: make(chan interface{}), addCh: make(chan interface{}), done: make(chan struct{}), + runFinished: make(chan struct{}), upstreamHasSynced: hasSynced, handler: handler, handlerName: handlerName, @@ -1328,6 +1476,7 @@ func (p *processorListener) pop() { } func (p *processorListener) run() { + defer close(p.runFinished) // this call blocks until the channel is closed. When a panic happens during the notification // we will catch it, **the offending item will be skipped!**, and after a short delay (one second) // the next notification will be attempted. This is usually better than the alternative of never diff --git a/constraint/vendor/k8s.io/client-go/tools/cache/store.go b/constraint/vendor/k8s.io/client-go/tools/cache/store.go index 261ed60d9..76cb70c56 100644 --- a/constraint/vendor/k8s.io/client-go/tools/cache/store.go +++ b/constraint/vendor/k8s.io/client-go/tools/cache/store.go @@ -402,6 +402,9 @@ func WithTransformer(transformer TransformFunc) StoreOption { func WithStoreMetrics(identifier InformerNameAndResource, metrics InformerMetricsProvider) StoreOption { return func(c *cache) { c.identifier = identifier + if metrics == nil { + metrics = globalInformerMetricsProvider + } c.metrics = metrics } } diff --git a/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go b/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go index 3ccdebc1c..b5a686a4c 100644 --- a/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go +++ b/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go @@ -17,5 +17,6 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/client-go/tools/clientcmd/api // +k8s:deepcopy-gen=package // +k8s:defaulter-gen=Kind +// +k8s:validation-gen=false package v1 diff --git a/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go b/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go index ef1e9b8eb..f4a48d071 100644 --- a/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go +++ b/constraint/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go @@ -229,8 +229,7 @@ func Convert_api_AuthInfo_To_v1_AuthInfo(in *api.AuthInfo, out *AuthInfo, s conv } func autoConvert_v1_AuthProviderConfig_To_api_AuthProviderConfig(in *AuthProviderConfig, out *api.AuthProviderConfig, s conversion.Scope) error { - out.Name = in.Name - out.Config = *(*map[string]string)(unsafe.Pointer(&in.Config)) + *out = *(*api.AuthProviderConfig)(unsafe.Pointer(in)) return nil } @@ -240,8 +239,7 @@ func Convert_v1_AuthProviderConfig_To_api_AuthProviderConfig(in *AuthProviderCon } func autoConvert_api_AuthProviderConfig_To_v1_AuthProviderConfig(in *api.AuthProviderConfig, out *AuthProviderConfig, s conversion.Scope) error { - out.Name = in.Name - out.Config = *(*map[string]string)(unsafe.Pointer(&in.Config)) + *out = *(*AuthProviderConfig)(unsafe.Pointer(in)) return nil } @@ -411,8 +409,7 @@ func Convert_api_ExecConfig_To_v1_ExecConfig(in *api.ExecConfig, out *ExecConfig } func autoConvert_v1_ExecEnvVar_To_api_ExecEnvVar(in *ExecEnvVar, out *api.ExecEnvVar, s conversion.Scope) error { - out.Name = in.Name - out.Value = in.Value + *out = *(*api.ExecEnvVar)(unsafe.Pointer(in)) return nil } @@ -422,8 +419,7 @@ func Convert_v1_ExecEnvVar_To_api_ExecEnvVar(in *ExecEnvVar, out *api.ExecEnvVar } func autoConvert_api_ExecEnvVar_To_v1_ExecEnvVar(in *api.ExecEnvVar, out *ExecEnvVar, s conversion.Scope) error { - out.Name = in.Name - out.Value = in.Value + *out = *(*ExecEnvVar)(unsafe.Pointer(in)) return nil } diff --git a/constraint/vendor/k8s.io/client-go/tools/clientcmd/loader.go b/constraint/vendor/k8s.io/client-go/tools/clientcmd/loader.go index d1d0a8295..e6e35a8ab 100644 --- a/constraint/vendor/k8s.io/client-go/tools/clientcmd/loader.go +++ b/constraint/vendor/k8s.io/client-go/tools/clientcmd/loader.go @@ -300,7 +300,8 @@ func (rules *ClientConfigLoadingRules) Migrate() error { return err } - if sourceInfo, err := os.Stat(source); err != nil { + sourceInfo, err := os.Stat(source) + if err != nil { if os.IsNotExist(err) || os.IsPermission(err) { // if the source file doesn't exist or we can't access it, there's no work to do. continue @@ -316,8 +317,8 @@ func (rules *ClientConfigLoadingRules) Migrate() error { if err != nil { return err } - // destination is created with mode 0666 before umask - err = os.WriteFile(destination, data, 0666) + // destination created with source perm, but never executable, and subject to umask + err = os.WriteFile(destination, data, sourceInfo.Mode().Perm()&0666) if err != nil { return err } @@ -641,7 +642,7 @@ func RelativizePathWithNoBacksteps(refs []*string, base string) error { } // if we have a backstep, don't mess with the path - if strings.HasPrefix(rel, "../") { + if strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { if filepath.IsAbs(*ref) { continue } diff --git a/constraint/vendor/k8s.io/client-go/tools/leaderelection/OWNERS b/constraint/vendor/k8s.io/client-go/tools/leaderelection/OWNERS index 70787f2b5..0aa6fd9a4 100644 --- a/constraint/vendor/k8s.io/client-go/tools/leaderelection/OWNERS +++ b/constraint/vendor/k8s.io/client-go/tools/leaderelection/OWNERS @@ -1,13 +1,12 @@ # See the OWNERS docs at https://go.k8s.io/owners approvers: - - mikedanese - jefftree reviewers: - wojtek-t - deads2k - - mikedanese - ingvagabund - jefftree emeritus_approvers: - timothysc + - mikedanese diff --git a/constraint/vendor/k8s.io/client-go/tools/leaderelection/leaderelection.go b/constraint/vendor/k8s.io/client-go/tools/leaderelection/leaderelection.go index 00798d82a..b4e70a6c7 100644 --- a/constraint/vendor/k8s.io/client-go/tools/leaderelection/leaderelection.go +++ b/constraint/vendor/k8s.io/client-go/tools/leaderelection/leaderelection.go @@ -312,12 +312,20 @@ func (le *LeaderElector) renew(ctx context.Context) { } // release attempts to release the leader lease if we have acquired it. +// It retries on conflict, which may occur if the context cancellation +// races with an inflight renew() operation. The client will see a ctx +// cancellation error while the apiserver completes the update and bumps +// the resource version. func (le *LeaderElector) release(logger klog.Logger) bool { - ctx := context.Background() + ctx := klog.NewContext(context.Background(), logger) timeoutCtx, timeoutCancel := context.WithTimeout(ctx, le.config.RenewDeadline) defer timeoutCancel() - // update the resourceVersion of lease - oldLeaderElectionRecord, _, err := le.config.Lock.Get(timeoutCtx) + return le.tryRelease(timeoutCtx) +} + +func (le *LeaderElector) tryRelease(ctx context.Context) bool { + logger := klog.FromContext(ctx) + oldLeaderElectionRecord, _, err := le.config.Lock.Get(ctx) if err != nil { if !errors.IsNotFound(err) { logger.Error(err, "error retrieving resource lock", "lock", le.config.Lock.Describe()) @@ -337,7 +345,11 @@ func (le *LeaderElector) release(logger klog.Logger) bool { RenewTime: now, AcquireTime: now, } - if err := le.config.Lock.Update(timeoutCtx, leaderElectionRecord); err != nil { + if err := le.config.Lock.Update(ctx, leaderElectionRecord); err != nil { + if errors.IsConflict(err) { + logger.V(4).Info("Conflict when releasing lease, retrying", "lock", le.config.Lock.Describe()) + return le.tryRelease(ctx) + } logger.Error(err, "Failed to release lease", "lock", le.config.Lock.Describe()) return false } diff --git a/constraint/vendor/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go b/constraint/vendor/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go index 5ee1dcbb5..e2ba21d37 100644 --- a/constraint/vendor/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go +++ b/constraint/vendor/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go @@ -25,10 +25,14 @@ import ( ) const ( + // Deprecated: UnknownLeader is only used by MultiLock, which is deprecated. UnknownLeader = "leaderelection.k8s.io/unknown" ) -// MultiLock is used for lock's migration +// Deprecated: MultiLock was used to facilitate migration from non-lease +// based leader election to lease-based leader election. Support for +// non-lease locks was removed in Kubernetes 1.28, making MultiLock +// non-functional. Use LeaseLock directly instead. type MultiLock struct { Primary Interface Secondary Interface @@ -99,6 +103,7 @@ func (ml *MultiLock) Identity() string { return ml.Primary.Identity() } +// Deprecated: ConcatRawRecord is only used by MultiLock, which is deprecated. func ConcatRawRecord(primaryRaw, secondaryRaw []byte) []byte { return bytes.Join([][]byte{primaryRaw, secondaryRaw}, []byte(",")) } diff --git a/constraint/vendor/k8s.io/client-go/tools/metrics/metrics.go b/constraint/vendor/k8s.io/client-go/tools/metrics/metrics.go index 2f626475b..bac15ae14 100644 --- a/constraint/vendor/k8s.io/client-go/tools/metrics/metrics.go +++ b/constraint/vendor/k8s.io/client-go/tools/metrics/metrics.go @@ -25,7 +25,37 @@ import ( "time" ) -var registerMetrics sync.Once +var ( + registerMetrics sync.Once + ensureRegisteredOnce sync.Once + // ensureRegisteredFn, if set via RegisterOpts.RegisterFn, is invoked + // exactly once before any rest client is constructed. Adapter packages + // (e.g. k8s.io/component-base/metrics/prometheus/restclient) install + // this callback in their init() so that the actual registration with + // legacyregistry — and the metric Create() that reads + // feature-gate-derived options like NativeHistograms — happens at + // runtime rather than at init() time. See EnsureRegistered for the + // caller-side contract. + ensureRegisteredFn func() +) + +// EnsureRegistered invokes the callback installed via RegisterOpts.RegisterFn (if +// any) exactly once. Callers should treat it as idempotent; subsequent calls are +// effectively free. +// +// New public constructors or entry points for packages in client-go that create +// a REST client, HTTP transport, or credential provider should invoke EnsureRegistered() +// at the very beginning of the function. Adapter Observe methods +// also call EnsureRegistered(), so no observations are lost if a constructor +// forgets to invoke it, but if invoked, the entrypoint call shifts registration from +// "first-observation" to "first client construction", meaning the metric +// series is visible to Promteheus scrapes from process startup rather than +// appearing only after the first request. +func EnsureRegistered() { + if ensureRegisteredFn != nil { + ensureRegisteredOnce.Do(ensureRegisteredFn) + } +} // DurationMetric is a measurement of some amount of time. type DurationMetric interface { @@ -163,6 +193,12 @@ type RegisterOpts struct { TransportCAReloads TransportCAReloadsMetric TransportCertRotationGCCalls TransportCertRotationGCCallsMetric TransportCacheGCCalls TransportCacheGCCallsMetric + + // RegisterFn, if non-nil, is invoked exactly once by EnsureRegistered(). + // before the first rest client is constructed. Adapters use this to defer + // registrations that depend on runtime state (eg., feature gates read my metric + // Create() without changing the import side contract of the adapter package.) + RegisterFn func() } // Register registers metrics for the rest client to use. This can @@ -197,7 +233,7 @@ func Register(opts RegisterOpts) { ExecPluginCalls = opts.ExecPluginCalls } if opts.ExecPluginPolicyCalls != nil { - ExecPluginCalls = opts.ExecPluginCalls + ExecPluginPolicyCalls = opts.ExecPluginPolicyCalls } if opts.RequestRetry != nil { RequestRetry = opts.RequestRetry @@ -217,6 +253,9 @@ func Register(opts RegisterOpts) { if opts.TransportCacheGCCalls != nil { TransportCacheGCCalls = opts.TransportCacheGCCalls } + if opts.RegisterFn != nil { + ensureRegisteredFn = opts.RegisterFn + } }) } diff --git a/constraint/vendor/k8s.io/client-go/tools/pager/pager.go b/constraint/vendor/k8s.io/client-go/tools/pager/pager.go index 3c77cc37f..500923e28 100644 --- a/constraint/vendor/k8s.io/client-go/tools/pager/pager.go +++ b/constraint/vendor/k8s.io/client-go/tools/pager/pager.go @@ -219,7 +219,7 @@ func (p *ListPager) eachListChunkBuffered(ctx context.Context, options metav1.Li chunkC := make(chan runtime.Object, p.PageBufferSize) bgResultC := make(chan error, 1) go func() { - defer utilruntime.HandleCrash() + defer utilruntime.HandleCrashWithContext(ctx) var err error defer func() { diff --git a/constraint/vendor/k8s.io/client-go/transport/OWNERS b/constraint/vendor/k8s.io/client-go/transport/OWNERS index 34adee5ec..17c96a91e 100644 --- a/constraint/vendor/k8s.io/client-go/transport/OWNERS +++ b/constraint/vendor/k8s.io/client-go/transport/OWNERS @@ -5,4 +5,3 @@ reviewers: - wojtek-t - deads2k - liggitt - - caesarxuchao diff --git a/constraint/vendor/k8s.io/client-go/transport/transport.go b/constraint/vendor/k8s.io/client-go/transport/transport.go index be97b7621..c4595da30 100644 --- a/constraint/vendor/k8s.io/client-go/transport/transport.go +++ b/constraint/vendor/k8s.io/client-go/transport/transport.go @@ -29,12 +29,14 @@ import ( utilnet "k8s.io/apimachinery/pkg/util/net" clientgofeaturegate "k8s.io/client-go/features" + "k8s.io/client-go/tools/metrics" "k8s.io/klog/v2" ) // New returns an http.RoundTripper that will provide the authentication // or transport level security defined by the provided Config. func New(config *Config) (http.RoundTripper, error) { + metrics.EnsureRegistered() // Set transport level security if config.Transport != nil && (config.HasCA() || config.HasCertAuth() || config.HasCertCallback() || config.TLS.Insecure) { return nil, fmt.Errorf("using a custom transport with TLS certificate options or the insecure flag is not allowed") diff --git a/constraint/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go b/constraint/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go index 72c0124a0..d46c429e7 100644 --- a/constraint/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go +++ b/constraint/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go @@ -66,12 +66,19 @@ type TransformFunc func(interface{}) (interface{}, error) // it is guarded by an environmental variable. // we cannot manipulate the environmental variable because // it will affect other tests in this package. +// +// The identity string can be left empty if the logger in the context already +// identifies what is being watched. func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity string, lastSyncedResourceVersion string, listFn ListFunc[T], listItemTransformFunc TransformFunc, listOptions metav1.ListOptions, retrieveItemsFn RetrieveItemsFunc[U]) { + logger := klog.FromContext(ctx) + if identity != "" { + logger = klog.LoggerWithName(logger, identity) + } if !canFormAdditionalListCall(lastSyncedResourceVersion, listOptions) { - klog.V(4).Infof("data consistency check for %s is enabled but the parameters (RV, ListOptions) doesn't allow for creating a valid LIST request. Skipping the data consistency check.", identity) + logger.V(4).Info("Data consistency check is enabled but the parameters (RV, ListOptions) doesn't allow for creating a valid LIST request. Skipping the data consistency check.") return } - klog.Warningf("data consistency check for %s is enabled, this will result in an additional call to the API server.", identity) + logger.Info("Warning: data consistency check is enabled, this will result in an additional call to the API server.") retrievedItems := toMetaObjectSliceOrDie(retrieveItemsFn()) listOptions = prepareListCallOptions(lastSyncedResourceVersion, listOptions, len(retrievedItems)) @@ -82,13 +89,13 @@ func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity // the consistency check will only be enabled in the CI // and LIST calls in general will be retired by the client-go library // if we fail simply log and retry - klog.Errorf("failed to list data from the server, retrying until stopCh is closed, err: %v", err) + logger.Info("Failed to list data from the server, retrying until context is canceled", "err", err) return false, nil } return true, nil }) if err != nil { - klog.Errorf("failed to list data from the server, the data consistency check for %s won't be performed, stopCh was closed, err: %v", identity, err) + logger.Error(err, "Failed to list data from the server, the data consistency check won't be performed, stopCh was closed") return } @@ -111,7 +118,7 @@ func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity sort.Sort(byUID(retrievedItems)) if !reflect.DeepEqual(listItems, retrievedItems) { - klog.Infof("previously received data for %s is different than received by the standard list api call against etcd, diff: %v", identity, diff.Diff(listItems, retrievedItems)) + logger.Info("Previously received data is different than received by the standard list api call against etcd", "diff", diff.Diff(listItems, retrievedItems)) msg := fmt.Sprintf("data inconsistency detected for %s, panicking!", identity) panic(msg) } diff --git a/constraint/vendor/k8s.io/client-go/util/retry/OWNERS b/constraint/vendor/k8s.io/client-go/util/retry/OWNERS deleted file mode 100644 index 75736b5aa..000000000 --- a/constraint/vendor/k8s.io/client-go/util/retry/OWNERS +++ /dev/null @@ -1,4 +0,0 @@ -# See the OWNERS docs at https://go.k8s.io/owners - -reviewers: - - caesarxuchao diff --git a/constraint/vendor/k8s.io/client-go/util/retry/util.go b/constraint/vendor/k8s.io/client-go/util/retry/util.go index 57d3cd49c..fd2a959ec 100644 --- a/constraint/vendor/k8s.io/client-go/util/retry/util.go +++ b/constraint/vendor/k8s.io/client-go/util/retry/util.go @@ -59,7 +59,7 @@ func OnError(backoff wait.Backoff, retriable func(error) bool, fn func() error) return false, err } }) - if wait.Interrupted(err) { + if wait.Interrupted(err) && lastErr != nil { err = lastErr } return err diff --git a/constraint/vendor/k8s.io/component-base/metrics/api/v1/zz_generated.model_name.go b/constraint/vendor/k8s.io/component-base/metrics/api/v1/zz_generated.model_name.go new file mode 100644 index 000000000..e80eef97c --- /dev/null +++ b/constraint/vendor/k8s.io/component-base/metrics/api/v1/zz_generated.model_name.go @@ -0,0 +1,27 @@ +//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 v1 + +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in MetricsConfiguration) OpenAPIModelName() string { + return "io.k8s.component-base.metrics.api.v1.MetricsConfiguration" +} diff --git a/constraint/vendor/k8s.io/component-base/tracing/utils.go b/constraint/vendor/k8s.io/component-base/tracing/utils.go index dde7a5b28..bd0be0dcf 100644 --- a/constraint/vendor/k8s.io/component-base/tracing/utils.go +++ b/constraint/vendor/k8s.io/component-base/tracing/utils.go @@ -21,16 +21,16 @@ import ( "net/http" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" - semconv "go.opentelemetry.io/otel/semconv/v1.17.0" oteltrace "go.opentelemetry.io/otel/trace" noopoteltrace "go.opentelemetry.io/otel/trace/noop" "k8s.io/client-go/transport" - "k8s.io/component-base/tracing/api/v1" + v1 "k8s.io/component-base/tracing/api/v1" ) // TracerProvider is an OpenTelemetry TracerProvider which can be shut down @@ -101,7 +101,7 @@ func WithTracing(handler http.Handler, tp oteltrace.TracerProvider, spanName str // Add the http.target attribute to the otelhttp span // Workaround for https://github.com/open-telemetry/opentelemetry-go-contrib/issues/3743 if r.URL != nil { - oteltrace.SpanFromContext(r.Context()).SetAttributes(semconv.HTTPTarget(r.URL.RequestURI())) + oteltrace.SpanFromContext(r.Context()).SetAttributes(attribute.Key("http.target").String(r.URL.RequestURI())) } handler.ServeHTTP(w, r) }) diff --git a/constraint/vendor/k8s.io/component-base/version/base.go b/constraint/vendor/k8s.io/component-base/version/base.go index 453b63d82..6394bc8cf 100644 --- a/constraint/vendor/k8s.io/component-base/version/base.go +++ b/constraint/vendor/k8s.io/component-base/version/base.go @@ -60,5 +60,5 @@ const ( // DefaultKubeBinaryVersion is the hard coded k8 binary version based on the latest K8s release. // It is supposed to be consistent with gitMajor and gitMinor, except for local tests, where gitMajor and gitMinor are "". // Should update for each minor release! - DefaultKubeBinaryVersion = "1.36" + DefaultKubeBinaryVersion = "1.37" ) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go index 7393bacf7..5d8ee9aa4 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go @@ -24,7 +24,7 @@ import ( // DeterministicMarshal calls the jsonv2 library with the deterministic // flag in order to have stable marshaling. func DeterministicMarshal(in any) ([]byte, error) { - return jsonv2.MarshalOptions{Deterministic: true}.Marshal(jsonv2.EncodeOptions{}, in) + return jsonv2.Marshal(in, jsonv2.Deterministic(true)) } // JSONRefFromMap populates a json reference object if the map v contains a $ref key. diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/README.md b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/README.md index 0349adf69..937c39800 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/README.md +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/README.md @@ -7,17 +7,24 @@ This module hosts an experimental implementation of v2 `encoding/json`. The API is unstable and breaking changes will regularly be made. Do not depend on this in publicly available modules. +Any commits that make breaking API or behavior changes will be marked +with the string "WARNING: " near the top of the commit message. +It is your responsibility to inspect the list of commit changes +when upgrading the module. Not all breaking changes will lead to build failures. + +A [proposal to include this module in Go as `encoding/json/v2` and `encoding/json/jsontext`](https://github.com/golang/go/issues/71497) has been started on the Go Github project on 2025-01-30. Please provide your feedback there. + ## Goals and objectives * **Mostly backwards compatible:** If possible, v2 should aim to be _mostly_ compatible with v1 in terms of both API and default behavior to ease migration. For example, the `Marshal` and `Unmarshal` functions are the most widely used declarations in the v1 package. It seems sensible for equivalent functionality -in v2 to be named the same and have the same signature. +in v2 to be named the same and have a mostly compatible signature. Behaviorally, we should aim for 95% to 99% backwards compatibility. We do not aim for 100% compatibility since we want the freedom to break certain behaviors that are now considered to have been a mistake. -We may provide options that can bring the v2 implementation to 100% compatibility, +Options exist that can bring the v2 implementation to 100% compatibility, but it will not be the default. * **More flexible:** There is a @@ -96,26 +103,32 @@ Syntax deals with the structural representation of JSON (as specified in Semantics deals with the meaning of syntactic data as usable application data. The `Encoder` and `Decoder` types are streaming tokenizers concerned with the -packing or parsing of JSON data. They operate on `Token` and `RawValue` types +packing or parsing of JSON data. They operate on `Token` and `Value` types which represent the common data structures that are representable in JSON. `Encoder` and `Decoder` do not aim to provide any interpretation of the data. -Functions like `Marshal`, `MarshalFull`, `MarshalNext`, `Unmarshal`, -`UnmarshalFull`, and `UnmarshalNext` provide semantic meaning by correlating +Functions like `Marshal`, `MarshalWrite`, `MarshalEncode`, `Unmarshal`, +`UnmarshalRead`, and `UnmarshalDecode` provide semantic meaning by correlating any arbitrary Go type with some JSON representation of that type (as stored in data types like `[]byte`, `io.Writer`, `io.Reader`, `Encoder`, or `Decoder`). ![API overview](api.png) -This diagram provides a high-level overview of the v2 `json` package. +This diagram provides a high-level overview of the v2 `json` and `jsontext` packages. Purple blocks represent types, while blue blocks represent functions or methods. The arrows and their direction represent the approximate flow of data. The bottom half of the diagram contains functionality that is only concerned -with syntax, while the upper half contains functionality that assigns -semantic meaning to syntactic data handled by the bottom half. +with syntax (implemented by the `jsontext` package), +while the upper half contains functionality that assigns +semantic meaning to syntactic data handled by the bottom half +(as implemented by the v2 `json` package). In contrast to v1 `encoding/json`, options are represented as separate types rather than being setter methods on the `Encoder` or `Decoder` types. +Some options affects JSON serialization at the syntactic layer, +while others affect it at the semantic layer. +Some options only affect JSON when decoding, +while others affect JSON while encoding. ## Behavior changes @@ -128,194 +141,35 @@ This table shows an overview of the changes: | v1 | v2 | Details | | -- | -- | ------- | -| JSON object members are unmarshaled into a Go struct using a **case-insensitive name match**. | JSON object members are unmarshaled into a Go struct using a **case-sensitive name match**. | [CaseSensitivity](/diff_test.go#:~:text=TestCaseSensitivity) | -| When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value is an empty Go value**, which is defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string. | When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value would encode as an empty JSON value**, which is defined as a JSON null, or an empty JSON string, object, or array. | [OmitEmptyOption](/diff_test.go#:~:text=TestOmitEmptyOption) | -| The `string` option **does affect** Go bools. | The `string` option **does not affect** Go bools. | [StringOption](/diff_test.go#:~:text=TestStringOption) | -| The `string` option **does not recursively affect** sub-values of the Go field value. | The `string` option **does recursively affect** sub-values of the Go field value. | [StringOption](/diff_test.go#:~:text=TestStringOption) | -| The `string` option **sometimes accepts** a JSON null escaped within a JSON string. | The `string` option **never accepts** a JSON null escaped within a JSON string. | [StringOption](/diff_test.go#:~:text=TestStringOption) | -| A nil Go slice is marshaled as a **JSON null**. | A nil Go slice is marshaled as an **empty JSON array**. | [NilSlicesAndMaps](/diff_test.go#:~:text=TestNilSlicesAndMaps) | -| A nil Go map is marshaled as a **JSON null**. | A nil Go map is marshaled as an **empty JSON object**. | [NilSlicesAndMaps](/diff_test.go#:~:text=TestNilSlicesAndMaps) | -| A Go array may be unmarshaled from a **JSON array of any length**. | A Go array must be unmarshaled from a **JSON array of the same length**. | [Arrays](/diff_test.go#:~:text=Arrays) | -| A Go byte array is represented as a **JSON array of JSON numbers**. | A Go byte array is represented as a **Base64-encoded JSON string**. | [ByteArrays](/diff_test.go#:~:text=TestByteArrays) | -| `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **inconsistently called**. | `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **consistently called**. | [PointerReceiver](/diff_test.go#:~:text=TestPointerReceiver) | -| A Go map is marshaled in a **deterministic order**. | A Go map is marshaled in a **non-deterministic order**. | [MapDeterminism](/diff_test.go#:~:text=TestMapDeterminism) | -| JSON strings are encoded **with HTML-specific characters being escaped**. | JSON strings are encoded **without any characters being escaped** (unless necessary). | [EscapeHTML](/diff_test.go#:~:text=TestEscapeHTML) | -| When marshaling, invalid UTF-8 within a Go string **are silently replaced**. | When marshaling, invalid UTF-8 within a Go string **results in an error**. | [InvalidUTF8](/diff_test.go#:~:text=TestInvalidUTF8) | -| When unmarshaling, invalid UTF-8 within a JSON string **are silently replaced**. | When unmarshaling, invalid UTF-8 within a JSON string **results in an error**. | [InvalidUTF8](/diff_test.go#:~:text=TestInvalidUTF8) | -| When marshaling, **an error does not occur** if the output JSON value contains objects with duplicate names. | When marshaling, **an error does occur** if the output JSON value contains objects with duplicate names. | [DuplicateNames](/diff_test.go#:~:text=TestDuplicateNames) | -| When unmarshaling, **an error does not occur** if the input JSON value contains objects with duplicate names. | When unmarshaling, **an error does occur** if the input JSON value contains objects with duplicate names. | [DuplicateNames](/diff_test.go#:~:text=TestDuplicateNames) | -| Unmarshaling a JSON null into a non-empty Go value **inconsistently clears the value or does nothing**. | Unmarshaling a JSON null into a non-empty Go value **always clears the value**. | [MergeNull](/diff_test.go#:~:text=TestMergeNull) | -| Unmarshaling a JSON value into a non-empty Go value **follows inconsistent and bizarre behavior**. | Unmarshaling a JSON value into a non-empty Go value **always merges if the input is an object, and otherwise replaces**. | [MergeComposite](/diff_test.go#:~:text=TestMergeComposite) | -| A `time.Duration` is represented as a **JSON number containing the decimal number of nanoseconds**. | A `time.Duration` is represented as a **JSON string containing the formatted duration (e.g., "1h2m3.456s")**. | [TimeDurations](/diff_test.go#:~:text=TestTimeDurations) | -| Unmarshaling a JSON number into a Go float beyond its representation **results in an error**. | Unmarshaling a JSON number into a Go float beyond its representation **uses the closest representable value (e.g., ±`math.MaxFloat`)**. | [MaxFloats](/diff_test.go#:~:text=TestMaxFloats) | -| A Go struct with only unexported fields **can be serialized**. | A Go struct with only unexported fields **cannot be serialized**. | [EmptyStructs](/diff_test.go#:~:text=TestEmptyStructs) | -| A Go struct that embeds an unexported struct type **can sometimes be serialized**. | A Go struct that embeds an unexported struct type **cannot be serialized**. | [EmbedUnexported](/diff_test.go#:~:text=TestEmbedUnexported) | - -See [diff_test.go](/diff_test.go) for details about every change. +| JSON object members are unmarshaled into a Go struct using a **case-insensitive name match**. | JSON object members are unmarshaled into a Go struct using a **case-sensitive name match**. | [CaseSensitivity](/v1/diff_test.go#:~:text=TestCaseSensitivity) | +| When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value is an empty Go value**, which is defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string. | When marshaling a Go struct, a struct field marked as `omitempty` is omitted if **the field value would encode as an empty JSON value**, which is defined as a JSON null, or an empty JSON string, object, or array. | [OmitEmptyOption](/v1/diff_test.go#:~:text=TestOmitEmptyOption) | +| The `string` option **does affect** Go strings and bools. | The `string` option **does not affect** Go strings or bools. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | +| The `string` option **does not recursively affect** sub-values of the Go field value. | The `string` option **does recursively affect** sub-values of the Go field value. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | +| The `string` option **sometimes accepts** a JSON null escaped within a JSON string. | The `string` option **never accepts** a JSON null escaped within a JSON string. | [StringOption](/v1/diff_test.go#:~:text=TestStringOption) | +| A nil Go slice is marshaled as a **JSON null**. | A nil Go slice is marshaled as an **empty JSON array**. | [NilSlicesAndMaps](/v1/diff_test.go#:~:text=TestNilSlicesAndMaps) | +| A nil Go map is marshaled as a **JSON null**. | A nil Go map is marshaled as an **empty JSON object**. | [NilSlicesAndMaps](/v1/diff_test.go#:~:text=TestNilSlicesAndMaps) | +| A Go array may be unmarshaled from a **JSON array of any length**. | A Go array must be unmarshaled from a **JSON array of the same length**. | [Arrays](/v1/diff_test.go#:~:text=Arrays) | +| A Go byte array is represented as a **JSON array of JSON numbers**. | A Go byte array is represented as a **Base64-encoded JSON string**. | [ByteArrays](/v1/diff_test.go#:~:text=TestByteArrays) | +| `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **inconsistently called**. | `MarshalJSON` and `UnmarshalJSON` methods declared on a pointer receiver are **consistently called**. | [PointerReceiver](/v1/diff_test.go#:~:text=TestPointerReceiver) | +| A Go map is marshaled in a **deterministic order**. | A Go map is marshaled in a **non-deterministic order**. | [MapDeterminism](/v1/diff_test.go#:~:text=TestMapDeterminism) | +| JSON strings are encoded **with HTML-specific characters being escaped**. | JSON strings are encoded **without any characters being escaped** (unless necessary). | [EscapeHTML](/v1/diff_test.go#:~:text=TestEscapeHTML) | +| When marshaling, invalid UTF-8 within a Go string **are silently replaced**. | When marshaling, invalid UTF-8 within a Go string **results in an error**. | [InvalidUTF8](/v1/diff_test.go#:~:text=TestInvalidUTF8) | +| When unmarshaling, invalid UTF-8 within a JSON string **are silently replaced**. | When unmarshaling, invalid UTF-8 within a JSON string **results in an error**. | [InvalidUTF8](/v1/diff_test.go#:~:text=TestInvalidUTF8) | +| When marshaling, **an error does not occur** if the output JSON value contains objects with duplicate names. | When marshaling, **an error does occur** if the output JSON value contains objects with duplicate names. | [DuplicateNames](/v1/diff_test.go#:~:text=TestDuplicateNames) | +| When unmarshaling, **an error does not occur** if the input JSON value contains objects with duplicate names. | When unmarshaling, **an error does occur** if the input JSON value contains objects with duplicate names. | [DuplicateNames](/v1/diff_test.go#:~:text=TestDuplicateNames) | +| Unmarshaling a JSON null into a non-empty Go value **inconsistently clears the value or does nothing**. | Unmarshaling a JSON null into a non-empty Go value **always clears the value**. | [MergeNull](/v1/diff_test.go#:~:text=TestMergeNull) | +| Unmarshaling a JSON value into a non-empty Go value **follows inconsistent and bizarre behavior**. | Unmarshaling a JSON value into a non-empty Go value **always merges if the input is an object, and otherwise replaces**. | [MergeComposite](/v1/diff_test.go#:~:text=TestMergeComposite) | +| A `time.Duration` is represented as a **JSON number containing the decimal number of nanoseconds**. | A `time.Duration` has no default representation in v2 (see [#71631](https://golang.org/issue/71631)) and results in an error. | | +| A Go struct with only unexported fields **can be serialized**. | A Go struct with only unexported fields **cannot be serialized**. | [EmptyStructs](/v1/diff_test.go#:~:text=TestEmptyStructs) | + +See [diff_test.go](/v1/diff_test.go) for details about every change. ## Performance -One of the goals of the v2 module is to be more performant than v1. - -Each of the charts below show the performance across -several different JSON implementations: - -* `JSONv1` is `encoding/json` at `v1.18.2` -* `JSONv2` is `github.com/go-json-experiment/json` at `v0.0.0-20220524042235-dd8be80fc4a7` -* `JSONIterator` is `github.com/json-iterator/go` at `v1.1.12` -* `SegmentJSON` is `github.com/segmentio/encoding/json` at `v0.3.5` -* `GoJSON` is `github.com/goccy/go-json` at `v0.9.7` -* `SonicJSON` is `github.com/bytedance/sonic` at `v1.3.0` - -Benchmarks were run across various datasets: - -* `CanadaGeometry` is a GeoJSON (RFC 7946) representation of Canada. - It contains many JSON arrays of arrays of two-element arrays of numbers. -* `CITMCatalog` contains many JSON objects using numeric names. -* `SyntheaFHIR` is sample JSON data from the healthcare industry. - It contains many nested JSON objects with mostly string values, - where the set of unique string values is relatively small. -* `TwitterStatus` is the JSON response from the Twitter API. - It contains a mix of all different JSON kinds, where string values - are a mix of both single-byte ASCII and multi-byte Unicode. -* `GolangSource` is a simple tree representing the Go source code. - It contains many nested JSON objects, each with the same schema. -* `StringUnicode` contains many strings with multi-byte Unicode runes. - -All of the implementations other than `JSONv1` and `JSONv2` make -extensive use of `unsafe`. As such, we expect those to generally be faster, -but at the cost of memory and type safety. `SonicJSON` goes a step even further -and uses just-in-time compilation to generate machine code specialized -for the Go type being marshaled or unmarshaled. -Also, `SonicJSON` does not validate JSON strings for valid UTF-8, -and so gains a notable performance boost on datasets with multi-byte Unicode. -Benchmarks are performed based on the default marshal and unmarshal behavior -of each package. Note that `JSONv2` aims to be safe and correct by default, -which may not be the most performant strategy. - -`JSONv2` has several semantic changes relative to `JSONv1` that -impacts performance: - -1. When marshaling, `JSONv2` no longer sorts the keys of a Go map. - This will improve performance. -2. When marshaling or unmarshaling, `JSONv2` always checks - to make sure JSON object names are unique. - This will hurt performance, but is more correct. -3. When marshaling or unmarshaling, `JSONv2` always - shallow copies the underlying value for a Go interface and - shallow copies the key and value for entries in a Go map. - This is done to keep the value as addressable so that `JSONv2` can - call methods and functions that operate on a pointer receiver. - This will hurt performance, but is more correct. - -All of the charts are unit-less since the values are normalized -relative to `JSONv1`, which is why `JSONv1` always has a value of 1. -A lower value is better (i.e., runs faster). - -Benchmarks were performed on an AMD Ryzen 9 5900X. - -The code for the benchmarks is located at -https://github.com/go-json-experiment/jsonbench. - -### Marshal Performance - -#### Concrete types - -![Benchmark Marshal Concrete](benchmark-marshal-concrete.png) - -* This compares marshal performance when serializing - [from concrete types](/testdata_test.go). -* The `JSONv1` implementation is close to optimal (without the use of `unsafe`). -* Relative to `JSONv1`, `JSONv2` is generally as fast or slightly faster. -* Relative to `JSONIterator`, `JSONv2` is up to 1.3x faster. -* Relative to `SegmentJSON`, `JSONv2` is up to 1.8x slower. -* Relative to `GoJSON`, `JSONv2` is up to 2.0x slower. -* Relative to `SonicJSON`, `JSONv2` is about 1.8x to 3.2x slower - (ignoring `StringUnicode` since `SonicJSON` does not validate UTF-8). -* For `JSONv1` and `JSONv2`, marshaling from concrete types is - mostly limited by the performance of Go reflection. - -#### Interface types - -![Benchmark Marshal Interface](benchmark-marshal-interface.png) - -* This compares marshal performance when serializing from - `any`, `map[string]any`, and `[]any` types. -* Relative to `JSONv1`, `JSONv2` is about 1.5x to 4.2x faster. -* Relative to `JSONIterator`, `JSONv2` is about 1.1x to 2.4x faster. -* Relative to `SegmentJSON`, `JSONv2` is about 1.2x to 1.8x faster. -* Relative to `GoJSON`, `JSONv2` is about 1.1x to 2.5x faster. -* Relative to `SonicJSON`, `JSONv2` is up to 1.5x slower - (ignoring `StringUnicode` since `SonicJSON` does not validate UTF-8). -* `JSONv2` is faster than the alternatives. - One advantange is because it does not sort the keys for a `map[string]any`, - while alternatives (except `SonicJSON` and `JSONIterator`) do sort the keys. - -#### RawValue types - -![Benchmark Marshal Rawvalue](benchmark-marshal-rawvalue.png) - -* This compares performance when marshaling from a `json.RawValue`. - This mostly exercises the underlying encoder and - hides the cost of Go reflection. -* Relative to `JSONv1`, `JSONv2` is about 3.5x to 7.8x faster. -* `JSONIterator` is blazingly fast because - [it does not validate whether the raw value is valid](https://go.dev/play/p/bun9IXQCKRe) - and simply copies it to the output. -* Relative to `SegmentJSON`, `JSONv2` is about 1.5x to 2.7x faster. -* Relative to `GoJSON`, `JSONv2` is up to 2.2x faster. -* Relative to `SonicJSON`, `JSONv2` is up to 1.5x faster. -* Aside from `JSONIterator`, `JSONv2` is generally the fastest. - -### Unmarshal Performance - -#### Concrete types - -![Benchmark Unmarshal Concrete](benchmark-unmarshal-concrete.png) - -* This compares unmarshal performance when deserializing - [into concrete types](/testdata_test.go). -* Relative to `JSONv1`, `JSONv2` is about 1.8x to 5.7x faster. -* Relative to `JSONIterator`, `JSONv2` is about 1.1x to 1.6x slower. -* Relative to `SegmentJSON`, `JSONv2` is up to 2.5x slower. -* Relative to `GoJSON`, `JSONv2` is about 1.4x to 2.1x slower. -* Relative to `SonicJSON`, `JSONv2` is up to 4.0x slower - (ignoring `StringUnicode` since `SonicJSON` does not validate UTF-8). -* For `JSONv1` and `JSONv2`, unmarshaling into concrete types is - mostly limited by the performance of Go reflection. - -#### Interface types - -![Benchmark Unmarshal Interface](benchmark-unmarshal-interface.png) - -* This compares unmarshal performance when deserializing into - `any`, `map[string]any`, and `[]any` types. -* Relative to `JSONv1`, `JSONv2` is about 1.tx to 4.3x faster. -* Relative to `JSONIterator`, `JSONv2` is up to 1.5x faster. -* Relative to `SegmentJSON`, `JSONv2` is about 1.5 to 3.7x faster. -* Relative to `GoJSON`, `JSONv2` is up to 1.3x faster. -* Relative to `SonicJSON`, `JSONv2` is up to 1.5x slower - (ignoring `StringUnicode` since `SonicJSON` does not validate UTF-8). -* Aside from `SonicJSON`, `JSONv2` is generally just as fast - or faster than all the alternatives. - -#### RawValue types - -![Benchmark Unmarshal Rawvalue](benchmark-unmarshal-rawvalue.png) - -* This compares performance when unmarshaling into a `json.RawValue`. - This mostly exercises the underlying decoder and - hides away most of the cost of Go reflection. -* Relative to `JSONv1`, `JSONv2` is about 8.3x to 17.0x faster. -* Relative to `JSONIterator`, `JSONv2` is up to 2.0x faster. -* Relative to `SegmentJSON`, `JSONv2` is up to 1.6x faster or 1.7x slower. -* Relative to `GoJSON`, `JSONv2` is up to 1.9x faster or 2.1x slower. -* Relative to `SonicJSON`, `JSONv2` is up to 2.0x faster - (ignoring `StringUnicode` since `SonicJSON` does not validate UTF-8). -* `JSONv1` takes a - [lexical scanning approach](https://talks.golang.org/2011/lex.slide#1), - which performs a virtual function call for every byte of input. - In contrast, `JSONv2` makes heavy use of iterative and linear parsing logic - (with extra complexity to resume parsing when encountering segmented buffers). -* `JSONv2` is comparable to the alternatives that use `unsafe`. - Generally it is faster, but sometimes it is slower. +One of the goals of the v2 module is to be more performant than v1, +but not at the expense of correctness. +In general, v2 is at performance parity with v1 for marshaling, +but dramatically faster for unmarshaling. + +See https://github.com/go-json-experiment/jsonbench for benchmarks +comparing v2 with v1 and a number of other popular JSON implementations. diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go index e6c6216ff..dbf92432d 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go @@ -5,109 +5,65 @@ package json import ( - "errors" + "bytes" + "encoding" "io" "reflect" + "slices" + "strings" "sync" -) - -// MarshalOptions configures how Go data is serialized as JSON data. -// The zero value is equivalent to the default marshal settings. -type MarshalOptions struct { - requireKeyedLiterals - nonComparable - - // Marshalers is a list of type-specific marshalers to use. - Marshalers *Marshalers - - // StringifyNumbers specifies that numeric Go types should be serialized - // as a JSON string containing the equivalent JSON number value. - // - // According to RFC 8259, section 6, a JSON implementation may choose to - // limit the representation of a JSON number to an IEEE 754 binary64 value. - // This may cause decoders to lose precision for int64 and uint64 types. - // Escaping JSON numbers as a JSON string preserves the exact precision. - StringifyNumbers bool - - // DiscardUnknownMembers specifies that marshaling should ignore any - // JSON object members stored in Go struct fields dedicated to storing - // unknown JSON object members. - DiscardUnknownMembers bool - - // Deterministic specifies that the same input value will be serialized - // as the exact same output bytes. Different processes of - // the same program will serialize equal values to the same bytes, - // but different versions of the same program are not guaranteed - // to produce the exact same sequence of bytes. - Deterministic bool + "time" - // formatDepth is the depth at which we respect the format flag. - formatDepth int - // format is custom formatting for the value at the specified depth. - format string -} + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" +) -// Marshal serializes a Go value as a []byte with default options. -// It is a thin wrapper over MarshalOptions.Marshal. -func Marshal(in any) (out []byte, err error) { - return MarshalOptions{}.Marshal(EncodeOptions{}, in) -} +// Reference encoding and time packages to assist pkgsite +// in being able to hotlink references to those packages. +var ( + _ encoding.TextMarshaler + _ encoding.TextAppender + _ encoding.TextUnmarshaler + _ time.Time + _ time.Duration +) -// MarshalFull serializes a Go value into an io.Writer with default options. -// It is a thin wrapper over MarshalOptions.MarshalFull. -func MarshalFull(out io.Writer, in any) error { - return MarshalOptions{}.MarshalFull(EncodeOptions{}, out, in) -} +// export exposes internal functionality of the "jsontext" package. +var export = jsontext.Internal.Export(&internal.AllowInternalUse) // Marshal serializes a Go value as a []byte according to the provided -// marshal and encode options. It does not terminate the output with a newline. -// See MarshalNext for details about the conversion of a Go value into JSON. -func (mo MarshalOptions) Marshal(eo EncodeOptions, in any) (out []byte, err error) { - enc := getBufferedEncoder(eo) - defer putBufferedEncoder(enc) - enc.options.omitTopLevelNewline = true - err = mo.MarshalNext(enc, in) - // TODO(https://go.dev/issue/45038): Use bytes.Clone. - return append([]byte(nil), enc.buf...), err -} - -// MarshalFull serializes a Go value into an io.Writer according to the provided -// marshal and encode options. It does not terminate the output with a newline. -// See MarshalNext for details about the conversion of a Go value into JSON. -func (mo MarshalOptions) MarshalFull(eo EncodeOptions, out io.Writer, in any) error { - enc := getStreamingEncoder(out, eo) - defer putStreamingEncoder(enc) - enc.options.omitTopLevelNewline = true - err := mo.MarshalNext(enc, in) - return err -} - -// MarshalNext encodes a Go value as the next JSON value according to -// the provided marshal options. +// marshal and encode options (while ignoring unmarshal or decode options). +// It does not terminate the output with a newline. // // Type-specific marshal functions and methods take precedence // over the default representation of a value. // Functions or methods that operate on *T are only called when encoding // a value of type T (by taking its address) or a non-nil value of *T. -// MarshalNext ensures that a value is always addressable +// Marshal ensures that a value is always addressable // (by boxing it on the heap if necessary) so that // these functions and methods can be consistently called. For performance, -// it is recommended that MarshalNext be passed a non-nil pointer to the value. +// it is recommended that Marshal be passed a non-nil pointer to the value. // // The input value is encoded as JSON according the following rules: // -// - If any type-specific functions in MarshalOptions.Marshalers match +// - If any type-specific functions in a [WithMarshalers] option match // the value type, then those functions are called to encode the value. -// If all applicable functions return SkipFunc, +// If all applicable functions return [SkipFunc], // then the value is encoded according to subsequent rules. // -// - If the value type implements MarshalerV2, -// then the MarshalNextJSON method is called to encode the value. +// - If the value type implements [MarshalerTo], +// then the MarshalJSONTo method is called to encode the value. // -// - If the value type implements MarshalerV1, +// - If the value type implements [Marshaler], // then the MarshalJSON method is called to encode the value. // -// - If the value type implements encoding.TextMarshaler, +// - If the value type implements [encoding.TextAppender], +// then the AppendText method is called to encode the value and +// subsequently encode its result as a JSON string. +// +// - If the value type implements [encoding.TextMarshaler], // then the MarshalText method is called to encode the value and // subsequently encode its result as a JSON string. // @@ -139,25 +95,25 @@ func (mo MarshalOptions) MarshalFull(eo EncodeOptions, out io.Writer, in any) er // where each byte is recursively JSON-encoded as each JSON array element. // // - A Go integer is encoded as a JSON number without fractions or exponents. -// If MarshalOptions.StringifyNumbers is specified, then the JSON number is -// encoded within a JSON string. It does not support any custom format -// flags. +// If [StringifyNumbers] is specified or encoding a JSON object name, +// then the JSON number is encoded within a JSON string. +// It does not support any custom format flags. // // - A Go float is encoded as a JSON number. -// If MarshalOptions.StringifyNumbers is specified, +// If [StringifyNumbers] is specified or encoding a JSON object name, // then the JSON number is encoded within a JSON string. // If the format is "nonfinite", then NaN, +Inf, and -Inf are encoded as // the JSON strings "NaN", "Infinity", and "-Infinity", respectively. -// Otherwise, the presence of non-finite numbers results in a SemanticError. +// Otherwise, the presence of non-finite numbers results in a [SemanticError]. // // - A Go map is encoded as a JSON object, where each Go map key and value // is recursively encoded as a name and value pair in the JSON object. // The Go map key must encode as a JSON string, otherwise this results -// in a SemanticError. When encoding keys, MarshalOptions.StringifyNumbers -// is automatically applied so that numeric keys encode as JSON strings. -// The Go map is traversed in a non-deterministic order. -// For deterministic encoding, consider using RawValue.Canonicalize. +// in a [SemanticError]. The Go map is traversed in a non-deterministic order. +// For deterministic encoding, consider using the [Deterministic] option. // If the format is "emitnull", then a nil map is encoded as a JSON null. +// If the format is "emitempty", then a nil map is encoded as an empty JSON object, +// regardless of whether [FormatNilMapAsNull] is specified. // Otherwise by default, a nil map is encoded as an empty JSON object. // // - A Go struct is encoded as a JSON object. @@ -167,6 +123,8 @@ func (mo MarshalOptions) MarshalFull(eo EncodeOptions, out io.Writer, in any) er // - A Go slice is encoded as a JSON array, where each Go slice element // is recursively JSON-encoded as the elements of the JSON array. // If the format is "emitnull", then a nil slice is encoded as a JSON null. +// If the format is "emitempty", then a nil slice is encoded as an empty JSON array, +// regardless of whether [FormatNilSliceAsNull] is specified. // Otherwise by default, a nil slice is encoded as an empty JSON array. // // - A Go array is encoded as a JSON array, where each Go array element @@ -182,148 +140,144 @@ func (mo MarshalOptions) MarshalFull(eo EncodeOptions, out io.Writer, in any) er // the recursively JSON-encoded representation of the underlying value. // It does not support any custom format flags. // -// - A Go time.Time is encoded as a JSON string containing the timestamp -// formatted in RFC 3339 with nanosecond resolution. +// - A Go [time.Time] is encoded as a JSON string containing the timestamp +// formatted in RFC 3339 with nanosecond precision. // If the format matches one of the format constants declared // in the time package (e.g., RFC1123), then that format is used. -// Otherwise, the format is used as-is with time.Time.Format if non-empty. -// -// - A Go time.Duration is encoded as a JSON string containing the duration -// formatted according to time.Duration.String. -// If the format is "nanos", it is encoded as a JSON number -// containing the number of nanoseconds in the duration. +// If the format is "unix", "unixmilli", "unixmicro", or "unixnano", +// then the timestamp is encoded as a possibly fractional JSON number +// of the number of seconds (or milliseconds, microseconds, or nanoseconds) +// since the Unix epoch, which is January 1st, 1970 at 00:00:00 UTC. +// To avoid a fractional component, round the timestamp to the relevant unit. +// Otherwise, the format is used as-is with [time.Time.Format] if non-empty. +// +// - A Go [time.Duration] currently has no default representation and +// requires an explicit format to be specified. +// If the format is "sec", "milli", "micro", or "nano", +// then the duration is encoded as a possibly fractional JSON number +// of the number of seconds (or milliseconds, microseconds, or nanoseconds). +// To avoid a fractional component, round the duration to the relevant unit. +// If the format is "units", it is encoded as a JSON string formatted using +// [time.Duration.String] (e.g., "1h30m" for 1 hour 30 minutes). +// If the format is "iso8601", it is encoded as a JSON string using the +// ISO 8601 standard for durations (e.g., "PT1H30M" for 1 hour 30 minutes) +// using only accurate units of hours, minutes, and seconds. // // - All other Go types (e.g., complex numbers, channels, and functions) -// have no default representation and result in a SemanticError. +// have no default representation and result in a [SemanticError]. // -// JSON cannot represent cyclic data structures and -// MarshalNext does not handle them. +// JSON cannot represent cyclic data structures and Marshal does not handle them. // Passing cyclic structures will result in an error. -func (mo MarshalOptions) MarshalNext(out *Encoder, in any) error { +func Marshal(in any, opts ...Options) (out []byte, err error) { + enc := export.GetBufferedEncoder(opts...) + defer export.PutBufferedEncoder(enc) + xe := export.Encoder(enc) + xe.Flags.Set(jsonflags.OmitTopLevelNewline | 1) + err = marshalEncode(enc, in, &xe.Struct) + if err != nil && xe.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return nil, internal.TransformMarshalError(in, err) + } + return bytes.Clone(xe.Buf), err +} + +// MarshalWrite serializes a Go value into an [io.Writer] according to the provided +// marshal and encode options (while ignoring unmarshal or decode options). +// It does not terminate the output with a newline. +// See [Marshal] for details about the conversion of a Go value into JSON. +func MarshalWrite(out io.Writer, in any, opts ...Options) (err error) { + enc := export.GetStreamingEncoder(out, opts...) + defer export.PutStreamingEncoder(enc) + xe := export.Encoder(enc) + xe.Flags.Set(jsonflags.OmitTopLevelNewline | 1) + err = marshalEncode(enc, in, &xe.Struct) + if err != nil && xe.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.TransformMarshalError(in, err) + } + return err +} + +// MarshalEncode serializes a Go value into an [jsontext.Encoder] according to +// the provided marshal options (while ignoring unmarshal, encode, or decode options). +// Any marshal-relevant options already specified on the [jsontext.Encoder] +// take lower precedence than the set of options provided by the caller. +// Unlike [Marshal] and [MarshalWrite], encode options are ignored because +// they must have already been specified on the provided [jsontext.Encoder]. +// +// See [Marshal] for details about the conversion of a Go value into JSON. +func MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) (err error) { + xe := export.Encoder(out) + if len(opts) > 0 { + optsOriginal := xe.Struct + defer func() { xe.Struct = optsOriginal }() + xe.Struct.JoinWithoutCoderOptions(opts...) + } + err = marshalEncode(out, in, &xe.Struct) + if err != nil && xe.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.TransformMarshalError(in, err) + } + return err +} + +func marshalEncode(out *jsontext.Encoder, in any, mo *jsonopts.Struct) (err error) { v := reflect.ValueOf(in) if !v.IsValid() || (v.Kind() == reflect.Pointer && v.IsNil()) { - return out.WriteToken(Null) + return out.WriteToken(jsontext.Null) } // Shallow copy non-pointer values to obtain an addressable value. // It is beneficial to performance to always pass pointers to avoid this. - if v.Kind() != reflect.Pointer { + forceAddr := v.Kind() != reflect.Pointer + if forceAddr { v2 := reflect.New(v.Type()) v2.Elem().Set(v) v = v2 } - va := addressableValue{v.Elem()} // dereferenced pointer is always addressable + va := addressableValue{v.Elem(), forceAddr} // dereferenced pointer is always addressable t := va.Type() // Lookup and call the marshal function for this type. marshal := lookupArshaler(t).marshal if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, t) + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, t) } - if err := marshal(mo, out, va); err != nil { - if !out.options.AllowDuplicateNames { - out.tokens.invalidateDisabledNamespaces() + if err := marshal(out, va, mo); err != nil { + if !mo.Flags.Get(jsonflags.AllowDuplicateNames) { + export.Encoder(out).Tokens.InvalidateDisabledNamespaces() } return err } return nil } -// UnmarshalOptions configures how JSON data is deserialized as Go data. -// The zero value is equivalent to the default unmarshal settings. -type UnmarshalOptions struct { - requireKeyedLiterals - nonComparable - - // Unmarshalers is a list of type-specific unmarshalers to use. - Unmarshalers *Unmarshalers - - // StringifyNumbers specifies that numeric Go types can be deserialized - // from either a JSON number or a JSON string containing a JSON number - // without any surrounding whitespace. - StringifyNumbers bool - - // RejectUnknownMembers specifies that unknown members should be rejected - // when unmarshaling a JSON object, regardless of whether there is a field - // to store unknown members. - RejectUnknownMembers bool - - // formatDepth is the depth at which we respect the format flag. - formatDepth int - // format is custom formatting for the value at the specified depth. - format string -} - -// Unmarshal deserializes a Go value from a []byte with default options. -// It is a thin wrapper over UnmarshalOptions.Unmarshal. -func Unmarshal(in []byte, out any) error { - return UnmarshalOptions{}.Unmarshal(DecodeOptions{}, in, out) -} - -// UnmarshalFull deserializes a Go value from an io.Reader with default options. -// It is a thin wrapper over UnmarshalOptions.UnmarshalFull. -func UnmarshalFull(in io.Reader, out any) error { - return UnmarshalOptions{}.UnmarshalFull(DecodeOptions{}, in, out) -} - -// Unmarshal deserializes a Go value from a []byte according to the -// provided unmarshal and decode options. The output must be a non-nil pointer. +// Unmarshal decodes a []byte input into a Go value according to the provided +// unmarshal and decode options (while ignoring marshal or encode options). // The input must be a single JSON value with optional whitespace interspersed. -// See UnmarshalNext for details about the conversion of JSON into a Go value. -func (uo UnmarshalOptions) Unmarshal(do DecodeOptions, in []byte, out any) error { - dec := getBufferedDecoder(in, do) - defer putBufferedDecoder(dec) - return uo.unmarshalFull(dec, out) -} - -// UnmarshalFull deserializes a Go value from an io.Reader according to the -// provided unmarshal and decode options. The output must be a non-nil pointer. -// The input must be a single JSON value with optional whitespace interspersed. -// It consumes the entirety of io.Reader until io.EOF is encountered. -// See UnmarshalNext for details about the conversion of JSON into a Go value. -func (uo UnmarshalOptions) UnmarshalFull(do DecodeOptions, in io.Reader, out any) error { - dec := getStreamingDecoder(in, do) - defer putStreamingDecoder(dec) - return uo.unmarshalFull(dec, out) -} -func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { - switch err := uo.UnmarshalNext(in, out); err { - case nil: - return in.checkEOF() - case io.EOF: - return io.ErrUnexpectedEOF - default: - return err - } -} - -// UnmarshalNext decodes the next JSON value into a Go value according to -// the provided unmarshal options. The output must be a non-nil pointer. +// The output must be a non-nil pointer. // // Type-specific unmarshal functions and methods take precedence // over the default representation of a value. // Functions or methods that operate on *T are only called when decoding // a value of type T (by taking its address) or a non-nil value of *T. -// UnmarshalNext ensures that a value is always addressable +// Unmarshal ensures that a value is always addressable // (by boxing it on the heap if necessary) so that // these functions and methods can be consistently called. // // The input is decoded into the output according the following rules: // -// - If any type-specific functions in UnmarshalOptions.Unmarshalers match +// - If any type-specific functions in a [WithUnmarshalers] option match // the value type, then those functions are called to decode the JSON -// value. If all applicable functions return SkipFunc, +// value. If all applicable functions return [SkipFunc], // then the input is decoded according to subsequent rules. // -// - If the value type implements UnmarshalerV2, -// then the UnmarshalNextJSON method is called to decode the JSON value. +// - If the value type implements [UnmarshalerFrom], +// then the UnmarshalJSONFrom method is called to decode the JSON value. // -// - If the value type implements UnmarshalerV1, +// - If the value type implements [Unmarshaler], // then the UnmarshalJSON method is called to decode the JSON value. // -// - If the value type implements encoding.TextUnmarshaler, +// - If the value type implements [encoding.TextUnmarshaler], // then the input is decoded as a JSON string and // the UnmarshalText method is called with the decoded string value. -// This fails with a SemanticError if the input is not a JSON string. +// This fails with a [SemanticError] if the input is not a JSON string. // // - Otherwise, the JSON value is decoded according to the value's type // as described in detail below. @@ -336,7 +290,7 @@ func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { // A JSON null may be decoded into every supported Go value where // it is equivalent to storing the zero value of the Go value. // If the input JSON kind is not handled by the current Go value type, -// then this fails with a SemanticError. Unless otherwise specified, +// then this fails with a [SemanticError]. Unless otherwise specified, // the decoded value replaces any pre-existing value. // // The representation of each type is as follows: @@ -359,33 +313,31 @@ func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { // When decoding into a non-nil []byte, the slice length is reset to zero // and the decoded input is appended to it. // When decoding into a [N]byte, the input must decode to exactly N bytes, -// otherwise it fails with a SemanticError. +// otherwise it fails with a [SemanticError]. // // - A Go integer is decoded from a JSON number. -// It may also be decoded from a JSON string containing a JSON number -// if UnmarshalOptions.StringifyNumbers is specified. -// It fails with a SemanticError if the JSON number +// It must be decoded from a JSON string containing a JSON number +// if [StringifyNumbers] is specified or decoding a JSON object name. +// It fails with a [SemanticError] if the JSON number // has a fractional or exponent component. // It also fails if it overflows the representation of the Go integer type. // It does not support any custom format flags. // // - A Go float is decoded from a JSON number. -// It may also be decoded from a JSON string containing a JSON number -// if UnmarshalOptions.StringifyNumbers is specified. -// The JSON number is parsed as the closest representable Go float value. +// It must be decoded from a JSON string containing a JSON number +// if [StringifyNumbers] is specified or decoding a JSON object name. +// It fails if it overflows the representation of the Go float type. // If the format is "nonfinite", then the JSON strings // "NaN", "Infinity", and "-Infinity" are decoded as NaN, +Inf, and -Inf. -// Otherwise, the presence of such strings results in a SemanticError. +// Otherwise, the presence of such strings results in a [SemanticError]. // // - A Go map is decoded from a JSON object, // where each JSON object name and value pair is recursively decoded -// as the Go map key and value. When decoding keys, -// UnmarshalOptions.StringifyNumbers is automatically applied so that -// numeric keys can decode from JSON strings. Maps are not cleared. +// as the Go map key and value. Maps are not cleared. // If the Go map is nil, then a new map is allocated to decode into. // If the decoded key matches an existing Go map entry, the entry value // is reused by decoding the JSON object value into it. -// The only supported format is "emitnull" and has no effect when decoding. +// The formats "emitnull" and "emitempty" have no effect when decoding. // // - A Go struct is decoded from a JSON object. // See the “JSON Representation of Go structs” section @@ -395,12 +347,12 @@ func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { // is recursively decoded and appended to the Go slice. // Before appending into a Go slice, a new slice is allocated if it is nil, // otherwise the slice length is reset to zero. -// The only supported format is "emitnull" and has no effect when decoding. +// The formats "emitnull" and "emitempty" have no effect when decoding. // // - A Go array is decoded from a JSON array, where each JSON array element // is recursively decoded as each corresponding Go array element. // Each Go array element is zeroed before decoding into it. -// It fails with a SemanticError if the JSON array does not contain +// It fails with a [SemanticError] if the JSON array does not contain // the exact same number of elements as the Go array. // It does not support any custom format flags. // @@ -415,59 +367,133 @@ func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { // Otherwise, a nil interface value of an empty interface type is initialized // with a zero Go bool, string, float64, map[string]any, or []any if the // input is a JSON boolean, string, number, object, or array, respectively. -// If the interface value is still nil, then this fails with a SemanticError +// If the interface value is still nil, then this fails with a [SemanticError] // since decoding could not determine an appropriate Go type to decode into. // For example, unmarshaling into a nil io.Reader fails since // there is no concrete type to populate the interface value with. // Otherwise an underlying value exists and it recursively decodes // the JSON input into it. It does not support any custom format flags. // -// - A Go time.Time is decoded from a JSON string containing the time -// formatted in RFC 3339 with nanosecond resolution. +// - A Go [time.Time] is decoded from a JSON string containing the time +// formatted in RFC 3339 with nanosecond precision. // If the format matches one of the format constants declared in // the time package (e.g., RFC1123), then that format is used for parsing. -// Otherwise, the format is used as-is with time.Time.Parse if non-empty. -// -// - A Go time.Duration is decoded from a JSON string by -// passing the decoded string to time.ParseDuration. -// If the format is "nanos", it is instead decoded from a JSON number -// containing the number of nanoseconds in the duration. +// If the format is "unix", "unixmilli", "unixmicro", or "unixnano", +// then the timestamp is decoded from an optionally fractional JSON number +// of the number of seconds (or milliseconds, microseconds, or nanoseconds) +// since the Unix epoch, which is January 1st, 1970 at 00:00:00 UTC. +// Otherwise, the format is used as-is with [time.Time.Parse] if non-empty. +// +// - A Go [time.Duration] currently has no default representation and +// requires an explicit format to be specified. +// If the format is "sec", "milli", "micro", or "nano", +// then the duration is decoded from an optionally fractional JSON number +// of the number of seconds (or milliseconds, microseconds, or nanoseconds). +// If the format is "units", it is decoded from a JSON string parsed using +// [time.ParseDuration] (e.g., "1h30m" for 1 hour 30 minutes). +// If the format is "iso8601", it is decoded from a JSON string using the +// ISO 8601 standard for durations (e.g., "PT1H30M" for 1 hour 30 minutes) +// accepting only accurate units of hours, minutes, or seconds. // // - All other Go types (e.g., complex numbers, channels, and functions) -// have no default representation and result in a SemanticError. +// have no default representation and result in a [SemanticError]. // // In general, unmarshaling follows merge semantics (similar to RFC 7396) // where the decoded Go value replaces the destination value // for any JSON kind other than an object. // For JSON objects, the input object is merged into the destination value // where matching object members recursively apply merge semantics. -func (uo UnmarshalOptions) UnmarshalNext(in *Decoder, out any) error { +func Unmarshal(in []byte, out any, opts ...Options) (err error) { + dec := export.GetBufferedDecoder(in, opts...) + defer export.PutBufferedDecoder(dec) + xd := export.Decoder(dec) + err = unmarshalDecode(dec, out, &xd.Struct, true) + if err != nil && xd.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.TransformUnmarshalError(out, err) + } + return err +} + +// UnmarshalRead deserializes a Go value from an [io.Reader] according to the +// provided unmarshal and decode options (while ignoring marshal or encode options). +// The input must be a single JSON value with optional whitespace interspersed. +// It consumes the entirety of [io.Reader] until [io.EOF] is encountered, +// without reporting an error for EOF. The output must be a non-nil pointer. +// See [Unmarshal] for details about the conversion of JSON into a Go value. +func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error) { + dec := export.GetStreamingDecoder(in, opts...) + defer export.PutStreamingDecoder(dec) + xd := export.Decoder(dec) + err = unmarshalDecode(dec, out, &xd.Struct, true) + if err != nil && xd.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.TransformUnmarshalError(out, err) + } + return err +} + +// UnmarshalDecode deserializes a Go value from a [jsontext.Decoder] according to +// the provided unmarshal options (while ignoring marshal, encode, or decode options). +// Any unmarshal options already specified on the [jsontext.Decoder] +// take lower precedence than the set of options provided by the caller. +// Unlike [Unmarshal] and [UnmarshalRead], decode options are ignored because +// they must have already been specified on the provided [jsontext.Decoder]. +// +// The input may be a stream of one or more JSON values, +// where this only unmarshals the next JSON value in the stream. +// The output must be a non-nil pointer. +// See [Unmarshal] for details about the conversion of JSON into a Go value. +func UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) (err error) { + xd := export.Decoder(in) + if len(opts) > 0 { + optsOriginal := xd.Struct + defer func() { xd.Struct = optsOriginal }() + xd.Struct.JoinWithoutCoderOptions(opts...) + } + err = unmarshalDecode(in, out, &xd.Struct, false) + if err != nil && xd.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.TransformUnmarshalError(out, err) + } + return err +} + +func unmarshalDecode(in *jsontext.Decoder, out any, uo *jsonopts.Struct, last bool) (err error) { v := reflect.ValueOf(out) - if !v.IsValid() || v.Kind() != reflect.Pointer || v.IsNil() { - var t reflect.Type - if v.IsValid() { - t = v.Type() - if t.Kind() == reflect.Pointer { - t = t.Elem() + if v.Kind() != reflect.Pointer || v.IsNil() { + return &SemanticError{action: "unmarshal", GoType: reflect.TypeOf(out), Err: internal.ErrNonNilReference} + } + va := addressableValue{v.Elem(), false} // dereferenced pointer is always addressable + t := va.Type() + + // In legacy semantics, the entirety of the next JSON value + // was validated before attempting to unmarshal it. + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + if err := export.Decoder(in).CheckNextValue(last); err != nil { + if err == io.EOF && last { + offset := in.InputOffset() + int64(len(in.UnreadBuffer())) + return &jsontext.SyntacticError{ByteOffset: offset, Err: io.ErrUnexpectedEOF} } + return err } - err := errors.New("value must be passed as a non-nil pointer reference") - return &SemanticError{action: "unmarshal", GoType: t, Err: err} } - va := addressableValue{v.Elem()} // dereferenced pointer is always addressable - t := va.Type() // Lookup and call the unmarshal function for this type. unmarshal := lookupArshaler(t).unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, t) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, t) } - if err := unmarshal(uo, in, va); err != nil { - if !in.options.AllowDuplicateNames { - in.tokens.invalidateDisabledNamespaces() + if err := unmarshal(in, va, uo); err != nil { + if !uo.Flags.Get(jsonflags.AllowDuplicateNames) { + export.Decoder(in).Tokens.InvalidateDisabledNamespaces() + } + if err == io.EOF && last { + offset := in.InputOffset() + int64(len(in.UnreadBuffer())) + return &jsontext.SyntacticError{ByteOffset: offset, Err: io.ErrUnexpectedEOF} } return err } + if last { + return export.Decoder(in).CheckEOF() + } return nil } @@ -477,17 +503,31 @@ func (uo UnmarshalOptions) UnmarshalNext(in *Decoder, out any) error { // There is no compile magic that enforces this property, // but rather the need to construct this type makes it easier to examine each // construction site to ensure that this property is upheld. -type addressableValue struct{ reflect.Value } +type addressableValue struct { + reflect.Value + + // forcedAddr reports whether this value is addressable + // only through the use of [newAddressableValue]. + // This is only used for [jsonflags.CallMethodsWithLegacySemantics]. + forcedAddr bool +} // newAddressableValue constructs a new addressable value of type t. func newAddressableValue(t reflect.Type) addressableValue { - return addressableValue{reflect.New(t).Elem()} + return addressableValue{reflect.New(t).Elem(), true} } +// TODO: Remove *jsonopts.Struct argument from [marshaler] and [unmarshaler]. +// This can be directly accessed on the encoder or decoder. + // All marshal and unmarshal behavior is implemented using these signatures. +// The *jsonopts.Struct argument is guaranteed to identical to or at least +// a strict super-set of the options in Encoder.Struct or Decoder.Struct. +// It is identical for Marshal, Unmarshal, MarshalWrite, and UnmarshalRead. +// It is a super-set for MarshalEncode and UnmarshalDecode. type ( - marshaler = func(MarshalOptions, *Encoder, addressableValue) error - unmarshaler = func(UnmarshalOptions, *Decoder, addressableValue) error + marshaler = func(*jsontext.Encoder, addressableValue, *jsonopts.Struct) error + unmarshaler = func(*jsontext.Decoder, addressableValue, *jsonopts.Struct) error ) type arshaler struct { @@ -511,3 +551,28 @@ func lookupArshaler(t reflect.Type) *arshaler { v, _ := lookupArshalerCache.LoadOrStore(t, fncs) return v.(*arshaler) } + +var stringsPools = &sync.Pool{New: func() any { return new(stringSlice) }} + +type stringSlice []string + +// getStrings returns a non-nil pointer to a slice with length n. +func getStrings(n int) *stringSlice { + s := stringsPools.Get().(*stringSlice) + if cap(*s) < n { + *s = make([]string, n) + } + *s = (*s)[:n] + return s +} + +func putStrings(s *stringSlice) { + if cap(*s) > 1<<10 { + *s = nil // avoid pinning arbitrarily large amounts of memory + } + stringsPools.Put(s) +} + +func (ss *stringSlice) Sort() { + slices.SortFunc(*ss, func(x, y string) int { return strings.Compare(x, y) }) +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go index c62b1f320..fd034c1a1 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go @@ -4,47 +4,69 @@ package json -import "reflect" +import ( + "cmp" + "math" + "reflect" + "strconv" -// This files contains an optimized marshal and unmarshal implementation + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" +) + +// This file contains an optimized marshal and unmarshal implementation // for the any type. This type is often used when the Go program has // no knowledge of the JSON schema. This is a common enough occurrence // to justify the complexity of adding logic for this. -func marshalValueAny(mo MarshalOptions, enc *Encoder, val any) error { +// marshalValueAny marshals a Go any as a JSON value. +// This assumes that there are no special formatting directives +// for any possible nested value. +func marshalValueAny(enc *jsontext.Encoder, val any, mo *jsonopts.Struct) error { switch val := val.(type) { case nil: - return enc.WriteToken(Null) + return enc.WriteToken(jsontext.Null) case bool: - return enc.WriteToken(Bool(val)) + return enc.WriteToken(jsontext.Bool(val)) case string: - return enc.WriteToken(String(val)) + return enc.WriteToken(jsontext.String(val)) case float64: - return enc.WriteToken(Float(val)) + if math.IsNaN(val) || math.IsInf(val, 0) { + break // use default logic below + } + return enc.WriteToken(jsontext.Float(val)) case map[string]any: - return marshalObjectAny(mo, enc, val) + return marshalObjectAny(enc, val, mo) case []any: - return marshalArrayAny(mo, enc, val) - default: - v := newAddressableValue(reflect.TypeOf(val)) - v.Set(reflect.ValueOf(val)) - marshal := lookupArshaler(v.Type()).marshal - if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, v.Type()) - } - return marshal(mo, enc, v) + return marshalArrayAny(enc, val, mo) } + + v := newAddressableValue(reflect.TypeOf(val)) + v.Set(reflect.ValueOf(val)) + marshal := lookupArshaler(v.Type()).marshal + if mo.Marshalers != nil { + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, v.Type()) + } + return marshal(enc, v, mo) } -func unmarshalValueAny(uo UnmarshalOptions, dec *Decoder) (any, error) { +// unmarshalValueAny unmarshals a JSON value as a Go any. +// This assumes that there are no special formatting directives +// for any possible nested value. +// Duplicate names must be rejected since this does not implement merging. +func unmarshalValueAny(dec *jsontext.Decoder, uo *jsonopts.Struct) (any, error) { switch k := dec.PeekKind(); k { case '{': - return unmarshalObjectAny(uo, dec) + return unmarshalObjectAny(dec, uo) case '[': - return unmarshalArrayAny(uo, dec) + return unmarshalArrayAny(dec, uo) default: - var flags valueFlags - val, err := dec.readValue(&flags) + xd := export.Decoder(dec) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return nil, err } @@ -56,13 +78,19 @@ func unmarshalValueAny(uo UnmarshalOptions, dec *Decoder) (any, error) { case 't': return true, nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) - if dec.stringCache == nil { - dec.stringCache = new(stringCache) + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if xd.StringCache == nil { + xd.StringCache = new(stringCache) } - return dec.stringCache.make(val), nil + return makeString(xd.StringCache, val), nil case '0': - fv, _ := parseFloat(val, 64) // ignore error since readValue guarantees val is valid + if uo.Flags.Get(jsonflags.UnmarshalAnyWithRawNumber) { + return internal.RawNumberOf(val), nil + } + fv, ok := jsonwire.ParseFloat(val, 64) + if !ok { + return fv, newUnmarshalErrorAfterWithValue(dec, float64Type, strconv.ErrRange) + } return fv, nil default: panic("BUG: invalid kind: " + k.String()) @@ -70,41 +98,49 @@ func unmarshalValueAny(uo UnmarshalOptions, dec *Decoder) (any, error) { } } -func marshalObjectAny(mo MarshalOptions, enc *Encoder, obj map[string]any) error { +// marshalObjectAny marshals a Go map[string]any as a JSON object +// (or as a JSON null if nil and [jsonflags.FormatNilMapAsNull]). +func marshalObjectAny(enc *jsontext.Encoder, obj map[string]any, mo *jsonopts.Struct) error { // Check for cycles. - if enc.tokens.depth() > startDetectingCyclesAfter { + xe := export.Encoder(enc) + if xe.Tokens.Depth() > startDetectingCyclesAfter { v := reflect.ValueOf(obj) - if err := enc.seenPointers.visit(v); err != nil { - return err + if err := visitPointer(&xe.SeenPointers, v); err != nil { + return newMarshalErrorBefore(enc, mapStringAnyType, err) } - defer enc.seenPointers.leave(v) + defer leavePointer(&xe.SeenPointers, v) } - // Optimize for marshaling an empty map without any preceding whitespace. - if len(obj) == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '{') - enc.buf = append(enc.buf, "{}"...) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + // Handle empty maps. + if len(obj) == 0 { + if mo.Flags.Get(jsonflags.FormatNilMapAsNull) && obj == nil { + return enc.WriteToken(jsontext.Null) + } + // Optimize for marshaling an empty map without any preceding whitespace. + if !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '{'), "{}"...) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() + } + return nil } - return nil } - if err := enc.WriteToken(ObjectStart); err != nil { + if err := enc.WriteToken(jsontext.BeginObject); err != nil { return err } // A Go map guarantees that each entry has a unique key // The only possibility of duplicates is due to invalid UTF-8. - if !enc.options.AllowInvalidUTF8 { - enc.tokens.last.disableNamespace() + if !mo.Flags.Get(jsonflags.AllowInvalidUTF8) { + xe.Tokens.Last.DisableNamespace() } - if !mo.Deterministic || len(obj) <= 1 { + if !mo.Flags.Get(jsonflags.Deterministic) || len(obj) <= 1 { for name, val := range obj { - if err := enc.WriteToken(String(name)); err != nil { + if err := enc.WriteToken(jsontext.String(name)); err != nil { return err } - if err := marshalValueAny(mo, enc, val); err != nil { + if err := marshalValueAny(enc, val, mo); err != nil { return err } } @@ -117,122 +153,133 @@ func marshalObjectAny(mo MarshalOptions, enc *Encoder, obj map[string]any) error } names.Sort() for _, name := range *names { - if err := enc.WriteToken(String(name)); err != nil { + if err := enc.WriteToken(jsontext.String(name)); err != nil { return err } - if err := marshalValueAny(mo, enc, obj[name]); err != nil { + if err := marshalValueAny(enc, obj[name], mo); err != nil { return err } } putStrings(names) } - if err := enc.WriteToken(ObjectEnd); err != nil { + if err := enc.WriteToken(jsontext.EndObject); err != nil { return err } return nil } -func unmarshalObjectAny(uo UnmarshalOptions, dec *Decoder) (map[string]any, error) { - tok, err := dec.ReadToken() - if err != nil { +// unmarshalObjectAny unmarshals a JSON object as a Go map[string]any. +// It panics if not decoding a JSON object. +func unmarshalObjectAny(dec *jsontext.Decoder, uo *jsonopts.Struct) (map[string]any, error) { + switch tok, err := dec.ReadToken(); { + case err != nil: return nil, err + case tok.Kind() != '{': + panic("BUG: invalid kind: " + tok.Kind().String()) } - k := tok.Kind() - switch k { - case 'n': - return nil, nil - case '{': - obj := make(map[string]any) - // A Go map guarantees that each entry has a unique key - // The only possibility of duplicates is due to invalid UTF-8. - if !dec.options.AllowInvalidUTF8 { - dec.tokens.last.disableNamespace() - } - for dec.PeekKind() != '}' { - tok, err := dec.ReadToken() - if err != nil { - return obj, err - } - name := tok.String() + obj := make(map[string]any) + // A Go map guarantees that each entry has a unique key + // The only possibility of duplicates is due to invalid UTF-8. + if !uo.Flags.Get(jsonflags.AllowInvalidUTF8) { + export.Decoder(dec).Tokens.Last.DisableNamespace() + } + var errUnmarshal error + for dec.PeekKind() != '}' { + tok, err := dec.ReadToken() + if err != nil { + return obj, err + } + name := tok.String() - // Manually check for duplicate names. - if _, ok := obj[name]; ok { - name := dec.previousBuffer() - err := &SyntacticError{str: "duplicate name " + string(name) + " in object"} - return obj, err.withOffset(dec.InputOffset() - int64(len(name))) - } + // Manually check for duplicate names. + if _, ok := obj[name]; ok { + // TODO: Unread the object name. + name := export.Decoder(dec).PreviousTokenOrValue() + err := newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(name)) + return obj, err + } - val, err := unmarshalValueAny(uo, dec) - obj[name] = val - if err != nil { + val, err := unmarshalValueAny(dec, uo) + obj[name] = val + if err != nil { + if isFatalError(err, uo.Flags) { return obj, err } + errUnmarshal = cmp.Or(err, errUnmarshal) } - if _, err := dec.ReadToken(); err != nil { - return obj, err - } - return obj, nil } - return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: mapStringAnyType} + if _, err := dec.ReadToken(); err != nil { + return obj, err + } + return obj, errUnmarshal } -func marshalArrayAny(mo MarshalOptions, enc *Encoder, arr []any) error { +// marshalArrayAny marshals a Go []any as a JSON array +// (or as a JSON null if nil and [jsonflags.FormatNilSliceAsNull]). +func marshalArrayAny(enc *jsontext.Encoder, arr []any, mo *jsonopts.Struct) error { // Check for cycles. - if enc.tokens.depth() > startDetectingCyclesAfter { + xe := export.Encoder(enc) + if xe.Tokens.Depth() > startDetectingCyclesAfter { v := reflect.ValueOf(arr) - if err := enc.seenPointers.visit(v); err != nil { - return err + if err := visitPointer(&xe.SeenPointers, v); err != nil { + return newMarshalErrorBefore(enc, sliceAnyType, err) } - defer enc.seenPointers.leave(v) + defer leavePointer(&xe.SeenPointers, v) } - // Optimize for marshaling an empty slice without any preceding whitespace. - if len(arr) == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '[') - enc.buf = append(enc.buf, "[]"...) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + // Handle empty slices. + if len(arr) == 0 { + if mo.Flags.Get(jsonflags.FormatNilSliceAsNull) && arr == nil { + return enc.WriteToken(jsontext.Null) + } + // Optimize for marshaling an empty slice without any preceding whitespace. + if !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '['), "[]"...) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() + } + return nil } - return nil } - if err := enc.WriteToken(ArrayStart); err != nil { + if err := enc.WriteToken(jsontext.BeginArray); err != nil { return err } for _, val := range arr { - if err := marshalValueAny(mo, enc, val); err != nil { + if err := marshalValueAny(enc, val, mo); err != nil { return err } } - if err := enc.WriteToken(ArrayEnd); err != nil { + if err := enc.WriteToken(jsontext.EndArray); err != nil { return err } return nil } -func unmarshalArrayAny(uo UnmarshalOptions, dec *Decoder) ([]any, error) { - tok, err := dec.ReadToken() - if err != nil { +// unmarshalArrayAny unmarshals a JSON array as a Go []any. +// It panics if not decoding a JSON array. +func unmarshalArrayAny(dec *jsontext.Decoder, uo *jsonopts.Struct) ([]any, error) { + switch tok, err := dec.ReadToken(); { + case err != nil: return nil, err + case tok.Kind() != '[': + panic("BUG: invalid kind: " + tok.Kind().String()) } - k := tok.Kind() - switch k { - case 'n': - return nil, nil - case '[': - arr := []any{} - for dec.PeekKind() != ']' { - val, err := unmarshalValueAny(uo, dec) - arr = append(arr, val) - if err != nil { + arr := []any{} + var errUnmarshal error + for dec.PeekKind() != ']' { + val, err := unmarshalValueAny(dec, uo) + arr = append(arr, val) + if err != nil { + if isFatalError(err, uo.Flags) { return arr, err } + errUnmarshal = cmp.Or(errUnmarshal, err) } - if _, err := dec.ReadToken(); err != nil { - return arr, err - } - return arr, nil } - return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: sliceAnyType} + if _, err := dec.ReadToken(); err != nil { + return arr, err + } + return arr, errUnmarshal } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go index fd26eba35..3f21c8d35 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go @@ -6,6 +6,8 @@ package json import ( "bytes" + "cmp" + "encoding" "encoding/base32" "encoding/base64" "encoding/hex" @@ -13,9 +15,16 @@ import ( "fmt" "math" "reflect" - "sort" + "slices" "strconv" + "strings" "sync" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // optimizeCommon specifies whether to use optimizations targeted for certain @@ -25,44 +34,56 @@ const optimizeCommon = true var ( // Most natural Go type that correspond with each JSON type. - anyType = reflect.TypeOf((*any)(nil)).Elem() // JSON value - boolType = reflect.TypeOf((*bool)(nil)).Elem() // JSON bool - stringType = reflect.TypeOf((*string)(nil)).Elem() // JSON string - float64Type = reflect.TypeOf((*float64)(nil)).Elem() // JSON number - mapStringAnyType = reflect.TypeOf((*map[string]any)(nil)).Elem() // JSON object - sliceAnyType = reflect.TypeOf((*[]any)(nil)).Elem() // JSON array - - bytesType = reflect.TypeOf((*[]byte)(nil)).Elem() - emptyStructType = reflect.TypeOf((*struct{})(nil)).Elem() + anyType = reflect.TypeFor[any]() // JSON value + boolType = reflect.TypeFor[bool]() // JSON bool + stringType = reflect.TypeFor[string]() // JSON string + float64Type = reflect.TypeFor[float64]() // JSON number + mapStringAnyType = reflect.TypeFor[map[string]any]() // JSON object + sliceAnyType = reflect.TypeFor[[]any]() // JSON array + + bytesType = reflect.TypeFor[[]byte]() + emptyStructType = reflect.TypeFor[struct{}]() ) const startDetectingCyclesAfter = 1000 -type seenPointers map[typedPointer]struct{} +type seenPointers = map[any]struct{} type typedPointer struct { typ reflect.Type ptr any // always stores unsafe.Pointer, but avoids depending on unsafe + len int // remember slice length to avoid false positives } -// visit visits pointer p of type t, reporting an error if seen before. +// visitPointer visits pointer p of type t, reporting an error if seen before. // If successfully visited, then the caller must eventually call leave. -func (m *seenPointers) visit(v reflect.Value) error { - p := typedPointer{v.Type(), v.UnsafePointer()} +func visitPointer(m *seenPointers, v reflect.Value) error { + p := typedPointer{v.Type(), v.UnsafePointer(), sliceLen(v)} if _, ok := (*m)[p]; ok { - return &SemanticError{action: "marshal", GoType: p.typ, Err: errors.New("encountered a cycle")} + return internal.ErrCycle } if *m == nil { - *m = make(map[typedPointer]struct{}) + *m = make(seenPointers) } (*m)[p] = struct{}{} return nil } -func (m *seenPointers) leave(v reflect.Value) { - p := typedPointer{v.Type(), v.UnsafePointer()} +func leavePointer(m *seenPointers, v reflect.Value) { + p := typedPointer{v.Type(), v.UnsafePointer(), sliceLen(v)} delete(*m, p) } +func sliceLen(v reflect.Value) int { + if v.Kind() == reflect.Slice { + return v.Len() + } + return 0 +} + +func len64[Bytes ~[]byte | ~string](in Bytes) int64 { + return int64(len(in)) +} + func makeDefaultArshaler(t reflect.Type) *arshaler { switch t.Kind() { case reflect.Bool: @@ -71,7 +92,7 @@ func makeDefaultArshaler(t reflect.Type) *arshaler { return makeStringArshaler(t) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return makeIntArshaler(t) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return makeUintArshaler(t) case reflect.Float32, reflect.Float64: return makeFloatArshaler(t) @@ -81,13 +102,13 @@ func makeDefaultArshaler(t reflect.Type) *arshaler { return makeStructArshaler(t) case reflect.Slice: fncs := makeSliceArshaler(t) - if t.AssignableTo(bytesType) { + if t.Elem().Kind() == reflect.Uint8 { return makeBytesArshaler(t, fncs) } return fncs case reflect.Array: fncs := makeArrayArshaler(t) - if reflect.SliceOf(t.Elem()).AssignableTo(bytesType) { + if t.Elem().Kind() == reflect.Uint8 { return makeBytesArshaler(t, fncs) } return fncs @@ -102,31 +123,35 @@ func makeDefaultArshaler(t reflect.Type) *arshaler { func makeBoolArshaler(t reflect.Type) *arshaler { var fncs arshaler - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } // Optimize for marshaling without preceding whitespace. - if optimizeCommon && !enc.options.multiline && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, 't') - if va.Bool() { - enc.buf = append(enc.buf, "true"...) - } else { - enc.buf = append(enc.buf, "false"...) - } - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace|jsonflags.StringifyBoolsAndStrings) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = strconv.AppendBool(xe.Tokens.MayAppendDelim(xe.Buf, 't'), va.Bool()) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() } return nil } - return enc.WriteToken(Bool(va.Bool())) + if mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) { + if va.Bool() { + return enc.WriteToken(jsontext.String("true")) + } else { + return enc.WriteToken(jsontext.String("false")) + } + } + return enc.WriteToken(jsontext.Bool(va.Bool())) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) } tok, err := dec.ReadToken() if err != nil { @@ -135,187 +160,267 @@ func makeBoolArshaler(t reflect.Type) *arshaler { k := tok.Kind() switch k { case 'n': - va.SetBool(false) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetBool(false) + } return nil case 't', 'f': - va.SetBool(tok.Bool()) - return nil + if !uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) { + va.SetBool(tok.Bool()) + return nil + } + case '"': + if uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) { + switch tok.String() { + case "true": + va.SetBool(true) + case "false": + va.SetBool(false) + default: + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && tok.String() == "null" { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetBool(false) + } + return nil + } + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax) + } + return nil + } } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfterWithSkipping(dec, t, nil) } return &fncs } func makeStringArshaler(t reflect.Type) *arshaler { var fncs arshaler - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) + } + + // Optimize for marshaling without preceding whitespace. + s := va.String() + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace|jsonflags.StringifyBoolsAndStrings) && !xe.Tokens.Last.NeedObjectName() { + b := xe.Buf + b = xe.Tokens.MayAppendDelim(b, '"') + b, err := jsonwire.AppendQuote(b, s, &mo.Flags) + if err == nil { + xe.Buf = b + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() + } + return nil + } + // Otherwise, the string contains invalid UTF-8, + // so let the logic below construct the proper error. } - return enc.WriteToken(String(va.String())) + + if mo.Flags.Get(jsonflags.StringifyBoolsAndStrings) { + b, err := jsonwire.AppendQuote(nil, s, &mo.Flags) + if err != nil { + return newMarshalErrorBefore(enc, t, &jsontext.SyntacticError{Err: err}) + } + q, err := jsontext.AppendQuote(nil, b) + if err != nil { + panic("BUG: second AppendQuote should never fail: " + err.Error()) + } + return enc.WriteValue(q) + } + return enc.WriteToken(jsontext.String(s)) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) } - var flags valueFlags - val, err := dec.readValue(&flags) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': - va.SetString("") + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetString("") + } return nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) - if dec.stringCache == nil { - dec.stringCache = new(stringCache) + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if uo.Flags.Get(jsonflags.StringifyBoolsAndStrings) { + val, err = jsontext.AppendUnquote(nil, val) + if err != nil { + return newUnmarshalErrorAfter(dec, t, err) + } + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && string(val) == "null" { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetString("") + } + return nil + } + } + if xd.StringCache == nil { + xd.StringCache = new(stringCache) } - str := dec.stringCache.make(val) + str := makeString(xd.StringCache, val) va.SetString(str) return nil } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfter(dec, t, nil) } return &fncs } var ( - encodeBase16 = func(dst, src []byte) { hex.Encode(dst, src) } - encodeBase32 = base32.StdEncoding.Encode - encodeBase32Hex = base32.HexEncoding.Encode - encodeBase64 = base64.StdEncoding.Encode - encodeBase64URL = base64.URLEncoding.Encode - encodedLenBase16 = hex.EncodedLen - encodedLenBase32 = base32.StdEncoding.EncodedLen - encodedLenBase32Hex = base32.HexEncoding.EncodedLen - encodedLenBase64 = base64.StdEncoding.EncodedLen - encodedLenBase64URL = base64.URLEncoding.EncodedLen - decodeBase16 = hex.Decode - decodeBase32 = base32.StdEncoding.Decode - decodeBase32Hex = base32.HexEncoding.Decode - decodeBase64 = base64.StdEncoding.Decode - decodeBase64URL = base64.URLEncoding.Decode - decodedLenBase16 = hex.DecodedLen - decodedLenBase32 = base32.StdEncoding.WithPadding(base32.NoPadding).DecodedLen - decodedLenBase32Hex = base32.HexEncoding.WithPadding(base32.NoPadding).DecodedLen - decodedLenBase64 = base64.StdEncoding.WithPadding(base64.NoPadding).DecodedLen - decodedLenBase64URL = base64.URLEncoding.WithPadding(base64.NoPadding).DecodedLen + appendEncodeBase16 = hex.AppendEncode + appendEncodeBase32 = base32.StdEncoding.AppendEncode + appendEncodeBase32Hex = base32.HexEncoding.AppendEncode + appendEncodeBase64 = base64.StdEncoding.AppendEncode + appendEncodeBase64URL = base64.URLEncoding.AppendEncode + encodedLenBase16 = hex.EncodedLen + encodedLenBase32 = base32.StdEncoding.EncodedLen + encodedLenBase32Hex = base32.HexEncoding.EncodedLen + encodedLenBase64 = base64.StdEncoding.EncodedLen + encodedLenBase64URL = base64.URLEncoding.EncodedLen + appendDecodeBase16 = hex.AppendDecode + appendDecodeBase32 = base32.StdEncoding.AppendDecode + appendDecodeBase32Hex = base32.HexEncoding.AppendDecode + appendDecodeBase64 = base64.StdEncoding.AppendDecode + appendDecodeBase64URL = base64.URLEncoding.AppendDecode ) func makeBytesArshaler(t reflect.Type, fncs *arshaler) *arshaler { - // NOTE: This handles both []byte and [N]byte. - marshalDefault := fncs.marshal - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - encode, encodedLen := encodeBase64, encodedLenBase64 - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - switch mo.format { + // NOTE: This handles both []~byte and [N]~byte. + // The v2 default is to treat a []namedByte as equivalent to []T + // since being able to convert []namedByte to []byte relies on + // dubious Go reflection behavior (see https://go.dev/issue/24746). + // For v1 emulation, we use jsonflags.FormatBytesWithLegacySemantics + // to forcibly treat []namedByte as a []byte. + marshalArray := fncs.marshal + isNamedByte := t.Elem().PkgPath() != "" + hasMarshaler := implementsAny(t.Elem(), allMarshalerTypes...) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + if !mo.Flags.Get(jsonflags.FormatBytesWithLegacySemantics) && isNamedByte { + return marshalArray(enc, va, mo) // treat as []T or [N]T + } + xe := export.Encoder(enc) + appendEncode := appendEncodeBase64 + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + switch mo.Format { case "base64": - encode, encodedLen = encodeBase64, encodedLenBase64 + appendEncode = appendEncodeBase64 case "base64url": - encode, encodedLen = encodeBase64URL, encodedLenBase64URL + appendEncode = appendEncodeBase64URL case "base32": - encode, encodedLen = encodeBase32, encodedLenBase32 + appendEncode = appendEncodeBase32 case "base32hex": - encode, encodedLen = encodeBase32Hex, encodedLenBase32Hex + appendEncode = appendEncodeBase32Hex case "base16", "hex": - encode, encodedLen = encodeBase16, encodedLenBase16 + appendEncode = appendEncodeBase16 case "array": - mo.format = "" - return marshalDefault(mo, enc, va) + mo.Format = "" + return marshalArray(enc, va, mo) default: - return newInvalidFormatError("marshal", t, mo.format) + return newInvalidFormatError(enc, t) } + } else if mo.Flags.Get(jsonflags.FormatByteArrayAsArray) && va.Kind() == reflect.Array { + return marshalArray(enc, va, mo) + } else if mo.Flags.Get(jsonflags.FormatBytesWithLegacySemantics) && hasMarshaler { + return marshalArray(enc, va, mo) } - val := enc.UnusedBuffer() - b := va.Bytes() - n := len(`"`) + encodedLen(len(b)) + len(`"`) - if cap(val) < n { - val = make([]byte, n) - } else { - val = val[:n] + if mo.Flags.Get(jsonflags.FormatNilSliceAsNull) && va.Kind() == reflect.Slice && va.IsNil() { + // TODO: Provide a "emitempty" format override? + return enc.WriteToken(jsontext.Null) } - val[0] = '"' - encode(val[len(`"`):len(val)-len(`"`)], b) - val[len(val)-1] = '"' - return enc.WriteValue(val) + return xe.AppendRaw('"', true, func(b []byte) ([]byte, error) { + return appendEncode(b, va.Bytes()), nil + }) } - unmarshalDefault := fncs.unmarshal - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - decode, decodedLen, encodedLen := decodeBase64, decodedLenBase64, encodedLenBase64 - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - switch uo.format { + unmarshalArray := fncs.unmarshal + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + if !uo.Flags.Get(jsonflags.FormatBytesWithLegacySemantics) && isNamedByte { + return unmarshalArray(dec, va, uo) // treat as []T or [N]T + } + xd := export.Decoder(dec) + appendDecode, encodedLen := appendDecodeBase64, encodedLenBase64 + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + switch uo.Format { case "base64": - decode, decodedLen, encodedLen = decodeBase64, decodedLenBase64, encodedLenBase64 + appendDecode, encodedLen = appendDecodeBase64, encodedLenBase64 case "base64url": - decode, decodedLen, encodedLen = decodeBase64URL, decodedLenBase64URL, encodedLenBase64URL + appendDecode, encodedLen = appendDecodeBase64URL, encodedLenBase64URL case "base32": - decode, decodedLen, encodedLen = decodeBase32, decodedLenBase32, encodedLenBase32 + appendDecode, encodedLen = appendDecodeBase32, encodedLenBase32 case "base32hex": - decode, decodedLen, encodedLen = decodeBase32Hex, decodedLenBase32Hex, encodedLenBase32Hex + appendDecode, encodedLen = appendDecodeBase32Hex, encodedLenBase32Hex case "base16", "hex": - decode, decodedLen, encodedLen = decodeBase16, decodedLenBase16, encodedLenBase16 + appendDecode, encodedLen = appendDecodeBase16, encodedLenBase16 case "array": - uo.format = "" - return unmarshalDefault(uo, dec, va) + uo.Format = "" + return unmarshalArray(dec, va, uo) default: - return newInvalidFormatError("unmarshal", t, uo.format) + return newInvalidFormatError(dec, t) } + } else if uo.Flags.Get(jsonflags.FormatByteArrayAsArray) && va.Kind() == reflect.Array { + return unmarshalArray(dec, va, uo) + } else if uo.Flags.Get(jsonflags.FormatBytesWithLegacySemantics) && dec.PeekKind() == '[' { + return unmarshalArray(dec, va, uo) } - var flags valueFlags - val, err := dec.readValue(&flags) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': - va.Set(reflect.Zero(t)) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) || va.Kind() != reflect.Array { + va.SetZero() + } return nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) - - // For base64 and base32, decodedLen computes the maximum output size - // when given the original input size. To compute the exact size, - // adjust the input size by excluding trailing padding characters. - // This is unnecessary for base16, but also harmless. - n := len(val) - for n > 0 && val[n-1] == '=' { - n-- - } - n = decodedLen(n) - b := va.Bytes() - if va.Kind() == reflect.Array { - if n != len(b) { - err := fmt.Errorf("decoded base64 length of %d mismatches array length of %d", n, len(b)) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} - } - } else { - if b == nil || cap(b) < n { - b = make([]byte, n) - } else { - b = b[:n] - } + // NOTE: The v2 default is to strictly comply with RFC 4648. + // Section 3.2 specifies that padding is required. + // Section 3.3 specifies that non-alphabet characters + // (e.g., '\r' or '\n') must be rejected. + // Section 3.5 specifies that unnecessary non-zero bits in + // the last quantum may be rejected. Since this is optional, + // we do not reject such inputs. + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + b, err := appendDecode(va.Bytes()[:0], val) + if err != nil { + return newUnmarshalErrorAfter(dec, t, err) } - n2, err := decode(b, val) - if err == nil && len(val) != encodedLen(n2) { + if len(val) != encodedLen(len(b)) && !uo.Flags.Get(jsonflags.ParseBytesWithLooseRFC4648) { // TODO(https://go.dev/issue/53845): RFC 4648, section 3.3, // specifies that non-alphabet characters must be rejected. // Unfortunately, the "base32" and "base64" packages allow // '\r' and '\n' characters by default. - err = errors.New("illegal data at input byte " + strconv.Itoa(bytes.IndexAny(val, "\r\n"))) - } - if err != nil { - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + i := bytes.IndexAny(val, "\r\n") + err := fmt.Errorf("illegal character %s at offset %d", jsonwire.QuoteRune(val[i:]), i) + return newUnmarshalErrorAfter(dec, t, err) } - if va.Kind() == reflect.Slice { + + if va.Kind() == reflect.Array { + dst := va.Bytes() + clear(dst[copy(dst, b):]) // noop if len(b) <= len(dst) + if len(b) != len(dst) && !uo.Flags.Get(jsonflags.UnmarshalArrayFromAnyLength) { + err := fmt.Errorf("decoded length of %d mismatches array length of %d", len(b), len(dst)) + return newUnmarshalErrorAfter(dec, t, err) + } + } else { + if b == nil { + b = []byte{} + } va.SetBytes(b) } return nil } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfter(dec, t, nil) } return fncs } @@ -323,64 +428,77 @@ func makeBytesArshaler(t reflect.Type, fncs *arshaler) *arshaler { func makeIntArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } // Optimize for marshaling without preceding whitespace or string escaping. - if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') - enc.buf = strconv.AppendInt(enc.buf, va.Int(), 10) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace|jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = strconv.AppendInt(xe.Tokens.MayAppendDelim(xe.Buf, '0'), va.Int(), 10) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() } return nil } - x := math.Float64frombits(uint64(va.Int())) - return enc.writeNumber(x, rawIntNumber, mo.StringifyNumbers) + k := stringOrNumberKind(xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers)) + return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) { + return strconv.AppendInt(b, va.Int(), 10), nil + }) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) - } - var flags valueFlags - val, err := dec.readValue(&flags) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) + } + stringify := xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': - va.SetInt(0) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetInt(0) + } return nil case '"': - if !uo.StringifyNumbers { + if !stringify { break } - val = unescapeStringMayCopy(val, flags.isVerbatim()) + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && string(val) == "null" { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetInt(0) + } + return nil + } fallthrough case '0': + if stringify && k == '0' { + break + } var negOffset int - neg := val[0] == '-' + neg := len(val) > 0 && val[0] == '-' if neg { negOffset = 1 } - n, ok := parseDecUint(val[negOffset:]) + n, ok := jsonwire.ParseUint(val[negOffset:]) maxInt := uint64(1) << (bits - 1) overflow := (neg && n > maxInt) || (!neg && n > maxInt-1) if !ok { if n != math.MaxUint64 { - err := fmt.Errorf("cannot parse %q as signed integer: %w", val, strconv.ErrSyntax) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax) } overflow = true } if overflow { - err := fmt.Errorf("cannot parse %q as signed integer: %w", val, strconv.ErrRange) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange) } if neg { va.SetInt(int64(-n)) @@ -389,7 +507,7 @@ func makeIntArshaler(t reflect.Type) *arshaler { } return nil } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfter(dec, t, nil) } return &fncs } @@ -397,64 +515,77 @@ func makeIntArshaler(t reflect.Type) *arshaler { func makeUintArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } // Optimize for marshaling without preceding whitespace or string escaping. - if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') - enc.buf = strconv.AppendUint(enc.buf, va.Uint(), 10) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace|jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = strconv.AppendUint(xe.Tokens.MayAppendDelim(xe.Buf, '0'), va.Uint(), 10) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() } return nil } - x := math.Float64frombits(va.Uint()) - return enc.writeNumber(x, rawUintNumber, mo.StringifyNumbers) + k := stringOrNumberKind(xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers)) + return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) { + return strconv.AppendUint(b, va.Uint(), 10), nil + }) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) - } - var flags valueFlags - val, err := dec.readValue(&flags) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) + } + stringify := xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': - va.SetUint(0) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetUint(0) + } return nil case '"': - if !uo.StringifyNumbers { + if !stringify { break } - val = unescapeStringMayCopy(val, flags.isVerbatim()) + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && string(val) == "null" { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetUint(0) + } + return nil + } fallthrough case '0': - n, ok := parseDecUint(val) + if stringify && k == '0' { + break + } + n, ok := jsonwire.ParseUint(val) maxUint := uint64(1) << bits overflow := n > maxUint-1 if !ok { if n != math.MaxUint64 { - err := fmt.Errorf("cannot parse %q as unsigned integer: %w", val, strconv.ErrSyntax) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax) } overflow = true } if overflow { - err := fmt.Errorf("cannot parse %q as unsigned integer: %w", val, strconv.ErrRange) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange) } va.SetUint(n) return nil } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfter(dec, t, nil) } return &fncs } @@ -462,59 +593,66 @@ func makeUintArshaler(t reflect.Type) *arshaler { func makeFloatArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) var allowNonFinite bool - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - if mo.format == "nonfinite" { + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + if mo.Format == "nonfinite" { allowNonFinite = true } else { - return newInvalidFormatError("marshal", t, mo.format) + return newInvalidFormatError(enc, t) } } fv := va.Float() if math.IsNaN(fv) || math.IsInf(fv, 0) { if !allowNonFinite { - err := fmt.Errorf("invalid value: %v", fv) - return &SemanticError{action: "marshal", GoType: t, Err: err} + err := fmt.Errorf("unsupported value: %v", fv) + return newMarshalErrorBefore(enc, t, err) } - return enc.WriteToken(Float(fv)) + return enc.WriteToken(jsontext.Float(fv)) } // Optimize for marshaling without preceding whitespace or string escaping. - if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') - enc.buf = appendNumber(enc.buf, fv, bits) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace|jsonflags.StringifyNumbers) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = jsonwire.AppendFloat(xe.Tokens.MayAppendDelim(xe.Buf, '0'), fv, bits) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() } return nil } - return enc.writeNumber(fv, bits, mo.StringifyNumbers) + k := stringOrNumberKind(xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers)) + return xe.AppendRaw(k, true, func(b []byte) ([]byte, error) { + return jsonwire.AppendFloat(b, va.Float(), bits), nil + }) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) var allowNonFinite bool - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - if uo.format == "nonfinite" { + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + if uo.Format == "nonfinite" { allowNonFinite = true } else { - return newInvalidFormatError("unmarshal", t, uo.format) + return newInvalidFormatError(dec, t) } } - var flags valueFlags - val, err := dec.readValue(&flags) + stringify := xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': - va.SetFloat(0) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetFloat(0) + } return nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) if allowNonFinite { switch string(val) { case "NaN": @@ -528,24 +666,31 @@ func makeFloatArshaler(t reflect.Type) *arshaler { return nil } } - if !uo.StringifyNumbers { + if !stringify { break } - if n, err := consumeNumber(val); n != len(val) || err != nil { - err := fmt.Errorf("cannot parse %q as JSON number: %w", val, strconv.ErrSyntax) - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && string(val) == "null" { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetFloat(0) + } + return nil + } + if n, err := jsonwire.ConsumeNumber(val); n != len(val) || err != nil { + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrSyntax) } fallthrough case '0': - // NOTE: Floating-point parsing is by nature a lossy operation. - // We never report an overflow condition since we can always - // round the input to the closest representable finite value. - // For extremely large numbers, the closest value is ±MaxFloat. - fv, _ := parseFloat(val, bits) + if stringify && k == '0' { + break + } + fv, ok := jsonwire.ParseFloat(val, bits) va.SetFloat(fv) + if !ok { + return newUnmarshalErrorAfterWithValue(dec, t, strconv.ErrRange) + } return nil } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfter(dec, t, nil) } return &fncs } @@ -568,54 +713,61 @@ func makeMapArshaler(t reflect.Type) *arshaler { keyFncs = lookupArshaler(t.Key()) valFncs = lookupArshaler(t.Elem()) } - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { + nillableLegacyKey := t.Key().Kind() == reflect.Pointer && + implementsAny(t.Key(), textMarshalerType, textAppenderType) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { // Check for cycles. - if enc.tokens.depth() > startDetectingCyclesAfter { - if err := enc.seenPointers.visit(va.Value); err != nil { - return err - } - defer enc.seenPointers.leave(va.Value) - } - - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - if mo.format == "emitnull" { - if va.IsNil() { - return enc.WriteToken(Null) - } - mo.format = "" - } else { - return newInvalidFormatError("marshal", t, mo.format) + xe := export.Encoder(enc) + if xe.Tokens.Depth() > startDetectingCyclesAfter { + if err := visitPointer(&xe.SeenPointers, va.Value); err != nil { + return newMarshalErrorBefore(enc, t, err) + } + defer leavePointer(&xe.SeenPointers, va.Value) + } + + emitNull := mo.Flags.Get(jsonflags.FormatNilMapAsNull) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + switch mo.Format { + case "emitnull": + emitNull = true + mo.Format = "" + case "emitempty": + emitNull = false + mo.Format = "" + default: + return newInvalidFormatError(enc, t) } } - // Optimize for marshaling an empty map without any preceding whitespace. + // Handle empty maps. n := va.Len() - if optimizeCommon && n == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '{') - enc.buf = append(enc.buf, "{}"...) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if n == 0 { + if emitNull && va.IsNil() { + return enc.WriteToken(jsontext.Null) + } + // Optimize for marshaling an empty map without any preceding whitespace. + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '{'), "{}"...) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() + } + return nil } - return nil } once.Do(init) - if err := enc.WriteToken(ObjectStart); err != nil { + if err := enc.WriteToken(jsontext.BeginObject); err != nil { return err } if n > 0 { - // Handle maps with numeric key types by stringifying them. - mko := mo - mko.StringifyNumbers = true - nonDefaultKey := keyFncs.nonDefault marshalKey := keyFncs.marshal marshalVal := valFncs.marshal if mo.Marshalers != nil { var ok bool - marshalKey, ok = mo.Marshalers.lookup(marshalKey, t.Key()) - marshalVal, _ = mo.Marshalers.lookup(marshalVal, t.Elem()) + marshalKey, ok = mo.Marshalers.(*Marshalers).lookup(marshalKey, t.Key()) + marshalVal, _ = mo.Marshalers.(*Marshalers).lookup(marshalVal, t.Elem()) nonDefaultKey = nonDefaultKey || ok } k := newAddressableValue(t.Key()) @@ -624,22 +776,29 @@ func makeMapArshaler(t reflect.Type) *arshaler { // A Go map guarantees that each entry has a unique key. // As such, disable the expensive duplicate name check if we know // that every Go key will serialize as a unique JSON string. - if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), enc.options.AllowInvalidUTF8) { - enc.tokens.last.disableNamespace() + if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), mo.Flags.Get(jsonflags.AllowInvalidUTF8)) { + xe.Tokens.Last.DisableNamespace() } switch { - case !mo.Deterministic || n <= 1: + case !mo.Flags.Get(jsonflags.Deterministic) || n <= 1: for iter := va.Value.MapRange(); iter.Next(); { k.SetIterKey(iter) - if err := marshalKey(mko, enc, k); err != nil { - // TODO: If err is errMissingName, then wrap it as a - // SemanticError since this key type cannot be serialized - // as a JSON string. - return err + err := marshalKey(enc, k, mo) + if err != nil { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + errors.Is(err, jsontext.ErrNonStringName) && nillableLegacyKey && k.IsNil() { + err = enc.WriteToken(jsontext.String("")) + } + if err != nil { + if serr, ok := err.(*jsontext.SyntacticError); ok && serr.Err == jsontext.ErrNonStringName { + err = newMarshalErrorBefore(enc, k.Type(), err) + } + return err + } } v.SetIterValue(iter) - if err := marshalVal(mo, enc, v); err != nil { + if err := marshalVal(enc, v, mo); err != nil { return err } } @@ -651,13 +810,13 @@ func makeMapArshaler(t reflect.Type) *arshaler { } names.Sort() for _, name := range *names { - if err := enc.WriteToken(String(name)); err != nil { + if err := enc.WriteToken(jsontext.String(name)); err != nil { return err } // TODO(https://go.dev/issue/57061): Use v.SetMapIndexOf. k.SetString(name) v.Set(va.MapIndex(k.Value)) - if err := marshalVal(mo, enc, v); err != nil { + if err := marshalVal(enc, v, mo); err != nil { return err } } @@ -666,52 +825,62 @@ func makeMapArshaler(t reflect.Type) *arshaler { type member struct { name string // unquoted name key addressableValue + val addressableValue } members := make([]member, n) keys := reflect.MakeSlice(reflect.SliceOf(t.Key()), n, n) + vals := reflect.MakeSlice(reflect.SliceOf(t.Elem()), n, n) for i, iter := 0, va.Value.MapRange(); i < n && iter.Next(); i++ { // Marshal the member name. - k := addressableValue{keys.Index(i)} // indexed slice element is always addressable + k := addressableValue{keys.Index(i), true} // indexed slice element is always addressable k.SetIterKey(iter) - if err := marshalKey(mko, enc, k); err != nil { - // TODO: If err is errMissingName, then wrap it as a - // SemanticError since this key type cannot be serialized - // as a JSON string. - return err + v := addressableValue{vals.Index(i), true} // indexed slice element is always addressable + v.SetIterValue(iter) + err := marshalKey(enc, k, mo) + if err != nil { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + errors.Is(err, jsontext.ErrNonStringName) && nillableLegacyKey && k.IsNil() { + err = enc.WriteToken(jsontext.String("")) + } + if err != nil { + if serr, ok := err.(*jsontext.SyntacticError); ok && serr.Err == jsontext.ErrNonStringName { + err = newMarshalErrorBefore(enc, k.Type(), err) + } + return err + } } - name := enc.unwriteOnlyObjectMemberName() - members[i] = member{name, k} + name := xe.UnwriteOnlyObjectMemberName() + members[i] = member{name, k, v} } // TODO: If AllowDuplicateNames is enabled, then sort according // to reflect.Value as well if the names are equal. // See internal/fmtsort. - // TODO(https://go.dev/issue/47619): Use slices.SortFunc instead. - sort.Slice(members, func(i, j int) bool { - return lessUTF16(members[i].name, members[j].name) + slices.SortFunc(members, func(x, y member) int { + return strings.Compare(x.name, y.name) }) for _, member := range members { - if err := enc.WriteToken(String(member.name)); err != nil { + if err := enc.WriteToken(jsontext.String(member.name)); err != nil { return err } - // TODO(https://go.dev/issue/57061): Use v.SetMapIndexOf. - v.Set(va.MapIndex(member.key.Value)) - if err := marshalVal(mo, enc, v); err != nil { + if err := marshalVal(enc, member.val, mo); err != nil { return err } } } } - if err := enc.WriteToken(ObjectEnd); err != nil { + if err := enc.WriteToken(jsontext.EndObject); err != nil { return err } return nil } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - if uo.format == "emitnull" { - uo.format = "" // only relevant for marshaling - } else { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + switch uo.Format { + case "emitnull", "emitempty": + uo.Format = "" // only relevant for marshaling + default: + return newInvalidFormatError(dec, t) } } tok, err := dec.ReadToken() @@ -721,7 +890,7 @@ func makeMapArshaler(t reflect.Type) *arshaler { k := tok.Kind() switch k { case 'n': - va.Set(reflect.Zero(t)) + va.SetZero() return nil case '{': once.Do(init) @@ -729,17 +898,13 @@ func makeMapArshaler(t reflect.Type) *arshaler { va.Set(reflect.MakeMap(t)) } - // Handle maps with numeric key types by stringifying them. - uko := uo - uko.StringifyNumbers = true - nonDefaultKey := keyFncs.nonDefault unmarshalKey := keyFncs.unmarshal unmarshalVal := valFncs.unmarshal if uo.Unmarshalers != nil { var ok bool - unmarshalKey, ok = uo.Unmarshalers.lookup(unmarshalKey, t.Key()) - unmarshalVal, _ = uo.Unmarshalers.lookup(unmarshalVal, t.Elem()) + unmarshalKey, ok = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshalKey, t.Key()) + unmarshalVal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshalVal, t.Elem()) nonDefaultKey = nonDefaultKey || ok } k := newAddressableValue(t.Key()) @@ -751,8 +916,8 @@ func makeMapArshaler(t reflect.Type) *arshaler { // will be rejected as duplicates since they semantically refer // to the same Go value. This is an unusual interaction // between syntax and semantics, but is more correct. - if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), dec.options.AllowInvalidUTF8) { - dec.tokens.last.disableNamespace() + if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), uo.Flags.Get(jsonflags.AllowInvalidUTF8)) { + xd.Tokens.Last.DisableNamespace() } // In the rare case where the map is not already empty, @@ -760,46 +925,72 @@ func makeMapArshaler(t reflect.Type) *arshaler { // since existing presence alone is insufficient to indicate // whether the input had a duplicate name. var seen reflect.Value - if !dec.options.AllowDuplicateNames && va.Len() > 0 { + if !uo.Flags.Get(jsonflags.AllowDuplicateNames) && va.Len() > 0 { seen = reflect.MakeMap(reflect.MapOf(k.Type(), emptyStructType)) } + var errUnmarshal error for dec.PeekKind() != '}' { - k.Set(reflect.Zero(t.Key())) - if err := unmarshalKey(uko, dec, k); err != nil { - return err + // Unmarshal the map entry key. + k.SetZero() + err := unmarshalKey(dec, k, uo) + if err != nil { + if isFatalError(err, uo.Flags) { + return err + } + if err := dec.SkipValue(); err != nil { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) + continue } if k.Kind() == reflect.Interface && !k.IsNil() && !k.Elem().Type().Comparable() { - err := fmt.Errorf("invalid incomparable key type %v", k.Elem().Type()) - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + err := newUnmarshalErrorAfter(dec, t, fmt.Errorf("invalid incomparable key type %v", k.Elem().Type())) + if !uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err + } + if err2 := dec.SkipValue(); err2 != nil { + return err2 + } + errUnmarshal = cmp.Or(errUnmarshal, err) + continue } + // Check if a pre-existing map entry value exists for this key. if v2 := va.MapIndex(k.Value); v2.IsValid() { - if !dec.options.AllowDuplicateNames && (!seen.IsValid() || seen.MapIndex(k.Value).IsValid()) { + if !uo.Flags.Get(jsonflags.AllowDuplicateNames) && (!seen.IsValid() || seen.MapIndex(k.Value).IsValid()) { // TODO: Unread the object name. - name := dec.previousBuffer() - err := &SyntacticError{str: "duplicate name " + string(name) + " in object"} - return err.withOffset(dec.InputOffset() - int64(len(name))) + name := xd.PreviousTokenOrValue() + return newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(name)) + } + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + v.Set(v2) + } else { + v.SetZero() } - v.Set(v2) } else { - v.Set(reflect.Zero(v.Type())) + v.SetZero() } - err := unmarshalVal(uo, dec, v) + + // Unmarshal the map entry value. + err = unmarshalVal(dec, v, uo) va.SetMapIndex(k.Value, v.Value) if seen.IsValid() { seen.SetMapIndex(k.Value, reflect.Zero(emptyStructType)) } if err != nil { - return err + if isFatalError(err, uo.Flags) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } } if _, err := dec.ReadToken(); err != nil { return err } - return nil + return errUnmarshal } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfterWithSkipping(dec, t, nil) } return &fncs } @@ -812,7 +1003,7 @@ func mapKeyWithUniqueRepresentation(k reflect.Kind, allowInvalidUTF8 bool) bool switch k { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return true case reflect.String: // For strings, we have to be careful since names with invalid UTF-8 @@ -825,6 +1016,8 @@ func mapKeyWithUniqueRepresentation(k reflect.Kind, allowInvalidUTF8 bool) bool } } +var errNilField = errors.New("cannot set embedded pointer to unexported struct type") + func makeStructArshaler(t reflect.Type) *arshaler { // NOTE: The logic below disables namespaces for tracking duplicate names // and does the tracking locally with an efficient bit-set based on which @@ -839,27 +1032,26 @@ func makeStructArshaler(t reflect.Type) *arshaler { init := func() { fields, errInit = makeStructFields(t) } - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } once.Do(init) - if errInit != nil { - err := *errInit // shallow copy SemanticError - err.action = "marshal" - return &err + if errInit != nil && !mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return newMarshalErrorBefore(enc, errInit.GoType, errInit.Err) } - if err := enc.WriteToken(ObjectStart); err != nil { + if err := enc.WriteToken(jsontext.BeginObject); err != nil { return err } var seenIdxs uintSet prevIdx := -1 - enc.tokens.last.disableNamespace() // we manually ensure unique names below + xe.Tokens.Last.DisableNamespace() // we manually ensure unique names below for i := range fields.flattened { f := &fields.flattened[i] - v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable - if len(f.index) > 1 { - v = v.fieldByIndex(f.index[1:], false) + v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable + if len(f.index) > 0 { + v = v.fieldByIndex(f.index, false) if !v.IsValid() { continue // implies a nil inlined field } @@ -867,7 +1059,13 @@ func makeStructArshaler(t reflect.Type) *arshaler { // OmitZero skips the field if the Go value is zero, // which we can determine up front without calling the marshaler. - if f.omitzero && ((f.isZero == nil && v.IsZero()) || (f.isZero != nil && f.isZero(v))) { + if (f.omitzero || mo.Flags.Get(jsonflags.OmitZeroStructFields)) && + ((f.isZero == nil && v.IsZero()) || (f.isZero != nil && f.isZero(v))) { + continue + } + + // Check for the legacy definition of omitempty. + if f.omitempty && mo.Flags.Get(jsonflags.OmitEmptyWithLegacySemantics) && isLegacyEmpty(v) { continue } @@ -875,14 +1073,15 @@ func makeStructArshaler(t reflect.Type) *arshaler { nonDefault := f.fncs.nonDefault if mo.Marshalers != nil { var ok bool - marshal, ok = mo.Marshalers.lookup(marshal, f.typ) + marshal, ok = mo.Marshalers.(*Marshalers).lookup(marshal, f.typ) nonDefault = nonDefault || ok } // OmitEmpty skips the field if the marshaled JSON value is empty, // which we can know up front if there are no custom marshalers, // otherwise we must marshal the value and unwrite it if empty. - if f.omitempty && !nonDefault && f.isEmpty != nil && f.isEmpty(v) { + if f.omitempty && !mo.Flags.Get(jsonflags.OmitEmptyWithLegacySemantics) && + !nonDefault && f.isEmpty != nil && f.isEmpty(v) { continue // fast path for omitempty } @@ -898,50 +1097,60 @@ func makeStructArshaler(t reflect.Type) *arshaler { // 5. There is no possibility of an error occurring. if optimizeCommon { // Append any delimiters or optional whitespace. - if enc.tokens.last.length() > 0 { - enc.buf = append(enc.buf, ',') + b := xe.Buf + if xe.Tokens.Last.Length() > 0 { + b = append(b, ',') + if mo.Flags.Get(jsonflags.SpaceAfterComma) { + b = append(b, ' ') + } } - if enc.options.multiline { - enc.buf = enc.appendIndent(enc.buf, enc.tokens.needIndent('"')) + if mo.Flags.Get(jsonflags.Multiline) { + b = xe.AppendIndent(b, xe.Tokens.NeedIndent('"')) } // Append the token to the output and to the state machine. - n0 := len(enc.buf) // offset before calling appendString - if enc.options.EscapeRune == nil { - enc.buf = append(enc.buf, f.quotedName...) + n0 := len(b) // offset before calling AppendQuote + if !f.nameNeedEscape { + b = append(b, f.quotedName...) } else { - enc.buf, _ = appendString(enc.buf, f.name, false, enc.options.EscapeRune) - } - if !enc.options.AllowDuplicateNames { - enc.names.replaceLastQuotedOffset(n0) + b, _ = jsonwire.AppendQuote(b, f.name, &mo.Flags) } - enc.tokens.last.increment() + xe.Buf = b + xe.Names.ReplaceLastQuotedOffset(n0) + xe.Tokens.Last.Increment() } else { - if err := enc.WriteToken(String(f.name)); err != nil { + if err := enc.WriteToken(jsontext.String(f.name)); err != nil { return err } } // Write the object member value. - mo2 := mo + flagsOriginal := mo.Flags if f.string { - mo2.StringifyNumbers = true + if !mo.Flags.Get(jsonflags.StringifyWithLegacySemantics) { + mo.Flags.Set(jsonflags.StringifyNumbers | 1) + } else if canLegacyStringify(f.typ) { + mo.Flags.Set(jsonflags.StringifyNumbers | jsonflags.StringifyBoolsAndStrings | 1) + } } if f.format != "" { - mo2.formatDepth = enc.tokens.depth() - mo2.format = f.format + mo.FormatDepth = xe.Tokens.Depth() + mo.Format = f.format } - if err := marshal(mo2, enc, v); err != nil { + err := marshal(enc, v, mo) + mo.Flags = flagsOriginal + mo.Format = "" + if err != nil { return err } // Try unwriting the member if empty (slow path for omitempty). - if f.omitempty { + if f.omitempty && !mo.Flags.Get(jsonflags.OmitEmptyWithLegacySemantics) { var prevName *string if prevIdx >= 0 { prevName = &fields.flattened[prevIdx].name } - if enc.unwriteEmptyObjectMember(prevName) { + if xe.UnwriteEmptyObjectMember(prevName) { continue } } @@ -949,23 +1158,23 @@ func makeStructArshaler(t reflect.Type) *arshaler { // Remember the previous written object member. // The set of seen fields only needs to be updated to detect // duplicate names with those from the inlined fallback. - if !enc.options.AllowDuplicateNames && fields.inlinedFallback != nil { + if !mo.Flags.Get(jsonflags.AllowDuplicateNames) && fields.inlinedFallback != nil { seenIdxs.insert(uint(f.id)) } prevIdx = f.id } - if fields.inlinedFallback != nil && !(mo.DiscardUnknownMembers && fields.inlinedFallback.unknown) { + if fields.inlinedFallback != nil && !(mo.Flags.Get(jsonflags.DiscardUnknownMembers) && fields.inlinedFallback.unknown) { var insertUnquotedName func([]byte) bool - if !enc.options.AllowDuplicateNames { + if !mo.Flags.Get(jsonflags.AllowDuplicateNames) { insertUnquotedName = func(name []byte) bool { // Check that the name from inlined fallback does not match // one of the previously marshaled names from known fields. - if foldedFields := fields.byFoldedName[string(foldName(name))]; len(foldedFields) > 0 { + if foldedFields := fields.lookupByFoldedName(name); len(foldedFields) > 0 { if f := fields.byActualName[string(name)]; f != nil { return seenIdxs.insert(uint(f.id)) } for _, f := range foldedFields { - if f.nocase { + if f.matchFoldedName(name, &mo.Flags) { return seenIdxs.insert(uint(f.id)) } } @@ -973,21 +1182,22 @@ func makeStructArshaler(t reflect.Type) *arshaler { // Check that the name does not match any other name // previously marshaled from the inlined fallback. - return enc.namespaces.last().insertUnquoted(name) + return xe.Namespaces.Last().InsertUnquoted(name) } } - if err := marshalInlinedFallbackAll(mo, enc, va, fields.inlinedFallback, insertUnquotedName); err != nil { + if err := marshalInlinedFallbackAll(enc, va, mo, fields.inlinedFallback, insertUnquotedName); err != nil { return err } } - if err := enc.WriteToken(ObjectEnd); err != nil { + if err := enc.WriteToken(jsontext.EndObject); err != nil { return err } return nil } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) } tok, err := dec.ReadToken() if err != nil { @@ -996,41 +1206,45 @@ func makeStructArshaler(t reflect.Type) *arshaler { k := tok.Kind() switch k { case 'n': - va.Set(reflect.Zero(t)) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetZero() + } return nil case '{': once.Do(init) - if errInit != nil { - err := *errInit // shallow copy SemanticError - err.action = "unmarshal" - return &err + if errInit != nil && !uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return newUnmarshalErrorAfter(dec, errInit.GoType, errInit.Err) } var seenIdxs uintSet - dec.tokens.last.disableNamespace() + xd.Tokens.Last.DisableNamespace() + var errUnmarshal error for dec.PeekKind() != '}' { // Process the object member name. - var flags valueFlags - val, err := dec.readValue(&flags) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { return err } - name := unescapeStringMayCopy(val, flags.isVerbatim()) + name := jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) f := fields.byActualName[string(name)] if f == nil { - for _, f2 := range fields.byFoldedName[string(foldName(name))] { - if f2.nocase { + for _, f2 := range fields.lookupByFoldedName(name) { + if f2.matchFoldedName(name, &uo.Flags) { f = f2 break } } if f == nil { - if uo.RejectUnknownMembers && (fields.inlinedFallback == nil || fields.inlinedFallback.unknown) { - return &SemanticError{action: "unmarshal", GoType: t, Err: fmt.Errorf("unknown name %s", val)} + if uo.Flags.Get(jsonflags.RejectUnknownMembers) && (fields.inlinedFallback == nil || fields.inlinedFallback.unknown) { + err := newUnmarshalErrorAfter(dec, t, ErrUnknownName) + if !uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } - if !dec.options.AllowDuplicateNames && !dec.namespaces.last().insertUnquoted(name) { + if !uo.Flags.Get(jsonflags.AllowDuplicateNames) && !xd.Namespaces.Last().InsertUnquoted(name) { // TODO: Unread the object name. - err := &SyntacticError{str: "duplicate name " + string(val) + " in object"} - return err.withOffset(dec.InputOffset() - int64(len(val))) + return newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(val)) } if fields.inlinedFallback == nil { @@ -1040,46 +1254,68 @@ func makeStructArshaler(t reflect.Type) *arshaler { } } else { // Marshal into value capable of storing arbitrary object members. - if err := unmarshalInlinedFallbackNext(uo, dec, va, fields.inlinedFallback, val, name); err != nil { - return err + if err := unmarshalInlinedFallbackNext(dec, va, uo, fields.inlinedFallback, val, name); err != nil { + if isFatalError(err, uo.Flags) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } } continue } } - if !dec.options.AllowDuplicateNames && !seenIdxs.insert(uint(f.id)) { + if !uo.Flags.Get(jsonflags.AllowDuplicateNames) && !seenIdxs.insert(uint(f.id)) { // TODO: Unread the object name. - err := &SyntacticError{str: "duplicate name " + string(val) + " in object"} - return err.withOffset(dec.InputOffset() - int64(len(val))) + return newDuplicateNameError(dec.StackPointer(), nil, dec.InputOffset()-len64(val)) } // Process the object member value. unmarshal := f.fncs.unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, f.typ) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, f.typ) } - uo2 := uo + flagsOriginal := uo.Flags if f.string { - uo2.StringifyNumbers = true + if !uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) { + uo.Flags.Set(jsonflags.StringifyNumbers | 1) + } else if canLegacyStringify(f.typ) { + uo.Flags.Set(jsonflags.StringifyNumbers | jsonflags.StringifyBoolsAndStrings | 1) + } } if f.format != "" { - uo2.formatDepth = dec.tokens.depth() - uo2.format = f.format + uo.FormatDepth = xd.Tokens.Depth() + uo.Format = f.format } - v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable - if len(f.index) > 1 { - v = v.fieldByIndex(f.index[1:], true) + v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable + if len(f.index) > 0 { + v = v.fieldByIndex(f.index, true) + if !v.IsValid() { + err := newUnmarshalErrorBefore(dec, t, errNilField) + if !uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) + unmarshal = func(dec *jsontext.Decoder, _ addressableValue, _ *jsonopts.Struct) error { + return dec.SkipValue() + } + } } - if err := unmarshal(uo2, dec, v); err != nil { - return err + err = unmarshal(dec, v, uo) + uo.Flags = flagsOriginal + uo.Format = "" + if err != nil { + if isFatalError(err, uo.Flags) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } } if _, err := dec.ReadToken(); err != nil { return err } - return nil + return errUnmarshal } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfterWithSkipping(dec, t, nil) } return &fncs } @@ -1090,7 +1326,7 @@ func (va addressableValue) fieldByIndex(index []int, mayAlloc bool) addressableV if !va.IsValid() { return va } - va = addressableValue{va.Field(i)} // addressable if struct value is addressable + va = addressableValue{va.Field(i), va.forcedAddr} // addressable if struct value is addressable } return va } @@ -1098,16 +1334,55 @@ func (va addressableValue) fieldByIndex(index []int, mayAlloc bool) addressableV func (va addressableValue) indirect(mayAlloc bool) addressableValue { if va.Kind() == reflect.Pointer { if va.IsNil() { - if !mayAlloc { + if !mayAlloc || !va.CanSet() { return addressableValue{} } va.Set(reflect.New(va.Type().Elem())) } - va = addressableValue{va.Elem()} // dereferenced pointer is always addressable + va = addressableValue{va.Elem(), false} // dereferenced pointer is always addressable } return va } +// isLegacyEmpty reports whether a value is empty according to the v1 definition. +func isLegacyEmpty(v addressableValue) bool { + // Equivalent to encoding/json.isEmptyValue@v1.21.0. + switch v.Kind() { + case reflect.Bool: + return v.Bool() == false + 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.String, reflect.Map, reflect.Slice, reflect.Array: + return v.Len() == 0 + case reflect.Pointer, reflect.Interface: + return v.IsNil() + } + return false +} + +// canLegacyStringify reports whether t can be stringified according to v1, +// where t is a bool, string, or number (or unnamed pointer to such). +// In v1, the `string` option does not apply recursively to nested types within +// a composite Go type (e.g., an array, slice, struct, map, or interface). +func canLegacyStringify(t reflect.Type) bool { + // Based on encoding/json.typeFields#L1126-L1143@v1.23.0 + if t.Name() == "" && t.Kind() == reflect.Ptr { + t = t.Elem() + } + switch t.Kind() { + case reflect.Bool, reflect.String, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64: + return true + } + return false +} + func makeSliceArshaler(t reflect.Type) *arshaler { var fncs arshaler var ( @@ -1117,64 +1392,75 @@ func makeSliceArshaler(t reflect.Type) *arshaler { init := func() { valFncs = lookupArshaler(t.Elem()) } - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { // Check for cycles. - if enc.tokens.depth() > startDetectingCyclesAfter { - if err := enc.seenPointers.visit(va.Value); err != nil { - return err - } - defer enc.seenPointers.leave(va.Value) - } - - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - if mo.format == "emitnull" { - if va.IsNil() { - return enc.WriteToken(Null) - } - mo.format = "" - } else { - return newInvalidFormatError("marshal", t, mo.format) + xe := export.Encoder(enc) + if xe.Tokens.Depth() > startDetectingCyclesAfter { + if err := visitPointer(&xe.SeenPointers, va.Value); err != nil { + return newMarshalErrorBefore(enc, t, err) + } + defer leavePointer(&xe.SeenPointers, va.Value) + } + + emitNull := mo.Flags.Get(jsonflags.FormatNilSliceAsNull) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + switch mo.Format { + case "emitnull": + emitNull = true + mo.Format = "" + case "emitempty": + emitNull = false + mo.Format = "" + default: + return newInvalidFormatError(enc, t) } } - // Optimize for marshaling an empty slice without any preceding whitespace. + // Handle empty slices. n := va.Len() - if optimizeCommon && n == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { - enc.buf = enc.tokens.mayAppendDelim(enc.buf, '[') - enc.buf = append(enc.buf, "[]"...) - enc.tokens.last.increment() - if enc.needFlush() { - return enc.flush() + if n == 0 { + if emitNull && va.IsNil() { + return enc.WriteToken(jsontext.Null) + } + // Optimize for marshaling an empty slice without any preceding whitespace. + if optimizeCommon && !mo.Flags.Get(jsonflags.AnyWhitespace) && !xe.Tokens.Last.NeedObjectName() { + xe.Buf = append(xe.Tokens.MayAppendDelim(xe.Buf, '['), "[]"...) + xe.Tokens.Last.Increment() + if xe.NeedFlush() { + return xe.Flush() + } + return nil } - return nil } once.Do(init) - if err := enc.WriteToken(ArrayStart); err != nil { + if err := enc.WriteToken(jsontext.BeginArray); err != nil { return err } marshal := valFncs.marshal if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, t.Elem()) + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, t.Elem()) } - for i := 0; i < n; i++ { - v := addressableValue{va.Index(i)} // indexed slice element is always addressable - if err := marshal(mo, enc, v); err != nil { + for i := range n { + v := addressableValue{va.Index(i), false} // indexed slice element is always addressable + if err := marshal(enc, v, mo); err != nil { return err } } - if err := enc.WriteToken(ArrayEnd); err != nil { + if err := enc.WriteToken(jsontext.EndArray); err != nil { return err } return nil } emptySlice := reflect.MakeSlice(t, 0, 0) - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - if uo.format == "emitnull" { - uo.format = "" // only relevant for marshaling - } else { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + switch uo.Format { + case "emitnull", "emitempty": + uo.Format = "" // only relevant for marshaling + default: + return newInvalidFormatError(dec, t) } } @@ -1185,13 +1471,13 @@ func makeSliceArshaler(t reflect.Type) *arshaler { k := tok.Kind() switch k { case 'n': - va.Set(reflect.Zero(t)) + va.SetZero() return nil case '[': once.Do(init) unmarshal := valFncs.unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, t.Elem()) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, t.Elem()) } mustZero := true // we do not know the cleanliness of unused capacity cap := va.Cap() @@ -1199,22 +1485,25 @@ func makeSliceArshaler(t reflect.Type) *arshaler { va.SetLen(cap) } var i int + var errUnmarshal error for dec.PeekKind() != ']' { if i == cap { - // TODO(https://go.dev/issue/48000): Use reflect.Value.Append. - va.Set(reflect.Append(va.Value, reflect.Zero(t.Elem()))) + va.Value.Grow(1) cap = va.Cap() va.SetLen(cap) - mustZero = false // append guarantees that unused capacity is zero-initialized + mustZero = false // reflect.Value.Grow ensures new capacity is zero-initialized } - v := addressableValue{va.Index(i)} // indexed slice element is always addressable + v := addressableValue{va.Index(i), false} // indexed slice element is always addressable i++ - if mustZero { - v.Set(reflect.Zero(t.Elem())) + if mustZero && !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + v.SetZero() } - if err := unmarshal(uo, dec, v); err != nil { - va.SetLen(i) - return err + if err := unmarshal(dec, v, uo); err != nil { + if isFatalError(err, uo.Flags) { + va.SetLen(i) + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } } if i == 0 { @@ -1225,13 +1514,16 @@ func makeSliceArshaler(t reflect.Type) *arshaler { if _, err := dec.ReadToken(); err != nil { return err } - return nil + return errUnmarshal } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfterWithSkipping(dec, t, nil) } return &fncs } +var errArrayUnderflow = errors.New("too few array elements") +var errArrayOverflow = errors.New("too many array elements") + func makeArrayArshaler(t reflect.Type) *arshaler { var fncs arshaler var ( @@ -1242,32 +1534,34 @@ func makeArrayArshaler(t reflect.Type) *arshaler { valFncs = lookupArshaler(t.Elem()) } n := t.Len() - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } once.Do(init) - if err := enc.WriteToken(ArrayStart); err != nil { + if err := enc.WriteToken(jsontext.BeginArray); err != nil { return err } marshal := valFncs.marshal if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, t.Elem()) + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, t.Elem()) } - for i := 0; i < n; i++ { - v := addressableValue{va.Index(i)} // indexed array element is addressable if array is addressable - if err := marshal(mo, enc, v); err != nil { + for i := range n { + v := addressableValue{va.Index(i), va.forcedAddr} // indexed array element is addressable if array is addressable + if err := marshal(enc, v, mo); err != nil { return err } } - if err := enc.WriteToken(ArrayEnd); err != nil { + if err := enc.WriteToken(jsontext.EndArray); err != nil { return err } return nil } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) } tok, err := dec.ReadToken() if err != nil { @@ -1276,37 +1570,51 @@ func makeArrayArshaler(t reflect.Type) *arshaler { k := tok.Kind() switch k { case 'n': - va.Set(reflect.Zero(t)) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetZero() + } return nil case '[': once.Do(init) unmarshal := valFncs.unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, t.Elem()) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, t.Elem()) } var i int + var errUnmarshal error for dec.PeekKind() != ']' { if i >= n { - err := errors.New("too many array elements") - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + if err := dec.SkipValue(); err != nil { + return err + } + err = errArrayOverflow + continue } - v := addressableValue{va.Index(i)} // indexed array element is addressable if array is addressable - v.Set(reflect.Zero(v.Type())) - if err := unmarshal(uo, dec, v); err != nil { - return err + v := addressableValue{va.Index(i), va.forcedAddr} // indexed array element is addressable if array is addressable + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + v.SetZero() + } + if err := unmarshal(dec, v, uo); err != nil { + if isFatalError(err, uo.Flags) { + return err + } + errUnmarshal = cmp.Or(errUnmarshal, err) } i++ } + for ; i < n; i++ { + va.Index(i).SetZero() + err = errArrayUnderflow + } if _, err := dec.ReadToken(); err != nil { return err } - if i < n { - err := errors.New("too few array elements") - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + if err != nil && !uo.Flags.Get(jsonflags.UnmarshalArrayFromAnyLength) { + return newUnmarshalErrorAfter(dec, t, err) } - return nil + return errUnmarshal } - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} + return newUnmarshalErrorAfterWithSkipping(dec, t, nil) } return &fncs } @@ -1320,46 +1628,62 @@ func makePointerArshaler(t reflect.Type) *arshaler { init := func() { valFncs = lookupArshaler(t.Elem()) } - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { // Check for cycles. - if enc.tokens.depth() > startDetectingCyclesAfter { - if err := enc.seenPointers.visit(va.Value); err != nil { - return err + xe := export.Encoder(enc) + if xe.Tokens.Depth() > startDetectingCyclesAfter { + if err := visitPointer(&xe.SeenPointers, va.Value); err != nil { + return newMarshalErrorBefore(enc, t, err) } - defer enc.seenPointers.leave(va.Value) + defer leavePointer(&xe.SeenPointers, va.Value) } - // NOTE: MarshalOptions.format is forwarded to underlying marshal. + // NOTE: Struct.Format is forwarded to underlying marshal. if va.IsNil() { - return enc.WriteToken(Null) + return enc.WriteToken(jsontext.Null) } once.Do(init) marshal := valFncs.marshal if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, t.Elem()) + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, t.Elem()) } - v := addressableValue{va.Elem()} // dereferenced pointer is always addressable - return marshal(mo, enc, v) + v := addressableValue{va.Elem(), false} // dereferenced pointer is always addressable + return marshal(enc, v, mo) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - // NOTE: UnmarshalOptions.format is forwarded to underlying unmarshal. + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + // NOTE: Struct.Format is forwarded to underlying unmarshal. if dec.PeekKind() == 'n' { if _, err := dec.ReadToken(); err != nil { return err } - va.Set(reflect.Zero(t)) + va.SetZero() return nil } once.Do(init) unmarshal := valFncs.unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, t.Elem()) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, t.Elem()) } if va.IsNil() { va.Set(reflect.New(t.Elem())) } - v := addressableValue{va.Elem()} // dereferenced pointer is always addressable - return unmarshal(uo, dec, v) + v := addressableValue{va.Elem(), false} // dereferenced pointer is always addressable + if err := unmarshal(dec, v, uo); err != nil { + return err + } + if uo.Flags.Get(jsonflags.StringifyWithLegacySemantics) && + uo.Flags.Get(jsonflags.StringifyNumbers|jsonflags.StringifyBoolsAndStrings) { + // A JSON null quoted within a JSON string should take effect + // within the pointer value, rather than the indirect value. + // + // TODO: This does not correctly handle escaped nulls + // (e.g., "\u006e\u0075\u006c\u006c"), but is good enough + // for such an esoteric use case of the `string` option. + if string(export.Decoder(dec).PreviousTokenOrValue()) == `"null"` { + va.SetZero() + } + } + return nil } return &fncs } @@ -1370,34 +1694,82 @@ func makeInterfaceArshaler(t reflect.Type) *arshaler { // store them back into the interface afterwards. var fncs arshaler - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - return newInvalidFormatError("marshal", t, mo.format) + var whichMarshaler reflect.Type + for _, iface := range allMarshalerTypes { + if t.Implements(iface) { + whichMarshaler = t + break + } + } + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + return newInvalidFormatError(enc, t) } if va.IsNil() { - return enc.WriteToken(Null) + return enc.WriteToken(jsontext.Null) + } else if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && whichMarshaler != nil { + // The marshaler for a pointer never calls the method on a nil receiver. + // Wrap the nil pointer within a struct type so that marshal + // instead appears on a value receiver and may be called. + if va.Elem().Kind() == reflect.Pointer && va.Elem().IsNil() { + v2 := newAddressableValue(whichMarshaler) + switch whichMarshaler { + case jsonMarshalerToType: + v2.Set(reflect.ValueOf(struct{ MarshalerTo }{va.Elem().Interface().(MarshalerTo)})) + case jsonMarshalerType: + v2.Set(reflect.ValueOf(struct{ Marshaler }{va.Elem().Interface().(Marshaler)})) + case textAppenderType: + v2.Set(reflect.ValueOf(struct{ encoding.TextAppender }{va.Elem().Interface().(encoding.TextAppender)})) + case textMarshalerType: + v2.Set(reflect.ValueOf(struct{ encoding.TextMarshaler }{va.Elem().Interface().(encoding.TextMarshaler)})) + } + va = v2 + } } v := newAddressableValue(va.Elem().Type()) v.Set(va.Elem()) marshal := lookupArshaler(v.Type()).marshal if mo.Marshalers != nil { - marshal, _ = mo.Marshalers.lookup(marshal, v.Type()) + marshal, _ = mo.Marshalers.(*Marshalers).lookup(marshal, v.Type()) } // Optimize for the any type if there are no special options. - if optimizeCommon && t == anyType && !mo.StringifyNumbers && mo.format == "" && (mo.Marshalers == nil || !mo.Marshalers.fromAny) { - return marshalValueAny(mo, enc, va.Elem().Interface()) + if optimizeCommon && + t == anyType && !mo.Flags.Get(jsonflags.StringifyNumbers|jsonflags.StringifyBoolsAndStrings) && mo.Format == "" && + (mo.Marshalers == nil || !mo.Marshalers.(*Marshalers).fromAny) { + return marshalValueAny(enc, va.Elem().Interface(), mo) } - return marshal(mo, enc, v) + return marshal(enc, v, mo) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - return newInvalidFormatError("unmarshal", t, uo.format) + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + return newInvalidFormatError(dec, t) + } + if uo.Flags.Get(jsonflags.MergeWithLegacySemantics) && !va.IsNil() { + // Legacy merge behavior is difficult to explain. + // In general, it only merges for non-nil pointer kinds. + // As a special case, unmarshaling a JSON null into a pointer + // sets a concrete nil pointer of the underlying type + // (rather than setting the interface value itself to nil). + e := va.Elem() + if e.Kind() == reflect.Pointer && !e.IsNil() { + if dec.PeekKind() == 'n' && e.Elem().Kind() == reflect.Pointer { + if _, err := dec.ReadToken(); err != nil { + return err + } + va.Elem().Elem().SetZero() + return nil + } + } else { + va.SetZero() + } } if dec.PeekKind() == 'n' { if _, err := dec.ReadToken(); err != nil { return err } - va.Set(reflect.Zero(t)) + va.SetZero() return nil } var v addressableValue @@ -1407,8 +1779,10 @@ func makeInterfaceArshaler(t reflect.Type) *arshaler { // are always unmarshaled into an any value as Go strings. // Duplicate name check must be enforced since unmarshalValueAny // does not implement merge semantics. - if optimizeCommon && t == anyType && uo.format == "" && (uo.Unmarshalers == nil || !uo.Unmarshalers.fromAny) && !dec.options.AllowDuplicateNames { - v, err := unmarshalValueAny(uo, dec) + if optimizeCommon && + t == anyType && !uo.Flags.Get(jsonflags.AllowDuplicateNames) && uo.Format == "" && + (uo.Unmarshalers == nil || !uo.Unmarshalers.(*Unmarshalers).fromAny) { + v, err := unmarshalValueAny(dec, uo) // We must check for nil interface values up front. // See https://go.dev/issue/52310. if v != nil { @@ -1419,8 +1793,7 @@ func makeInterfaceArshaler(t reflect.Type) *arshaler { k := dec.PeekKind() if !isAnyType(t) { - err := errors.New("cannot derive concrete type for non-empty interface") - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + return newUnmarshalErrorBeforeWithSkipping(dec, t, internal.ErrNilInterface) } switch k { case 'f', 't': @@ -1428,7 +1801,11 @@ func makeInterfaceArshaler(t reflect.Type) *arshaler { case '"': v = newAddressableValue(stringType) case '0': - v = newAddressableValue(float64Type) + if uo.Flags.Get(jsonflags.UnmarshalAnyWithRawNumber) { + v = addressableValue{reflect.ValueOf(internal.NewRawNumber()).Elem(), true} + } else { + v = newAddressableValue(float64Type) + } case '{': v = newAddressableValue(mapStringAnyType) case '[': @@ -1450,9 +1827,9 @@ func makeInterfaceArshaler(t reflect.Type) *arshaler { } unmarshal := lookupArshaler(v.Type()).unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, v.Type()) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, v.Type()) } - err := unmarshal(uo, dec, v) + err := unmarshal(dec, v, uo) va.Set(v.Value) return err } @@ -1470,16 +1847,62 @@ func isAnyType(t reflect.Type) bool { func makeInvalidArshaler(t reflect.Type) *arshaler { var fncs arshaler - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - return &SemanticError{action: "marshal", GoType: t} + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + return newMarshalErrorBefore(enc, t, nil) } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - return &SemanticError{action: "unmarshal", GoType: t} + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + return newUnmarshalErrorBefore(dec, t, nil) } return &fncs } -func newInvalidFormatError(action string, t reflect.Type, format string) error { - err := fmt.Errorf("invalid format flag: %q", format) - return &SemanticError{action: action, GoType: t, Err: err} +func stringOrNumberKind(isString bool) jsontext.Kind { + if isString { + return '"' + } else { + return '0' + } +} + +type uintSet64 uint64 + +func (s uintSet64) has(i uint) bool { return s&(1< 0 } +func (s *uintSet64) set(i uint) { *s |= 1 << i } + +// uintSet is a set of unsigned integers. +// It is optimized for most integers being close to zero. +type uintSet struct { + lo uintSet64 + hi []uintSet64 +} + +// has reports whether i is in the set. +func (s *uintSet) has(i uint) bool { + if i < 64 { + return s.lo.has(i) + } else { + i -= 64 + iHi, iLo := int(i/64), i%64 + return iHi < len(s.hi) && s.hi[iHi].has(iLo) + } +} + +// insert inserts i into the set and reports whether it was the first insertion. +func (s *uintSet) insert(i uint) bool { + // TODO: Make this inlinable at least for the lower 64-bit case. + if i < 64 { + has := s.lo.has(i) + s.lo.set(i) + return !has + } else { + i -= 64 + iHi, iLo := int(i/64), i%64 + if iHi >= len(s.hi) { + s.hi = append(s.hi, make([]uintSet64, iHi+1-len(s.hi))...) + s.hi = s.hi[:cap(s.hi)] + } + has := s.hi[iHi].has(iLo) + s.hi[iHi].set(iLo) + return !has + } } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go index 8a4e70083..50dca26b8 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go @@ -9,62 +9,75 @@ import ( "fmt" "reflect" "sync" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) -// SkipFunc may be returned by MarshalFuncV2 and UnmarshalFuncV2 functions. +// SkipFunc may be returned by [MarshalToFunc] and [UnmarshalFromFunc] functions. // // Any function that returns SkipFunc must not cause observable side effects -// on the provided Encoder or Decoder. For example, it is permissible to call -// Decoder.PeekKind, but not permissible to call Decoder.ReadToken or -// Encoder.WriteToken since such methods mutate the state. -const SkipFunc = jsonError("skip function") +// on the provided [jsontext.Encoder] or [jsontext.Decoder]. +// For example, it is permissible to call [jsontext.Decoder.PeekKind], +// but not permissible to call [jsontext.Decoder.ReadToken] or +// [jsontext.Encoder.WriteToken] since such methods mutate the state. +var SkipFunc = errors.New("json: skip function") + +var errSkipMutation = errors.New("must not read or write any tokens when skipping") +var errNonSingularValue = errors.New("must read or write exactly one value") // Marshalers is a list of functions that may override the marshal behavior -// of specific types. Populate MarshalOptions.Marshalers to use it. +// of specific types. Populate [WithMarshalers] to use it with +// [Marshal], [MarshalWrite], or [MarshalEncode]. // A nil *Marshalers is equivalent to an empty list. +// There are no exported fields or methods on Marshalers. type Marshalers = typedMarshalers -// NewMarshalers constructs a flattened list of marshal functions. +// JoinMarshalers constructs a flattened list of marshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. -// If a function returns SkipFunc, then the next applicable function is called, +// If a function returns [SkipFunc], then the next applicable function is called, // otherwise the default marshaling behavior is used. // // For example: // -// m1 := NewMarshalers(f1, f2) -// m2 := NewMarshalers(f0, m1, f3) // equivalent to m3 -// m3 := NewMarshalers(f0, f1, f2, f3) // equivalent to m2 -func NewMarshalers(ms ...*Marshalers) *Marshalers { +// m1 := JoinMarshalers(f1, f2) +// m2 := JoinMarshalers(f0, m1, f3) // equivalent to m3 +// m3 := JoinMarshalers(f0, f1, f2, f3) // equivalent to m2 +func JoinMarshalers(ms ...*Marshalers) *Marshalers { return newMarshalers(ms...) } // Unmarshalers is a list of functions that may override the unmarshal behavior -// of specific types. Populate UnmarshalOptions.Unmarshalers to use it. +// of specific types. Populate [WithUnmarshalers] to use it with +// [Unmarshal], [UnmarshalRead], or [UnmarshalDecode]. // A nil *Unmarshalers is equivalent to an empty list. +// There are no exported fields or methods on Unmarshalers. type Unmarshalers = typedUnmarshalers -// NewUnmarshalers constructs a flattened list of unmarshal functions. +// JoinUnmarshalers constructs a flattened list of unmarshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. -// If a function returns SkipFunc, then the next applicable function is called, +// If a function returns [SkipFunc], then the next applicable function is called, // otherwise the default unmarshaling behavior is used. // // For example: // -// u1 := NewUnmarshalers(f1, f2) -// u2 := NewUnmarshalers(f0, u1, f3) // equivalent to u3 -// u3 := NewUnmarshalers(f0, f1, f2, f3) // equivalent to u2 -func NewUnmarshalers(us ...*Unmarshalers) *Unmarshalers { +// u1 := JoinUnmarshalers(f1, f2) +// u2 := JoinUnmarshalers(f0, u1, f3) // equivalent to u3 +// u3 := JoinUnmarshalers(f0, f1, f2, f3) // equivalent to u2 +func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newUnmarshalers(us...) } -type typedMarshalers = typedArshalers[MarshalOptions, Encoder] -type typedUnmarshalers = typedArshalers[UnmarshalOptions, Decoder] -type typedArshalers[Options, Coder any] struct { +type typedMarshalers = typedArshalers[jsontext.Encoder] +type typedUnmarshalers = typedArshalers[jsontext.Decoder] +type typedArshalers[Coder any] struct { nonComparable - fncVals []typedArshaler[Options, Coder] + fncVals []typedArshaler[Coder] fncCache sync.Map // map[reflect.Type]arshaler // fromAny reports whether any of Go types used to represent arbitrary JSON @@ -78,18 +91,18 @@ type typedArshalers[Options, Coder any] struct { // if this is true. fromAny bool } -type typedMarshaler = typedArshaler[MarshalOptions, Encoder] -type typedUnmarshaler = typedArshaler[UnmarshalOptions, Decoder] -type typedArshaler[Options, Coder any] struct { +type typedMarshaler = typedArshaler[jsontext.Encoder] +type typedUnmarshaler = typedArshaler[jsontext.Decoder] +type typedArshaler[Coder any] struct { typ reflect.Type - fnc func(Options, *Coder, addressableValue) error + fnc func(*Coder, addressableValue, *jsonopts.Struct) error maySkip bool } func newMarshalers(ms ...*Marshalers) *Marshalers { return newTypedArshalers(ms...) } func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) } -func newTypedArshalers[Options, Coder any](as ...*typedArshalers[Options, Coder]) *typedArshalers[Options, Coder] { - var a typedArshalers[Options, Coder] +func newTypedArshalers[Coder any](as ...*typedArshalers[Coder]) *typedArshalers[Coder] { + var a typedArshalers[Coder] for _, a2 := range as { if a2 != nil { a.fncVals = append(a.fncVals, a2.fncVals...) @@ -102,7 +115,7 @@ func newTypedArshalers[Options, Coder any](as ...*typedArshalers[Options, Coder] return &a } -func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addressableValue) error, t reflect.Type) (func(Options, *Coder, addressableValue) error, bool) { +func (a *typedArshalers[Coder]) lookup(fnc func(*Coder, addressableValue, *jsonopts.Struct) error, t reflect.Type) (func(*Coder, addressableValue, *jsonopts.Struct) error, bool) { if a == nil { return fnc, false } @@ -110,12 +123,12 @@ func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addres if v == nil { return fnc, false } - return v.(func(Options, *Coder, addressableValue) error), true + return v.(func(*Coder, addressableValue, *jsonopts.Struct) error), true } // Collect a list of arshalers that can be called for this type. // This list may be longer than 1 since some arshalers can be skipped. - var fncs []func(Options, *Coder, addressableValue) error + var fncs []func(*Coder, addressableValue, *jsonopts.Struct) error for _, fncVal := range a.fncVals { if !castableTo(t, fncVal.typ) { continue @@ -133,21 +146,21 @@ func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addres // Construct an arshaler that may call every applicable arshaler. fncDefault := fnc - fnc = func(o Options, c *Coder, v addressableValue) error { + fnc = func(c *Coder, v addressableValue, o *jsonopts.Struct) error { for _, fnc := range fncs { - if err := fnc(o, c, v); err != SkipFunc { + if err := fnc(c, v, o); err != SkipFunc { return err // may be nil or non-nil } } - return fncDefault(o, c, v) + return fncDefault(c, v, o) } // Use the first stored so duplicate work can be garbage collected. v, _ := a.fncCache.LoadOrStore(t, fnc) - return v.(func(Options, *Coder, addressableValue) error), true + return v.(func(*Coder, addressableValue, *jsonopts.Struct) error), true } -// MarshalFuncV1 constructs a type-specific marshaler that +// MarshalFunc constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value @@ -155,22 +168,30 @@ func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addres // // The function must marshal exactly one JSON value. // The value of T must not be retained outside the function call. -// It may not return SkipFunc. -func MarshalFuncV1[T any](fn func(T) ([]byte, error)) *Marshalers { - t := reflect.TypeOf((*T)(nil)).Elem() +// It may not return [SkipFunc]. +func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers { + t := reflect.TypeFor[T]() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, - fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { + fnc: func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { val, err := fn(va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "marshal function of type func(T) ([]byte, error)") - // TODO: Avoid wrapping semantic errors. - return &SemanticError{action: "marshal", GoType: t, Err: err} + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalFunc") // unlike unmarshal, always wrapped + } + err = newMarshalErrorBefore(enc, t, err) + return collapseSemanticErrors(err) } if err := enc.WriteValue(val); err != nil { - // TODO: Avoid wrapping semantic or I/O errors. - return &SemanticError{action: "marshal", JSONKind: RawValue(val).Kind(), GoType: t, Err: err} + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalFunc") // unlike unmarshal, always wrapped + } + if isSyntacticError(err) { + err = newMarshalErrorBefore(enc, t, err) + } + return err } return nil }, @@ -178,39 +199,47 @@ func MarshalFuncV1[T any](fn func(T) ([]byte, error)) *Marshalers { return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } -// MarshalFuncV2 constructs a type-specific marshaler that +// MarshalToFunc constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value // if T is an interface or pointer type. // // The function must marshal exactly one JSON value by calling write methods -// on the provided encoder. It may return SkipFunc such that marshaling can +// on the provided encoder. It may return [SkipFunc] such that marshaling can // move on to the next marshal function. However, no mutable method calls may -// be called on the encoder if SkipFunc is returned. -// The pointer to Encoder and the value of T must not be retained -// outside the function call. -func MarshalFuncV2[T any](fn func(MarshalOptions, *Encoder, T) error) *Marshalers { - t := reflect.TypeOf((*T)(nil)).Elem() +// be called on the encoder if [SkipFunc] is returned. +// The pointer to [jsontext.Encoder] and the value of T +// must not be retained outside the function call. +func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers { + t := reflect.TypeFor[T]() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, - fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - prevDepth, prevLength := enc.tokens.depthLength() - err := fn(mo, enc, va.castTo(t).Interface().(T)) - currDepth, currLength := enc.tokens.depthLength() + fnc: func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + prevDepth, prevLength := xe.Tokens.DepthLength() + xe.Flags.Set(jsonflags.WithinArshalCall | 1) + err := fn(enc, va.castTo(t).Interface().(T)) + xe.Flags.Set(jsonflags.WithinArshalCall | 0) + currDepth, currLength := xe.Tokens.DepthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { - err = errors.New("must write exactly one JSON value") + err = errNonSingularValue } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } - err = errors.New("must not write any JSON tokens when skipping") + err = errSkipMutation + } + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalToFunc") // unlike unmarshal, always wrapped } - // TODO: Avoid wrapping semantic or I/O errors. - return &SemanticError{action: "marshal", GoType: t, Err: err} + if !export.IsIOError(err) { + err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err) + } + return err } return nil }, @@ -219,7 +248,7 @@ func MarshalFuncV2[T any](fn func(MarshalOptions, *Encoder, T) error) *Marshaler return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } -// UnmarshalFuncV1 constructs a type-specific unmarshaler that +// UnmarshalFunc constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. @@ -227,13 +256,13 @@ func MarshalFuncV2[T any](fn func(MarshalOptions, *Encoder, T) error) *Marshaler // The function must unmarshal exactly one JSON value. // The input []byte must not be mutated. // The input []byte and value T must not be retained outside the function call. -// It may not return SkipFunc. -func UnmarshalFuncV1[T any](fn func([]byte, T) error) *Unmarshalers { - t := reflect.TypeOf((*T)(nil)).Elem() +// It may not return [SkipFunc]. +func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers { + t := reflect.TypeFor[T]() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, - fnc: func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { + fnc: func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { val, err := dec.ReadValue() if err != nil { return err // must be a syntactic or I/O error @@ -241,8 +270,11 @@ func UnmarshalFuncV1[T any](fn func([]byte, T) error) *Unmarshalers { err = fn(val, va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "unmarshal function of type func([]byte, T) error") - // TODO: Avoid wrapping semantic, syntactic, or I/O errors. - return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err // unlike marshal, never wrapped + } + err = newUnmarshalErrorAfter(dec, t, err) + return collapseSemanticErrors(err) } return nil }, @@ -250,38 +282,49 @@ func UnmarshalFuncV1[T any](fn func([]byte, T) error) *Unmarshalers { return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)} } -// UnmarshalFuncV2 constructs a type-specific unmarshaler that +// UnmarshalFromFunc constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. // // The function must unmarshal exactly one JSON value by calling read methods -// on the provided decoder. It may return SkipFunc such that unmarshaling can +// on the provided decoder. It may return [SkipFunc] such that unmarshaling can // move on to the next unmarshal function. However, no mutable method calls may -// be called on the decoder if SkipFunc is returned. -// The pointer to Decoder and the value of T must not be retained -// outside the function call. -func UnmarshalFuncV2[T any](fn func(UnmarshalOptions, *Decoder, T) error) *Unmarshalers { - t := reflect.TypeOf((*T)(nil)).Elem() +// be called on the decoder if [SkipFunc] is returned. +// The pointer to [jsontext.Decoder] and the value of T +// must not be retained outside the function call. +func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers { + t := reflect.TypeFor[T]() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, - fnc: func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - prevDepth, prevLength := dec.tokens.depthLength() - err := fn(uo, dec, va.castTo(t).Interface().(T)) - currDepth, currLength := dec.tokens.depthLength() + fnc: func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + prevDepth, prevLength := xd.Tokens.DepthLength() + xd.Flags.Set(jsonflags.WithinArshalCall | 1) + err := fn(dec, va.castTo(t).Interface().(T)) + xd.Flags.Set(jsonflags.WithinArshalCall | 0) + currDepth, currLength := xd.Tokens.DepthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { - err = errors.New("must read exactly one JSON value") + err = errNonSingularValue } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } - err = errors.New("must not read any JSON tokens when skipping") + err = errSkipMutation + } + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil { + return err2 + } + return err // unlike marshal, never wrapped + } + if !isSyntacticError(err) && !export.IsIOError(err) { + err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err) } - // TODO: Avoid wrapping semantic, syntactic, or I/O errors. - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + return err } return nil }, diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go index 258a98247..4509b87e4 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go @@ -7,7 +7,13 @@ package json import ( "bytes" "errors" + "io" "reflect" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // This package supports "inlining" a Go struct field, where the contents @@ -18,18 +24,20 @@ import ( // nested struct are virtually hoisted up to the parent struct using rules // similar to how Go embedding works (but operating within the JSON namespace). // -// However, inlined fields may also be of a Go map type with a string key -// or a RawValue. Such inlined fields are called "fallback" fields since they +// However, inlined fields may also be of a Go map type with a string key or +// a jsontext.Value. Such inlined fields are called "fallback" fields since they // represent any arbitrary JSON object member. Explicitly named fields take // precedence over the inlined fallback. Only one inlined fallback is allowed. -var rawValueType = reflect.TypeOf((*RawValue)(nil)).Elem() +var errRawInlinedNotObject = errors.New("inlined raw value must be a JSON object") + +var jsontextValueType = reflect.TypeFor[jsontext.Value]() // marshalInlinedFallbackAll marshals all the members in an inlined fallback. -func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableValue, f *structField, insertUnquotedName func([]byte) bool) error { - v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable - if len(f.index) > 1 { - v = v.fieldByIndex(f.index[1:], false) +func marshalInlinedFallbackAll(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct, f *structField, insertUnquotedName func([]byte) bool) error { + v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable + if len(f.index) > 0 { + v = v.fieldByIndex(f.index, false) if !v.IsValid() { return nil // implies a nil inlined field } @@ -39,34 +47,39 @@ func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableVa return nil } - if v.Type() == rawValueType { - b := v.Interface().(RawValue) + if v.Type() == jsontextValueType { + // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo. + b := *v.Addr().Interface().(*jsontext.Value) if len(b) == 0 { // TODO: Should this be nil? What if it were all whitespace? return nil } - dec := getBufferedDecoder(b, DecodeOptions{AllowDuplicateNames: true, AllowInvalidUTF8: true}) - defer putBufferedDecoder(dec) + dec := export.GetBufferedDecoder(b) + defer export.PutBufferedDecoder(dec) + xd := export.Decoder(dec) + xd.Flags.Set(jsonflags.AllowDuplicateNames | jsonflags.AllowInvalidUTF8 | 1) tok, err := dec.ReadToken() if err != nil { - return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return newMarshalErrorBefore(enc, v.Type(), err) } if tok.Kind() != '{' { - err := errors.New("inlined raw value must be a JSON object") - return &SemanticError{action: "marshal", JSONKind: tok.Kind(), GoType: rawValueType, Err: err} + return newMarshalErrorBefore(enc, v.Type(), errRawInlinedNotObject) } for dec.PeekKind() != '}' { // Parse the JSON object name. - var flags valueFlags - val, err := dec.readValue(&flags) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { - return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} + return newMarshalErrorBefore(enc, v.Type(), err) } if insertUnquotedName != nil { - name := unescapeStringMayCopy(val, flags.isVerbatim()) + name := jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) if !insertUnquotedName(name) { - return &SyntacticError{str: "duplicate name " + string(val) + " in object"} + return newDuplicateNameError(enc.StackPointer().Parent(), val, enc.OutputOffset()) } } if err := enc.WriteValue(val); err != nil { @@ -74,55 +87,55 @@ func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableVa } // Parse the JSON object value. - val, err = dec.readValue(&flags) + val, err = xd.ReadValue(&flags) if err != nil { - return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} + return newMarshalErrorBefore(enc, v.Type(), err) } if err := enc.WriteValue(val); err != nil { return err } } if _, err := dec.ReadToken(); err != nil { - return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} + return newMarshalErrorBefore(enc, v.Type(), err) } - if err := dec.checkEOF(); err != nil { - return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} + if err := xd.CheckEOF(); err != nil { + return newMarshalErrorBefore(enc, v.Type(), err) } return nil } else { - m := v // must be a map[string]V + m := v // must be a map[~string]V n := m.Len() if n == 0 { return nil } - mk := newAddressableValue(stringType) + mk := newAddressableValue(m.Type().Key()) mv := newAddressableValue(m.Type().Elem()) marshalKey := func(mk addressableValue) error { - b, err := appendString(enc.UnusedBuffer(), mk.String(), !enc.options.AllowInvalidUTF8, nil) + b, err := jsonwire.AppendQuote(enc.AvailableBuffer(), mk.String(), &mo.Flags) if err != nil { - return err + return newMarshalErrorBefore(enc, m.Type().Key(), err) } if insertUnquotedName != nil { isVerbatim := bytes.IndexByte(b, '\\') < 0 - name := unescapeStringMayCopy(b, isVerbatim) + name := jsonwire.UnquoteMayCopy(b, isVerbatim) if !insertUnquotedName(name) { - return &SyntacticError{str: "duplicate name " + string(b) + " in object"} + return newDuplicateNameError(enc.StackPointer().Parent(), b, enc.OutputOffset()) } } return enc.WriteValue(b) } marshalVal := f.fncs.marshal if mo.Marshalers != nil { - marshalVal, _ = mo.Marshalers.lookup(marshalVal, mv.Type()) + marshalVal, _ = mo.Marshalers.(*Marshalers).lookup(marshalVal, mv.Type()) } - if !mo.Deterministic || n <= 1 { + if !mo.Flags.Get(jsonflags.Deterministic) || n <= 1 { for iter := m.MapRange(); iter.Next(); { mk.SetIterKey(iter) if err := marshalKey(mk); err != nil { return err } mv.Set(iter.Value()) - if err := marshalVal(mo, enc, mv); err != nil { + if err := marshalVal(enc, mv, mo); err != nil { return err } } @@ -140,7 +153,7 @@ func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableVa } // TODO(https://go.dev/issue/57061): Use mv.SetMapIndexOf. mv.Set(m.MapIndex(mk.Value)) - if err := marshalVal(mo, enc, mv); err != nil { + if err := marshalVal(enc, mv, mo); err != nil { return err } } @@ -151,59 +164,61 @@ func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableVa } // unmarshalInlinedFallbackNext unmarshals only the next member in an inlined fallback. -func unmarshalInlinedFallbackNext(uo UnmarshalOptions, dec *Decoder, va addressableValue, f *structField, quotedName, unquotedName []byte) error { - v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable - if len(f.index) > 1 { - v = v.fieldByIndex(f.index[1:], true) +func unmarshalInlinedFallbackNext(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct, f *structField, quotedName, unquotedName []byte) error { + v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable + if len(f.index) > 0 { + v = v.fieldByIndex(f.index, true) } v = v.indirect(true) - if v.Type() == rawValueType { - b := v.Addr().Interface().(*RawValue) + if v.Type() == jsontextValueType { + b := v.Addr().Interface().(*jsontext.Value) if len(*b) == 0 { // TODO: Should this be nil? What if it were all whitespace? *b = append(*b, '{') } else { - *b = trimSuffixWhitespace(*b) - if hasSuffixByte(*b, '}') { + *b = jsonwire.TrimSuffixWhitespace(*b) + if jsonwire.HasSuffixByte(*b, '}') { // TODO: When merging into an object for the first time, // should we verify that it is valid? - *b = trimSuffixByte(*b, '}') - *b = trimSuffixWhitespace(*b) - if !hasSuffixByte(*b, ',') && !hasSuffixByte(*b, '{') { + *b = jsonwire.TrimSuffixByte(*b, '}') + *b = jsonwire.TrimSuffixWhitespace(*b) + if !jsonwire.HasSuffixByte(*b, ',') && !jsonwire.HasSuffixByte(*b, '{') { *b = append(*b, ',') } } else { - err := errors.New("inlined raw value must be a JSON object") - return &SemanticError{action: "unmarshal", GoType: rawValueType, Err: err} + return newUnmarshalErrorAfterWithSkipping(dec, v.Type(), errRawInlinedNotObject) } } *b = append(*b, quotedName...) *b = append(*b, ':') - rawValue, err := dec.ReadValue() + val, err := dec.ReadValue() if err != nil { return err } - *b = append(*b, rawValue...) + *b = append(*b, val...) *b = append(*b, '}') return nil } else { name := string(unquotedName) // TODO: Intern this? - m := v // must be a map[string]V + m := v // must be a map[~string]V if m.IsNil() { m.Set(reflect.MakeMap(m.Type())) } mk := reflect.ValueOf(name) - mv := newAddressableValue(v.Type().Elem()) // TODO: Cache across calls? + if mkt := m.Type().Key(); mkt != stringType { + mk = mk.Convert(mkt) + } + mv := newAddressableValue(m.Type().Elem()) // TODO: Cache across calls? if v2 := m.MapIndex(mk); v2.IsValid() { mv.Set(v2) } unmarshal := f.fncs.unmarshal if uo.Unmarshalers != nil { - unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, mv.Type()) + unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, mv.Type()) } - err := unmarshal(uo, dec, mv) + err := unmarshal(dec, mv, uo) m.SetMapIndex(mk, mv.Value) if err != nil { return err diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go index 20899c868..42d6ee876 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go @@ -8,47 +8,60 @@ import ( "encoding" "errors" "reflect" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) +var errNonStringValue = errors.New("JSON value must be string type") + // Interfaces for custom serialization. var ( - jsonMarshalerV1Type = reflect.TypeOf((*MarshalerV1)(nil)).Elem() - jsonMarshalerV2Type = reflect.TypeOf((*MarshalerV2)(nil)).Elem() - jsonUnmarshalerV1Type = reflect.TypeOf((*UnmarshalerV1)(nil)).Elem() - jsonUnmarshalerV2Type = reflect.TypeOf((*UnmarshalerV2)(nil)).Elem() - textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + jsonMarshalerType = reflect.TypeFor[Marshaler]() + jsonMarshalerToType = reflect.TypeFor[MarshalerTo]() + jsonUnmarshalerType = reflect.TypeFor[Unmarshaler]() + jsonUnmarshalerFromType = reflect.TypeFor[UnmarshalerFrom]() + textAppenderType = reflect.TypeFor[encoding.TextAppender]() + textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]() + textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]() + + allMarshalerTypes = []reflect.Type{jsonMarshalerToType, jsonMarshalerType, textAppenderType, textMarshalerType} + allUnmarshalerTypes = []reflect.Type{jsonUnmarshalerFromType, jsonUnmarshalerType, textUnmarshalerType} + allMethodTypes = append(allMarshalerTypes, allUnmarshalerTypes...) ) -// MarshalerV1 is implemented by types that can marshal themselves. -// It is recommended that types implement MarshalerV2 unless the implementation +// Marshaler is implemented by types that can marshal themselves. +// It is recommended that types implement [MarshalerTo] unless the implementation // is trying to avoid a hard dependency on the "jsontext" package. // // It is recommended that implementations return a buffer that is safe // for the caller to retain and potentially mutate. -type MarshalerV1 interface { +type Marshaler interface { MarshalJSON() ([]byte, error) } -// MarshalerV2 is implemented by types that can marshal themselves. -// It is recommended that types implement MarshalerV2 instead of MarshalerV1 +// MarshalerTo is implemented by types that can marshal themselves. +// It is recommended that types implement MarshalerTo instead of [Marshaler] // since this is both more performant and flexible. -// If a type implements both MarshalerV1 and MarshalerV2, -// then MarshalerV2 takes precedence. In such a case, both implementations +// If a type implements both Marshaler and MarshalerTo, +// then MarshalerTo takes precedence. In such a case, both implementations // should aim to have equivalent behavior for the default marshal options. // // The implementation must write only one JSON value to the Encoder and -// must not retain the pointer to Encoder. -type MarshalerV2 interface { - MarshalNextJSON(MarshalOptions, *Encoder) error +// must not retain the pointer to [jsontext.Encoder]. +type MarshalerTo interface { + MarshalJSONTo(*jsontext.Encoder) error - // TODO: Should users call the MarshalOptions.MarshalNext method or + // TODO: Should users call the MarshalEncode function or // should/can they call this method directly? Does it matter? } -// UnmarshalerV1 is implemented by types that can unmarshal themselves. -// It is recommended that types implement UnmarshalerV2 unless -// the implementation is trying to avoid a hard dependency on this package. +// Unmarshaler is implemented by types that can unmarshal themselves. +// It is recommended that types implement [UnmarshalerFrom] unless the implementation +// is trying to avoid a hard dependency on the "jsontext" package. // // The input can be assumed to be a valid encoding of a JSON value // if called from unmarshal functionality in this package. @@ -57,26 +70,26 @@ type MarshalerV2 interface { // unmarshaling into a pre-populated value. // // Implementations must not retain or mutate the input []byte. -type UnmarshalerV1 interface { +type Unmarshaler interface { UnmarshalJSON([]byte) error } -// UnmarshalerV2 is implemented by types that can unmarshal themselves. -// It is recommended that types implement UnmarshalerV2 instead of UnmarshalerV1 +// UnmarshalerFrom is implemented by types that can unmarshal themselves. +// It is recommended that types implement UnmarshalerFrom instead of [Unmarshaler] // since this is both more performant and flexible. -// If a type implements both UnmarshalerV1 and UnmarshalerV2, -// then UnmarshalerV2 takes precedence. In such a case, both implementations +// If a type implements both Unmarshaler and UnmarshalerFrom, +// then UnmarshalerFrom takes precedence. In such a case, both implementations // should aim to have equivalent behavior for the default unmarshal options. // // The implementation must read only one JSON value from the Decoder. -// It is recommended that UnmarshalNextJSON implement merge semantics when +// It is recommended that UnmarshalJSONFrom implement merge semantics when // unmarshaling into a pre-populated value. // -// Implementations must not retain the pointer to Decoder. -type UnmarshalerV2 interface { - UnmarshalNextJSON(UnmarshalOptions, *Decoder) error +// Implementations must not retain the pointer to [jsontext.Decoder]. +type UnmarshalerFrom interface { + UnmarshalJSONFrom(*jsontext.Decoder) error - // TODO: Should users call the UnmarshalOptions.UnmarshalNext method or + // TODO: Should users call the UnmarshalDecode function or // should/can they call this method directly? Does it matter? } @@ -88,114 +101,205 @@ func makeMethodArshaler(fncs *arshaler, t reflect.Type) *arshaler { return fncs } - // Handle custom marshaler. - switch which, needAddr := implementsWhich(t, jsonMarshalerV2Type, jsonMarshalerV1Type, textMarshalerType); which { - case jsonMarshalerV2Type: + if needAddr, ok := implements(t, textMarshalerType); ok { fncs.nonDefault = true - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - prevDepth, prevLength := enc.tokens.depthLength() - err := va.addrWhen(needAddr).Interface().(MarshalerV2).MarshalNextJSON(mo, enc) - currDepth, currLength := enc.tokens.depthLength() - if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil { - err = errors.New("must write exactly one JSON value") + prevMarshal := fncs.marshal + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + (needAddr && va.forcedAddr) { + return prevMarshal(enc, va, mo) } - if err != nil { + marshaler := va.Addr().Interface().(encoding.TextMarshaler) + if err := export.Encoder(enc).AppendRaw('"', false, func(b []byte) ([]byte, error) { + b2, err := marshaler.MarshalText() + return append(b, b2...), err + }); err != nil { err = wrapSkipFunc(err, "marshal method") - // TODO: Avoid wrapping semantic or I/O errors. - return &SemanticError{action: "marshal", GoType: t, Err: err} + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalText") // unlike unmarshal, always wrapped + } + if !isSemanticError(err) && !export.IsIOError(err) { + err = newMarshalErrorBefore(enc, t, err) + } + return err } return nil } - case jsonMarshalerV1Type: + } + + if needAddr, ok := implements(t, textAppenderType); ok { fncs.nonDefault = true - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - marshaler := va.addrWhen(needAddr).Interface().(MarshalerV1) - val, err := marshaler.MarshalJSON() - if err != nil { - err = wrapSkipFunc(err, "marshal method") - // TODO: Avoid wrapping semantic errors. - return &SemanticError{action: "marshal", GoType: t, Err: err} + prevMarshal := fncs.marshal + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) (err error) { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + (needAddr && va.forcedAddr) { + return prevMarshal(enc, va, mo) } - if err := enc.WriteValue(val); err != nil { - // TODO: Avoid wrapping semantic or I/O errors. - return &SemanticError{action: "marshal", JSONKind: RawValue(val).Kind(), GoType: t, Err: err} + appender := va.Addr().Interface().(encoding.TextAppender) + if err := export.Encoder(enc).AppendRaw('"', false, appender.AppendText); err != nil { + err = wrapSkipFunc(err, "append method") + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "AppendText") // unlike unmarshal, always wrapped + } + if !isSemanticError(err) && !export.IsIOError(err) { + err = newMarshalErrorBefore(enc, t, err) + } + return err } return nil } - case textMarshalerType: + } + + if needAddr, ok := implements(t, jsonMarshalerType); ok { fncs.nonDefault = true - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - marshaler := va.addrWhen(needAddr).Interface().(encoding.TextMarshaler) - s, err := marshaler.MarshalText() - if err != nil { - err = wrapSkipFunc(err, "marshal method") - // TODO: Avoid wrapping semantic errors. - return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} + prevMarshal := fncs.marshal + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + ((needAddr && va.forcedAddr) || export.Encoder(enc).Tokens.Last.NeedObjectName()) { + return prevMarshal(enc, va, mo) } - val := enc.UnusedBuffer() - val, err = appendString(val, string(s), true, nil) + marshaler := va.Addr().Interface().(Marshaler) + val, err := marshaler.MarshalJSON() if err != nil { - return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} + err = wrapSkipFunc(err, "marshal method") + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped + } + err = newMarshalErrorBefore(enc, t, err) + return collapseSemanticErrors(err) } if err := enc.WriteValue(val); err != nil { - // TODO: Avoid wrapping syntactic or I/O errors. - return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped + } + if isSyntacticError(err) { + err = newMarshalErrorBefore(enc, t, err) + } + return err } return nil } } - // Handle custom unmarshaler. - switch which, needAddr := implementsWhich(t, jsonUnmarshalerV2Type, jsonUnmarshalerV1Type, textUnmarshalerType); which { - case jsonUnmarshalerV2Type: + if needAddr, ok := implements(t, jsonMarshalerToType); ok { fncs.nonDefault = true - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - prevDepth, prevLength := dec.tokens.depthLength() - err := va.addrWhen(needAddr).Interface().(UnmarshalerV2).UnmarshalNextJSON(uo, dec) - currDepth, currLength := dec.tokens.depthLength() + prevMarshal := fncs.marshal + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + if mo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + ((needAddr && va.forcedAddr) || export.Encoder(enc).Tokens.Last.NeedObjectName()) { + return prevMarshal(enc, va, mo) + } + xe := export.Encoder(enc) + prevDepth, prevLength := xe.Tokens.DepthLength() + xe.Flags.Set(jsonflags.WithinArshalCall | 1) + err := va.Addr().Interface().(MarshalerTo).MarshalJSONTo(enc) + xe.Flags.Set(jsonflags.WithinArshalCall | 0) + currDepth, currLength := xe.Tokens.DepthLength() if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil { - err = errors.New("must read exactly one JSON value") + err = errNonSingularValue + } + if err != nil { + err = wrapSkipFunc(err, "marshal method") + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSONTo") // unlike unmarshal, always wrapped + } + if !export.IsIOError(err) { + err = newSemanticErrorWithPosition(enc, t, prevDepth, prevLength, err) + } + return err } + return nil + } + } + + if _, ok := implements(t, textUnmarshalerType); ok { + fncs.nonDefault = true + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + var flags jsonwire.ValueFlags + val, err := xd.ReadValue(&flags) if err != nil { + return err // must be a syntactic or I/O error + } + if val.Kind() == 'n' { + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + va.SetZero() + } + return nil + } + if val.Kind() != '"' { + return newUnmarshalErrorAfter(dec, t, errNonStringValue) + } + s := jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + unmarshaler := va.Addr().Interface().(encoding.TextUnmarshaler) + if err := unmarshaler.UnmarshalText(s); err != nil { err = wrapSkipFunc(err, "unmarshal method") - // TODO: Avoid wrapping semantic, syntactic, or I/O errors. - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err // unlike marshal, never wrapped + } + if !isSemanticError(err) && !isSyntacticError(err) && !export.IsIOError(err) { + err = newUnmarshalErrorAfter(dec, t, err) + } + return err } return nil } - case jsonUnmarshalerV1Type: + } + + if _, ok := implements(t, jsonUnmarshalerType); ok { fncs.nonDefault = true - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { + prevUnmarshal := fncs.unmarshal + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + if uo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + export.Decoder(dec).Tokens.Last.NeedObjectName() { + return prevUnmarshal(dec, va, uo) + } val, err := dec.ReadValue() if err != nil { return err // must be a syntactic or I/O error } - unmarshaler := va.addrWhen(needAddr).Interface().(UnmarshalerV1) + unmarshaler := va.Addr().Interface().(Unmarshaler) if err := unmarshaler.UnmarshalJSON(val); err != nil { err = wrapSkipFunc(err, "unmarshal method") - // TODO: Avoid wrapping semantic, syntactic, or I/O errors. - return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err // unlike marshal, never wrapped + } + err = newUnmarshalErrorAfter(dec, t, err) + return collapseSemanticErrors(err) } return nil } - case textUnmarshalerType: + } + + if _, ok := implements(t, jsonUnmarshalerFromType); ok { fncs.nonDefault = true - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - var flags valueFlags - val, err := dec.readValue(&flags) - if err != nil { - return err // must be a syntactic or I/O error + prevUnmarshal := fncs.unmarshal + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + if uo.Flags.Get(jsonflags.CallMethodsWithLegacySemantics) && + export.Decoder(dec).Tokens.Last.NeedObjectName() { + return prevUnmarshal(dec, va, uo) } - if val.Kind() != '"' { - err = errors.New("JSON value must be string type") - return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} + xd := export.Decoder(dec) + prevDepth, prevLength := xd.Tokens.DepthLength() + xd.Flags.Set(jsonflags.WithinArshalCall | 1) + err := va.Addr().Interface().(UnmarshalerFrom).UnmarshalJSONFrom(dec) + xd.Flags.Set(jsonflags.WithinArshalCall | 0) + currDepth, currLength := xd.Tokens.DepthLength() + if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil { + err = errNonSingularValue } - s := unescapeStringMayCopy(val, flags.isVerbatim()) - unmarshaler := va.addrWhen(needAddr).Interface().(encoding.TextUnmarshaler) - if err := unmarshaler.UnmarshalText(s); err != nil { + if err != nil { err = wrapSkipFunc(err, "unmarshal method") - // TODO: Avoid wrapping semantic, syntactic, or I/O errors. - return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + if err2 := xd.SkipUntil(prevDepth, prevLength+1); err2 != nil { + return err2 + } + return err // unlike marshal, never wrapped + } + if !isSyntacticError(err) && !export.IsIOError(err) { + err = newSemanticErrorWithPosition(dec, t, prevDepth, prevLength, err) + } + return err } return nil } @@ -204,26 +308,28 @@ func makeMethodArshaler(fncs *arshaler, t reflect.Type) *arshaler { return fncs } -// implementsWhich is like t.Implements(ifaceType) for a list of interfaces, +// implementsAny is like t.Implements(ifaceType) for a list of interfaces, // but checks whether either t or reflect.PointerTo(t) implements the interface. -// It returns the first interface type that matches and whether a value of t -// needs to be addressed first before it implements the interface. -func implementsWhich(t reflect.Type, ifaceTypes ...reflect.Type) (which reflect.Type, needAddr bool) { +func implementsAny(t reflect.Type, ifaceTypes ...reflect.Type) bool { for _, ifaceType := range ifaceTypes { - switch { - case t.Implements(ifaceType): - return ifaceType, false - case reflect.PointerTo(t).Implements(ifaceType): - return ifaceType, true + if _, ok := implements(t, ifaceType); ok { + return true } } - return nil, false + return false } -// addrWhen returns va.Addr if addr is specified, otherwise it returns itself. -func (va addressableValue) addrWhen(addr bool) reflect.Value { - if addr { - return va.Addr() +// implements is like t.Implements(ifaceType) but checks whether +// either t or reflect.PointerTo(t) implements the interface. +// It also reports whether the value needs to be addressed +// in order to satisfy the interface. +func implements(t, ifaceType reflect.Type) (needAddr, ok bool) { + switch { + case t.Implements(ifaceType): + return false, true + case reflect.PointerTo(t).Implements(ifaceType): + return true, true + default: + return false, false } - return va.Value } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go index fc8d5b007..30dd584d1 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go @@ -5,20 +5,31 @@ package json import ( + "bytes" + "cmp" "errors" "fmt" + "math" + "math/bits" "reflect" + "strconv" "strings" "time" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) var ( - timeDurationType = reflect.TypeOf((*time.Duration)(nil)).Elem() - timeTimeType = reflect.TypeOf((*time.Time)(nil)).Elem() + timeDurationType = reflect.TypeFor[time.Duration]() + timeTimeType = reflect.TypeFor[time.Time]() ) func makeTimeArshaler(fncs *arshaler, t reflect.Type) *arshaler { - // Ideally, time types would implement MarshalerV2 and UnmarshalerV2, + // Ideally, time types would implement MarshalerTo and UnmarshalerFrom, // but that would incur a dependency on package json from package time. // Given how widely used time is, it is more acceptable that we incur a // dependency on time from json. @@ -29,213 +40,736 @@ func makeTimeArshaler(fncs *arshaler, t reflect.Type) *arshaler { switch t { case timeDurationType: fncs.nonDefault = true - marshalNanos := fncs.marshal - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - if mo.format == "nanos" { - mo.format = "" - return marshalNanos(mo, enc, va) - } else { - return newInvalidFormatError("marshal", t, mo.format) + marshalNano := fncs.marshal + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) error { + xe := export.Encoder(enc) + var m durationArshaler + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + if !m.initFormat(mo.Format) { + return newInvalidFormatError(enc, t) } + } else if mo.Flags.Get(jsonflags.FormatDurationAsNano) { + return marshalNano(enc, va, mo) + } else { + // TODO(https://go.dev/issue/71631): Decide on default duration representation. + return newMarshalErrorBefore(enc, t, errors.New("no default representation (see https://go.dev/issue/71631); specify an explicit format")) } - td := va.Interface().(time.Duration) - b := enc.UnusedBuffer() - b = append(b, '"') - b = append(b, td.String()...) // never contains special characters - b = append(b, '"') - return enc.WriteValue(b) - } - unmarshalNanos := fncs.unmarshal - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - // TODO: Should there be a flag that specifies that we can unmarshal - // from either form since there would be no ambiguity? - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - if uo.format == "nanos" { - uo.format = "" - return unmarshalNanos(uo, dec, va) - } else { - return newInvalidFormatError("unmarshal", t, uo.format) + // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo. + m.td = *va.Addr().Interface().(*time.Duration) + k := stringOrNumberKind(!m.isNumeric() || xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers)) + if err := xe.AppendRaw(k, true, m.appendMarshal); err != nil { + if !isSyntacticError(err) && !export.IsIOError(err) { + err = newMarshalErrorBefore(enc, t, err) + } + return err + } + return nil + } + unmarshalNano := fncs.unmarshal + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) error { + xd := export.Decoder(dec) + var u durationArshaler + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + if !u.initFormat(uo.Format) { + return newInvalidFormatError(dec, t) } + } else if uo.Flags.Get(jsonflags.FormatDurationAsNano) { + return unmarshalNano(dec, va, uo) + } else { + // TODO(https://go.dev/issue/71631): Decide on default duration representation. + return newUnmarshalErrorBeforeWithSkipping(dec, t, errors.New("no default representation (see https://go.dev/issue/71631); specify an explicit format")) } - var flags valueFlags + stringify := !u.isNumeric() || xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers) + var flags jsonwire.ValueFlags td := va.Addr().Interface().(*time.Duration) - val, err := dec.readValue(&flags) + val, err := xd.ReadValue(&flags) if err != nil { return err } switch k := val.Kind(); k { case 'n': - *td = time.Duration(0) + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + *td = time.Duration(0) + } return nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) - td2, err := time.ParseDuration(string(val)) - if err != nil { - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + if !stringify { + break + } + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if err := u.unmarshal(val); err != nil { + return newUnmarshalErrorAfter(dec, t, err) + } + *td = u.td + return nil + case '0': + if stringify { + break + } + if err := u.unmarshal(val); err != nil { + return newUnmarshalErrorAfter(dec, t, err) } - *td = td2 + *td = u.td return nil - default: - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } + return newUnmarshalErrorAfter(dec, t, nil) } case timeTimeType: fncs.nonDefault = true - fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { - format := time.RFC3339Nano - isRFC3339 := true - if mo.format != "" && mo.formatDepth == enc.tokens.depth() { - var err error - format, isRFC3339, err = checkTimeFormat(mo.format) - if err != nil { - return &SemanticError{action: "marshal", GoType: t, Err: err} + fncs.marshal = func(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct) (err error) { + xe := export.Encoder(enc) + var m timeArshaler + if mo.Format != "" && mo.FormatDepth == xe.Tokens.Depth() { + if !m.initFormat(mo.Format) { + return newInvalidFormatError(enc, t) } } - tt := va.Interface().(time.Time) - b := enc.UnusedBuffer() - b = append(b, '"') - b = tt.AppendFormat(b, format) - b = append(b, '"') - if isRFC3339 { - // Not all Go timestamps can be represented as valid RFC 3339. - // Explicitly check for these edge cases. - // See https://go.dev/issue/4556 and https://go.dev/issue/54580. - var err error - switch b := b[len(`"`) : len(b)-len(`"`)]; { - case b[len("9999")] != '-': // year must be exactly 4 digits wide - err = errors.New("year outside of range [0,9999]") - case b[len(b)-1] != 'Z': - c := b[len(b)-len("Z07:00")] - if ('0' <= c && c <= '9') || parseDec2(b[len(b)-len("07:00"):]) >= 24 { - err = errors.New("timezone hour outside of range [0,23]") - } + // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo. + m.tt = *va.Addr().Interface().(*time.Time) + k := stringOrNumberKind(!m.isNumeric() || xe.Tokens.Last.NeedObjectName() || mo.Flags.Get(jsonflags.StringifyNumbers)) + if err := xe.AppendRaw(k, !m.hasCustomFormat(), m.appendMarshal); err != nil { + if mo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return internal.NewMarshalerError(va.Addr().Interface(), err, "MarshalJSON") // unlike unmarshal, always wrapped } - if err != nil { - return &SemanticError{action: "marshal", GoType: t, Err: err} + if !isSyntacticError(err) && !export.IsIOError(err) { + err = newMarshalErrorBefore(enc, t, err) } - return enc.WriteValue(b) // RFC 3339 never needs JSON escaping - } - // The format may contain special characters that need escaping. - // Verify that the result is a valid JSON string (common case), - // otherwise escape the string correctly (slower case). - if consumeSimpleString(b) != len(b) { - b, _ = appendString(nil, string(b[len(`"`):len(b)-len(`"`)]), true, nil) + return err } - return enc.WriteValue(b) + return nil } - fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { - format := time.RFC3339 - isRFC3339 := true - if uo.format != "" && uo.formatDepth == dec.tokens.depth() { - var err error - format, isRFC3339, err = checkTimeFormat(uo.format) - if err != nil { - return &SemanticError{action: "unmarshal", GoType: t, Err: err} + fncs.unmarshal = func(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct) (err error) { + xd := export.Decoder(dec) + var u timeArshaler + if uo.Format != "" && uo.FormatDepth == xd.Tokens.Depth() { + if !u.initFormat(uo.Format) { + return newInvalidFormatError(dec, t) } + } else if uo.Flags.Get(jsonflags.ParseTimeWithLooseRFC3339) { + u.looseRFC3339 = true } - var flags valueFlags + stringify := !u.isNumeric() || xd.Tokens.Last.NeedObjectName() || uo.Flags.Get(jsonflags.StringifyNumbers) + var flags jsonwire.ValueFlags tt := va.Addr().Interface().(*time.Time) - val, err := dec.readValue(&flags) + val, err := xd.ReadValue(&flags) if err != nil { return err } - k := val.Kind() - switch k { + switch k := val.Kind(); k { case 'n': - *tt = time.Time{} + if !uo.Flags.Get(jsonflags.MergeWithLegacySemantics) { + *tt = time.Time{} + } return nil case '"': - val = unescapeStringMayCopy(val, flags.isVerbatim()) - tt2, err := time.Parse(format, string(val)) - if isRFC3339 && err == nil { - // TODO(https://go.dev/issue/54580): RFC 3339 specifies - // the exact grammar of a valid timestamp. However, - // the parsing functionality in "time" is too loose and - // incorrectly accepts invalid timestamps as valid. - // Remove these manual checks when "time" checks it for us. - newParseError := func(layout, value, layoutElem, valueElem, message string) error { - return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message} - } - switch { - case val[len("2006-01-02T")+1] == ':': // hour must be two digits - err = newParseError(format, string(val), "15", string(val[len("2006-01-02T"):][:1]), "") - case val[len("2006-01-02T15:04:05")] == ',': // sub-second separator must be a period - err = newParseError(format, string(val), ".", ",", "") - case val[len(val)-1] != 'Z': - switch { - case parseDec2(val[len(val)-len("07:00"):]) >= 24: // timezone hour must be in range - err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone hour out of range") - case parseDec2(val[len(val)-len("00"):]) >= 60: // timezone minute must be in range - err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone minute out of range") - } + if !stringify { + break + } + val = jsonwire.UnquoteMayCopy(val, flags.IsVerbatim()) + if err := u.unmarshal(val); err != nil { + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err // unlike marshal, never wrapped } + return newUnmarshalErrorAfter(dec, t, err) + } + *tt = u.tt + return nil + case '0': + if stringify { + break } - if err != nil { - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} + if err := u.unmarshal(val); err != nil { + if uo.Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + return err // unlike marshal, never wrapped + } + return newUnmarshalErrorAfter(dec, t, err) } - *tt = tt2 + *tt = u.tt return nil - default: - return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } + return newUnmarshalErrorAfter(dec, t, nil) } } return fncs } -func checkTimeFormat(format string) (string, bool, error) { +type durationArshaler struct { + td time.Duration + + // base records the representation where: + // - 0 uses time.Duration.String + // - 1e0, 1e3, 1e6, or 1e9 use a decimal encoding of the duration as + // nanoseconds, microseconds, milliseconds, or seconds. + // - 8601 uses ISO 8601 + base uint64 +} + +func (a *durationArshaler) initFormat(format string) (ok bool) { + switch format { + case "units": + a.base = 0 + case "sec": + a.base = 1e9 + case "milli": + a.base = 1e6 + case "micro": + a.base = 1e3 + case "nano": + a.base = 1e0 + case "iso8601": + a.base = 8601 + default: + return false + } + return true +} + +func (a *durationArshaler) isNumeric() bool { + return a.base != 0 && a.base != 8601 +} + +func (a *durationArshaler) appendMarshal(b []byte) ([]byte, error) { + switch a.base { + case 0: + return append(b, a.td.String()...), nil + case 8601: + return appendDurationISO8601(b, a.td), nil + default: + return appendDurationBase10(b, a.td, a.base), nil + } +} + +func (a *durationArshaler) unmarshal(b []byte) (err error) { + switch a.base { + case 0: + a.td, err = time.ParseDuration(string(b)) + case 8601: + a.td, err = parseDurationISO8601(b) + default: + a.td, err = parseDurationBase10(b, a.base) + } + return err +} + +type timeArshaler struct { + tt time.Time + + // base records the representation where: + // - 0 uses RFC 3339 encoding of the timestamp + // - 1e0, 1e3, 1e6, or 1e9 use a decimal encoding of the timestamp as + // seconds, milliseconds, microseconds, or nanoseconds since Unix epoch. + // - math.MaxUint uses time.Time.Format to encode the timestamp + base uint64 + format string // time format passed to time.Parse + + looseRFC3339 bool +} + +func (a *timeArshaler) initFormat(format string) bool { // We assume that an exported constant in the time package will // always start with an uppercase ASCII letter. - if len(format) > 0 && 'A' <= format[0] && format[0] <= 'Z' { - switch format { - case "ANSIC": - return time.ANSIC, false, nil - case "UnixDate": - return time.UnixDate, false, nil - case "RubyDate": - return time.RubyDate, false, nil - case "RFC822": - return time.RFC822, false, nil - case "RFC822Z": - return time.RFC822Z, false, nil - case "RFC850": - return time.RFC850, false, nil - case "RFC1123": - return time.RFC1123, false, nil - case "RFC1123Z": - return time.RFC1123Z, false, nil - case "RFC3339": - return time.RFC3339, true, nil - case "RFC3339Nano": - return time.RFC3339Nano, true, nil - case "Kitchen": - return time.Kitchen, false, nil - case "Stamp": - return time.Stamp, false, nil - case "StampMilli": - return time.StampMilli, false, nil - case "StampMicro": - return time.StampMicro, false, nil - case "StampNano": - return time.StampNano, false, nil - default: - // Reject any format that is an exported Go identifier in case - // new format constants are added to the time package. - if strings.TrimFunc(format, isLetterOrDigit) == "" { - return "", false, fmt.Errorf("undefined format layout: %v", format) + if len(format) == 0 { + return false + } + a.base = math.MaxUint // implies custom format + if c := format[0]; !('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') { + a.format = format + return true + } + switch format { + case "ANSIC": + a.format = time.ANSIC + case "UnixDate": + a.format = time.UnixDate + case "RubyDate": + a.format = time.RubyDate + case "RFC822": + a.format = time.RFC822 + case "RFC822Z": + a.format = time.RFC822Z + case "RFC850": + a.format = time.RFC850 + case "RFC1123": + a.format = time.RFC1123 + case "RFC1123Z": + a.format = time.RFC1123Z + case "RFC3339": + a.base = 0 + a.format = time.RFC3339 + case "RFC3339Nano": + a.base = 0 + a.format = time.RFC3339Nano + case "Kitchen": + a.format = time.Kitchen + case "Stamp": + a.format = time.Stamp + case "StampMilli": + a.format = time.StampMilli + case "StampMicro": + a.format = time.StampMicro + case "StampNano": + a.format = time.StampNano + case "DateTime": + a.format = time.DateTime + case "DateOnly": + a.format = time.DateOnly + case "TimeOnly": + a.format = time.TimeOnly + case "unix": + a.base = 1e0 + case "unixmilli": + a.base = 1e3 + case "unixmicro": + a.base = 1e6 + case "unixnano": + a.base = 1e9 + default: + // Reject any Go identifier in case new constants are supported. + if strings.TrimFunc(format, isLetterOrDigit) == "" { + return false + } + a.format = format + } + return true +} + +func (a *timeArshaler) isNumeric() bool { + return int(a.base) > 0 +} + +func (a *timeArshaler) hasCustomFormat() bool { + return a.base == math.MaxUint +} + +func (a *timeArshaler) appendMarshal(b []byte) ([]byte, error) { + switch a.base { + case 0: + format := cmp.Or(a.format, time.RFC3339Nano) + n0 := len(b) + b = a.tt.AppendFormat(b, format) + // Not all Go timestamps can be represented as valid RFC 3339. + // Explicitly check for these edge cases. + // See https://go.dev/issue/4556 and https://go.dev/issue/54580. + switch b := b[n0:]; { + case b[len("9999")] != '-': // year must be exactly 4 digits wide + return b, errors.New("year outside of range [0,9999]") + case b[len(b)-1] != 'Z': + c := b[len(b)-len("Z07:00")] + if ('0' <= c && c <= '9') || parseDec2(b[len(b)-len("07:00"):]) >= 24 { + return b, errors.New("timezone hour outside of range [0,23]") } } + return b, nil + case math.MaxUint: + return a.tt.AppendFormat(b, a.format), nil + default: + return appendTimeUnix(b, a.tt, a.base), nil } - return format, false, nil +} + +func (a *timeArshaler) unmarshal(b []byte) (err error) { + switch a.base { + case 0: + // Use time.Time.UnmarshalText to avoid possible string allocation. + if err := a.tt.UnmarshalText(b); err != nil { + return err + } + // TODO(https://go.dev/issue/57912): + // RFC 3339 specifies the grammar for a valid timestamp. + // However, the parsing functionality in "time" is too loose and + // incorrectly accepts invalid timestamps as valid. + // Remove these manual checks when "time" checks it for us. + newParseError := func(layout, value, layoutElem, valueElem, message string) error { + return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message} + } + switch { + case a.looseRFC3339: + return nil + case b[len("2006-01-02T")+1] == ':': // hour must be two digits + return newParseError(time.RFC3339, string(b), "15", string(b[len("2006-01-02T"):][:1]), "") + case b[len("2006-01-02T15:04:05")] == ',': // sub-second separator must be a period + return newParseError(time.RFC3339, string(b), ".", ",", "") + case b[len(b)-1] != 'Z': + switch { + case parseDec2(b[len(b)-len("07:00"):]) >= 24: // timezone hour must be in range + return newParseError(time.RFC3339, string(b), "Z07:00", string(b[len(b)-len("Z07:00"):]), ": timezone hour out of range") + case parseDec2(b[len(b)-len("00"):]) >= 60: // timezone minute must be in range + return newParseError(time.RFC3339, string(b), "Z07:00", string(b[len(b)-len("Z07:00"):]), ": timezone minute out of range") + } + } + return nil + case math.MaxUint: + a.tt, err = time.Parse(a.format, string(b)) + return err + default: + a.tt, err = parseTimeUnix(b, a.base) + return err + } +} + +// appendDurationBase10 appends d formatted as a decimal fractional number, +// where pow10 is a power-of-10 used to scale down the number. +func appendDurationBase10(b []byte, d time.Duration, pow10 uint64) []byte { + b, n := mayAppendDurationSign(b, d) // append sign + whole, frac := bits.Div64(0, n, uint64(pow10)) // compute whole and frac fields + b = strconv.AppendUint(b, whole, 10) // append whole field + return appendFracBase10(b, frac, pow10) // append frac field +} + +// parseDurationBase10 parses d from a decimal fractional number, +// where pow10 is a power-of-10 used to scale up the number. +func parseDurationBase10(b []byte, pow10 uint64) (time.Duration, error) { + suffix, neg := consumeSign(b, false) // consume sign + wholeBytes, fracBytes := bytesCutByte(suffix, '.', true) // consume whole and frac fields + whole, okWhole := jsonwire.ParseUint(wholeBytes) // parse whole field; may overflow + frac, okFrac := parseFracBase10(fracBytes, pow10) // parse frac field + hi, lo := bits.Mul64(whole, uint64(pow10)) // overflow if hi > 0 + sum, co := bits.Add64(lo, uint64(frac), 0) // overflow if co > 0 + switch d := mayApplyDurationSign(sum, neg); { // overflow if neg != (d < 0) + case (!okWhole && whole != math.MaxUint64) || !okFrac: + return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrSyntax) + case !okWhole || hi > 0 || co > 0 || neg != (d < 0): + return 0, fmt.Errorf("invalid duration %q: %w", b, strconv.ErrRange) + default: + return d, nil + } +} + +// appendDurationISO8601 appends an ISO 8601 duration with a restricted grammar, +// where leading and trailing zeroes and zero-value designators are omitted. +// It only uses hour, minute, and second designators since ISO 8601 defines +// those as being "accurate", while year, month, week, and day are "nominal". +func appendDurationISO8601(b []byte, d time.Duration) []byte { + if d == 0 { + return append(b, "PT0S"...) + } + b, n := mayAppendDurationSign(b, d) + b = append(b, "PT"...) + n, nsec := bits.Div64(0, n, 1e9) // compute nsec field + n, sec := bits.Div64(0, n, 60) // compute sec field + hour, min := bits.Div64(0, n, 60) // compute hour and min fields + if hour > 0 { + b = append(strconv.AppendUint(b, hour, 10), 'H') + } + if min > 0 { + b = append(strconv.AppendUint(b, min, 10), 'M') + } + if sec > 0 || nsec > 0 { + b = append(appendFracBase10(strconv.AppendUint(b, sec, 10), nsec, 1e9), 'S') + } + return b +} + +// daysPerYear is the exact average number of days in a year according to +// the Gregorian calender, which has an extra day each year that is +// a multiple of 4, unless it is evenly divisible by 100 but not by 400. +// This does not take into account leap seconds, which are not deterministic. +const daysPerYear = 365.2425 + +var errInaccurateDateUnits = errors.New("inaccurate year, month, week, or day units") + +// parseDurationISO8601 parses a duration according to ISO 8601-1:2019, +// section 5.5.2.2 and 5.5.2.3 with the following restrictions or extensions: +// +// - A leading minus sign is permitted for negative duration according +// to ISO 8601-2:2019, section 4.4.1.9. We do not permit negative values +// for each "time scale component", which is permitted by section 4.4.1.1, +// but rarely supported by parsers. +// +// - A leading plus sign is permitted (and ignored). +// This is not required by ISO 8601, but not forbidden either. +// There is some precedent for this as it is supported by the principle of +// duration arithmetic as specified in ISO 8601-2-2019, section 14.1. +// Of note, the JavaScript grammar for ISO 8601 permits a leading plus sign. +// +// - A fractional value is only permitted for accurate units +// (i.e., hour, minute, and seconds) in the last time component, +// which is permissible by ISO 8601-1:2019, section 5.5.2.3. +// +// - Both periods ('.') and commas (',') are supported as the separator +// between the integer part and fraction part of a number, +// as specified in ISO 8601-1:2019, section 3.2.6. +// While ISO 8601 recommends comma as the default separator, +// most formatters uses a period. +// +// - Leading zeros are ignored. This is not required by ISO 8601, +// but also not forbidden by the standard. Many parsers support this. +// +// - Lowercase designators are supported. This is not required by ISO 8601, +// but also not forbidden by the standard. Many parsers support this. +// +// If the nominal units of year, month, week, or day are present, +// this produces a best-effort value and also reports [errInaccurateDateUnits]. +// +// The accepted grammar is identical to JavaScript's Duration: +// +// https://tc39.es/proposal-temporal/#prod-Duration +// +// We follow JavaScript's grammar as JSON itself is derived from JavaScript. +// The Temporal.Duration.toJSON method is guaranteed to produce an output +// that can be parsed by this function so long as arithmetic in JavaScript +// do not use a largestUnit value higher than "hours" (which is the default). +// Even if it does, this will do a best-effort parsing with inaccurate units, +// but report [errInaccurateDateUnits]. +func parseDurationISO8601(b []byte) (time.Duration, error) { + var invalid, overflow, inaccurate, sawFrac bool + var sumNanos, n, co uint64 + + // cutBytes is like [bytes.Cut], but uses either c0 or c1 as the separator. + cutBytes := func(b []byte, c0, c1 byte) (prefix, suffix []byte, ok bool) { + for i, c := range b { + if c == c0 || c == c1 { + return b[:i], b[i+1:], true + } + } + return b, nil, false + } + + // mayParseUnit attempts to parse another date or time number + // identified by the desHi and desLo unit characters. + // If the part is absent for current unit, it returns b as is. + mayParseUnit := func(b []byte, desHi, desLo byte, unit time.Duration) []byte { + number, suffix, ok := cutBytes(b, desHi, desLo) + if !ok || sawFrac { + return b // designator is not present or already saw fraction, which can only be in the last component + } + + // Parse the number. + // A fraction allowed for the accurate units in the last part. + whole, frac, ok := cutBytes(number, '.', ',') + if ok { + sawFrac = true + invalid = invalid || len(frac) == len("") || unit > time.Hour + if unit == time.Second { + n, ok = parsePaddedBase10(frac, uint64(time.Second)) + invalid = invalid || !ok + } else { + f, err := strconv.ParseFloat("0."+string(frac), 64) + invalid = invalid || err != nil || len(bytes.Trim(frac[len("."):], "0123456789")) > 0 + n = uint64(math.Round(f * float64(unit))) // never overflows since f is within [0..1] + } + sumNanos, co = bits.Add64(sumNanos, n, 0) // overflow if co > 0 + overflow = overflow || co > 0 + } + for len(whole) > 1 && whole[0] == '0' { + whole = whole[len("0"):] // trim leading zeros + } + n, ok := jsonwire.ParseUint(whole) // overflow if !ok && MaxUint64 + hi, lo := bits.Mul64(n, uint64(unit)) // overflow if hi > 0 + sumNanos, co = bits.Add64(sumNanos, lo, 0) // overflow if co > 0 + invalid = invalid || (!ok && n != math.MaxUint64) + overflow = overflow || (!ok && n == math.MaxUint64) || hi > 0 || co > 0 + inaccurate = inaccurate || unit > time.Hour + return suffix + } + + suffix, neg := consumeSign(b, true) + prefix, suffix, okP := cutBytes(suffix, 'P', 'p') + durDate, durTime, okT := cutBytes(suffix, 'T', 't') + invalid = invalid || len(prefix) > 0 || !okP || (okT && len(durTime) == 0) || len(durDate)+len(durTime) == 0 + if len(durDate) > 0 { // nominal portion of the duration + durDate = mayParseUnit(durDate, 'Y', 'y', time.Duration(daysPerYear*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'M', 'm', time.Duration(daysPerYear/12*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'W', 'w', time.Duration(7*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'D', 'd', time.Duration(24*60*60*1e9)) + invalid = invalid || len(durDate) > 0 // unknown elements + } + if len(durTime) > 0 { // accurate portion of the duration + durTime = mayParseUnit(durTime, 'H', 'h', time.Duration(60*60*1e9)) + durTime = mayParseUnit(durTime, 'M', 'm', time.Duration(60*1e9)) + durTime = mayParseUnit(durTime, 'S', 's', time.Duration(1e9)) + invalid = invalid || len(durTime) > 0 // unknown elements + } + d := mayApplyDurationSign(sumNanos, neg) + overflow = overflow || (neg != (d < 0) && d != 0) // overflows signed duration + + switch { + case invalid: + return 0, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, strconv.ErrSyntax) + case overflow: + return 0, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, strconv.ErrRange) + case inaccurate: + return d, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, errInaccurateDateUnits) + default: + return d, nil + } +} + +// mayAppendDurationSign appends a negative sign if n is negative. +func mayAppendDurationSign(b []byte, d time.Duration) ([]byte, uint64) { + if d < 0 { + b = append(b, '-') + d *= -1 + } + return b, uint64(d) +} + +// mayApplyDurationSign inverts n if neg is specified. +func mayApplyDurationSign(n uint64, neg bool) time.Duration { + if neg { + return -1 * time.Duration(n) + } else { + return +1 * time.Duration(n) + } +} + +// appendTimeUnix appends t formatted as a decimal fractional number, +// where pow10 is a power-of-10 used to scale up the number. +func appendTimeUnix(b []byte, t time.Time, pow10 uint64) []byte { + sec, nsec := t.Unix(), int64(t.Nanosecond()) + if sec < 0 { + b = append(b, '-') + sec, nsec = negateSecNano(sec, nsec) + } + switch { + case pow10 == 1e0: // fast case where units is in seconds + b = strconv.AppendUint(b, uint64(sec), 10) + return appendFracBase10(b, uint64(nsec), 1e9) + case uint64(sec) < 1e9: // intermediate case where units is not seconds, but no overflow + b = strconv.AppendUint(b, uint64(sec)*uint64(pow10)+uint64(uint64(nsec)/(1e9/pow10)), 10) + return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9) + default: // slow case where units is not seconds and overflow would occur + b = strconv.AppendUint(b, uint64(sec), 10) + b = appendPaddedBase10(b, uint64(nsec)/(1e9/pow10), pow10) + return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9) + } +} + +// parseTimeUnix parses t formatted as a decimal fractional number, +// where pow10 is a power-of-10 used to scale down the number. +func parseTimeUnix(b []byte, pow10 uint64) (time.Time, error) { + suffix, neg := consumeSign(b, false) // consume sign + wholeBytes, fracBytes := bytesCutByte(suffix, '.', true) // consume whole and frac fields + whole, okWhole := jsonwire.ParseUint(wholeBytes) // parse whole field; may overflow + frac, okFrac := parseFracBase10(fracBytes, 1e9/pow10) // parse frac field + var sec, nsec int64 + switch { + case pow10 == 1e0: // fast case where units is in seconds + sec = int64(whole) // check overflow later after negation + nsec = int64(frac) // cannot overflow + case okWhole: // intermediate case where units is not seconds, but no overflow + sec = int64(whole / pow10) // check overflow later after negation + nsec = int64((whole%pow10)*(1e9/pow10) + frac) // cannot overflow + case !okWhole && whole == math.MaxUint64: // slow case where units is not seconds and overflow occurred + width := int(math.Log10(float64(pow10))) // compute len(strconv.Itoa(pow10-1)) + whole, okWhole = jsonwire.ParseUint(wholeBytes[:len(wholeBytes)-width]) // parse the upper whole field + mid, _ := parsePaddedBase10(wholeBytes[len(wholeBytes)-width:], pow10) // parse the lower whole field + sec = int64(whole) // check overflow later after negation + nsec = int64(mid*(1e9/pow10) + frac) // cannot overflow + } + if neg { + sec, nsec = negateSecNano(sec, nsec) + } + switch t := time.Unix(sec, nsec).UTC(); { + case (!okWhole && whole != math.MaxUint64) || !okFrac: + return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrSyntax) + case !okWhole || neg != (t.Unix() < 0): + return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrRange) + default: + return t, nil + } +} + +// negateSecNano negates a Unix timestamp, where nsec must be within [0, 1e9). +func negateSecNano(sec, nsec int64) (int64, int64) { + sec = ^sec // twos-complement negation (i.e., -1*sec + 1) + nsec = -nsec + 1e9 // negate nsec and add 1e9 (which is the extra +1 from sec negation) + sec += int64(nsec / 1e9) // handle possible overflow of nsec if it started as zero + nsec %= 1e9 // ensure nsec stays within [0, 1e9) + return sec, nsec +} + +// appendFracBase10 appends the fraction of n/max10, +// where max10 is a power-of-10 that is larger than n. +func appendFracBase10(b []byte, n, max10 uint64) []byte { + if n == 0 { + return b + } + return bytes.TrimRight(appendPaddedBase10(append(b, '.'), n, max10), "0") +} + +// parseFracBase10 parses the fraction of n/max10, +// where max10 is a power-of-10 that is larger than n. +func parseFracBase10(b []byte, max10 uint64) (n uint64, ok bool) { + switch { + case len(b) == 0: + return 0, true + case len(b) < len(".0") || b[0] != '.': + return 0, false + } + return parsePaddedBase10(b[len("."):], max10) +} + +// appendPaddedBase10 appends a zero-padded encoding of n, +// where max10 is a power-of-10 that is larger than n. +func appendPaddedBase10(b []byte, n, max10 uint64) []byte { + if n < max10/10 { + // Formatting of n is shorter than log10(max10), + // so add max10/10 to ensure the length is equal to log10(max10). + i := len(b) + b = strconv.AppendUint(b, n+max10/10, 10) + b[i]-- // subtract the addition of max10/10 + return b + } + return strconv.AppendUint(b, n, 10) +} + +// parsePaddedBase10 parses b as the zero-padded encoding of n, +// where max10 is a power-of-10 that is larger than n. +// Truncated suffix is treated as implicit zeros. +// Extended suffix is ignored, but verified to contain only digits. +func parsePaddedBase10(b []byte, max10 uint64) (n uint64, ok bool) { + pow10 := uint64(1) + for pow10 < max10 { + n *= 10 + if len(b) > 0 { + if b[0] < '0' || '9' < b[0] { + return n, false + } + n += uint64(b[0] - '0') + b = b[1:] + } + pow10 *= 10 + } + if len(b) > 0 && len(bytes.TrimRight(b, "0123456789")) > 0 { + return n, false // trailing characters are not digits + } + return n, true +} + +// consumeSign consumes an optional leading negative or positive sign. +func consumeSign(b []byte, allowPlus bool) ([]byte, bool) { + if len(b) > 0 { + if b[0] == '-' { + return b[len("-"):], true + } else if b[0] == '+' && allowPlus { + return b[len("+"):], false + } + } + return b, false +} + +// bytesCutByte is similar to bytes.Cut(b, []byte{c}), +// except c may optionally be included as part of the suffix. +func bytesCutByte(b []byte, c byte, include bool) ([]byte, []byte) { + if i := bytes.IndexByte(b, c); i >= 0 { + if include { + return b[:i], b[i:] + } + return b[:i], b[i+1:] + } + return b, nil } // parseDec2 parses b as an unsigned, base-10, 2-digit number. -// It panics if len(b) < 2. The result is undefined if digits are not base-10. +// The result is undefined if digits are not base-10. func parseDec2(b []byte) byte { + if len(b) < 2 { + return 0 + } return 10*(b[0]-'0') + (b[1] - '0') } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go deleted file mode 100644 index 0d68b3233..000000000 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go +++ /dev/null @@ -1,1655 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package json - -import ( - "bytes" - "errors" - "io" - "math" - "strconv" - "unicode/utf16" - "unicode/utf8" -) - -// NOTE: The logic for decoding is complicated by the fact that reading from -// an io.Reader into a temporary buffer means that the buffer may contain a -// truncated portion of some valid input, requiring the need to fetch more data. -// -// This file is structured in the following way: -// -// - consumeXXX functions parse an exact JSON token from a []byte. -// If the buffer appears truncated, then it returns io.ErrUnexpectedEOF. -// The consumeSimpleXXX functions are so named because they only handle -// a subset of the grammar for the JSON token being parsed. -// They do not handle the full grammar to keep these functions inlineable. -// -// - Decoder.consumeXXX methods parse the next JSON token from Decoder.buf, -// automatically fetching more input if necessary. These methods take -// a position relative to the start of Decoder.buf as an argument and -// return the end of the consumed JSON token as a position, -// also relative to the start of Decoder.buf. -// -// - In the event of an I/O errors or state machine violations, -// the implementation avoids mutating the state of Decoder -// (aside from the book-keeping needed to implement Decoder.fetch). -// For this reason, only Decoder.ReadToken and Decoder.ReadValue are -// responsible for updated Decoder.prevStart and Decoder.prevEnd. -// -// - For performance, much of the implementation uses the pattern of calling -// the inlineable consumeXXX functions first, and if more work is necessary, -// then it calls the slower Decoder.consumeXXX methods. -// TODO: Revisit this pattern if the Go compiler provides finer control -// over exactly which calls are inlined or not. - -// DecodeOptions configures how JSON decoding operates. -// The zero value is equivalent to the default settings, -// which is compliant with both RFC 7493 and RFC 8259. -type DecodeOptions struct { - requireKeyedLiterals - nonComparable - - // AllowDuplicateNames specifies that JSON objects may contain - // duplicate member names. Disabling the duplicate name check may provide - // computational and performance benefits, but breaks compliance with - // RFC 7493, section 2.3. The input will still be compliant with RFC 8259, - // which leaves the handling of duplicate names as unspecified behavior. - AllowDuplicateNames bool - - // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, - // which will be mangled as the Unicode replacement character, U+FFFD. - // This causes the decoder to break compliance with - // RFC 7493, section 2.1, and RFC 8259, section 8.1. - AllowInvalidUTF8 bool -} - -// Decoder is a streaming decoder for raw JSON tokens and values. -// It is used to read a stream of top-level JSON values, -// each separated by optional whitespace characters. -// -// ReadToken and ReadValue calls may be interleaved. -// For example, the following JSON value: -// -// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} -// -// can be parsed with the following calls (ignoring errors for brevity): -// -// d.ReadToken() // { -// d.ReadToken() // "name" -// d.ReadToken() // "value" -// d.ReadValue() // "array" -// d.ReadToken() // [ -// d.ReadToken() // null -// d.ReadToken() // false -// d.ReadValue() // true -// d.ReadToken() // 3.14159 -// d.ReadToken() // ] -// d.ReadValue() // "object" -// d.ReadValue() // {"k":"v"} -// d.ReadToken() // } -// -// The above is one of many possible sequence of calls and -// may not represent the most sensible method to call for any given token/value. -// For example, it is probably more common to call ReadToken to obtain a -// string token for object names. -type Decoder struct { - state - decodeBuffer - options DecodeOptions - - stringCache *stringCache // only used when unmarshaling -} - -// decodeBuffer is a buffer split into 4 segments: -// -// - buf[0:prevEnd] // already read portion of the buffer -// - buf[prevStart:prevEnd] // previously read value -// - buf[prevEnd:len(buf)] // unread portion of the buffer -// - buf[len(buf):cap(buf)] // unused portion of the buffer -// -// Invariants: -// -// 0 ≤ prevStart ≤ prevEnd ≤ len(buf) ≤ cap(buf) -type decodeBuffer struct { - peekPos int // non-zero if valid offset into buf for start of next token - peekErr error // implies peekPos is -1 - - buf []byte // may alias rd if it is a bytes.Buffer - prevStart int - prevEnd int - - // baseOffset is added to prevStart and prevEnd to obtain - // the absolute offset relative to the start of io.Reader stream. - baseOffset int64 - - rd io.Reader -} - -// NewDecoder constructs a new streaming decoder reading from r. -// -// If r is a bytes.Buffer, then the decoder parses directly from the buffer -// without first copying the contents to an intermediate buffer. -// Additional writes to the buffer must not occur while the decoder is in use. -func NewDecoder(r io.Reader) *Decoder { - return DecodeOptions{}.NewDecoder(r) -} - -// NewDecoder constructs a new streaming decoder reading from r -// configured with the provided options. -func (o DecodeOptions) NewDecoder(r io.Reader) *Decoder { - d := new(Decoder) - o.ResetDecoder(d, r) - return d -} - -// ResetDecoder resets a decoder such that it is reading afresh from r and -// configured with the provided options. -func (o DecodeOptions) ResetDecoder(d *Decoder, r io.Reader) { - if d == nil { - panic("json: invalid nil Decoder") - } - if r == nil { - panic("json: invalid nil io.Reader") - } - d.reset(nil, r, o) -} - -func (d *Decoder) reset(b []byte, r io.Reader, o DecodeOptions) { - d.state.reset() - d.decodeBuffer = decodeBuffer{buf: b, rd: r} - d.options = o -} - -// Reset resets a decoder such that it is reading afresh from r but -// keep any pre-existing decoder options. -func (d *Decoder) Reset(r io.Reader) { - d.options.ResetDecoder(d, r) -} - -var errBufferWriteAfterNext = errors.New("invalid bytes.Buffer.Write call after calling bytes.Buffer.Next") - -// fetch reads at least 1 byte from the underlying io.Reader. -// It returns io.ErrUnexpectedEOF if zero bytes were read and io.EOF was seen. -func (d *Decoder) fetch() error { - if d.rd == nil { - return io.ErrUnexpectedEOF - } - - // Inform objectNameStack that we are about to fetch new buffer content. - d.names.copyQuotedBuffer(d.buf) - - // Specialize bytes.Buffer for better performance. - if bb, ok := d.rd.(*bytes.Buffer); ok { - switch { - case bb.Len() == 0: - return io.ErrUnexpectedEOF - case len(d.buf) == 0: - d.buf = bb.Next(bb.Len()) // "read" all data in the buffer - return nil - default: - // This only occurs if a partially filled bytes.Buffer was provided - // and more data is written to it while Decoder is reading from it. - // This practice will lead to data corruption since future writes - // may overwrite the contents of the current buffer. - // - // The user is trying to use a bytes.Buffer as a pipe, - // but a bytes.Buffer is poor implementation of a pipe, - // the purpose-built io.Pipe should be used instead. - return &ioError{action: "read", err: errBufferWriteAfterNext} - } - } - - // Allocate initial buffer if empty. - if cap(d.buf) == 0 { - d.buf = make([]byte, 0, 64) - } - - // Check whether to grow the buffer. - const maxBufferSize = 4 << 10 - const growthSizeFactor = 2 // higher value is faster - const growthRateFactor = 2 // higher value is slower - // By default, grow if below the maximum buffer size. - grow := cap(d.buf) <= maxBufferSize/growthSizeFactor - // Growing can be expensive, so only grow - // if a sufficient number of bytes have been processed. - grow = grow && int64(cap(d.buf)) < d.previousOffsetEnd()/growthRateFactor - // If prevStart==0, then fetch was called in order to fetch more data - // to finish consuming a large JSON value contiguously. - // Grow if less than 25% of the remaining capacity is available. - // Note that this may cause the input buffer to exceed maxBufferSize. - grow = grow || (d.prevStart == 0 && len(d.buf) >= 3*cap(d.buf)/4) - - if grow { - // Allocate a new buffer and copy the contents of the old buffer over. - // TODO: Provide a hard limit on the maximum internal buffer size? - buf := make([]byte, 0, cap(d.buf)*growthSizeFactor) - d.buf = append(buf, d.buf[d.prevStart:]...) - } else { - // Move unread portion of the data to the front. - n := copy(d.buf[:cap(d.buf)], d.buf[d.prevStart:]) - d.buf = d.buf[:n] - } - d.baseOffset += int64(d.prevStart) - d.prevEnd -= d.prevStart - d.prevStart = 0 - - // Read more data into the internal buffer. - for { - n, err := d.rd.Read(d.buf[len(d.buf):cap(d.buf)]) - switch { - case n > 0: - d.buf = d.buf[:len(d.buf)+n] - return nil // ignore errors if any bytes are read - case err == io.EOF: - return io.ErrUnexpectedEOF - case err != nil: - return &ioError{action: "read", err: err} - default: - continue // Read returned (0, nil) - } - } -} - -const invalidateBufferByte = '#' // invalid starting character for JSON grammar - -// invalidatePreviousRead invalidates buffers returned by Peek and Read calls -// so that the first byte is an invalid character. -// This Hyrum-proofs the API against faulty application code that assumes -// values returned by ReadValue remain valid past subsequent Read calls. -func (d *decodeBuffer) invalidatePreviousRead() { - // Avoid mutating the buffer if d.rd is nil which implies that d.buf - // is provided by the user code and may not expect mutations. - isBytesBuffer := func(r io.Reader) bool { - _, ok := r.(*bytes.Buffer) - return ok - } - if d.rd != nil && !isBytesBuffer(d.rd) && d.prevStart < d.prevEnd && uint(d.prevStart) < uint(len(d.buf)) { - d.buf[d.prevStart] = invalidateBufferByte - d.prevStart = d.prevEnd - } -} - -// needMore reports whether there are no more unread bytes. -func (d *decodeBuffer) needMore(pos int) bool { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - return pos == len(d.buf) -} - -// injectSyntacticErrorWithPosition wraps a SyntacticError with the position, -// otherwise it returns the error as is. -// It takes a position relative to the start of the start of d.buf. -func (d *decodeBuffer) injectSyntacticErrorWithPosition(err error, pos int) error { - if serr, ok := err.(*SyntacticError); ok { - return serr.withOffset(d.baseOffset + int64(pos)) - } - return err -} - -func (d *decodeBuffer) previousOffsetStart() int64 { return d.baseOffset + int64(d.prevStart) } -func (d *decodeBuffer) previousOffsetEnd() int64 { return d.baseOffset + int64(d.prevEnd) } -func (d *decodeBuffer) previousBuffer() []byte { return d.buf[d.prevStart:d.prevEnd] } -func (d *decodeBuffer) unreadBuffer() []byte { return d.buf[d.prevEnd:len(d.buf)] } - -// PeekKind retrieves the next token kind, but does not advance the read offset. -// It returns 0 if there are no more tokens. -func (d *Decoder) PeekKind() Kind { - // Check whether we have a cached peek result. - if d.peekPos > 0 { - return Kind(d.buf[d.peekPos]).normalize() - } - - var err error - d.invalidatePreviousRead() - pos := d.prevEnd - - // Consume leading whitespace. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { - err = io.EOF // EOF possibly if no Tokens present after top-level value - } - d.peekPos, d.peekErr = -1, err - return invalidKind - } - } - - // Consume colon or comma. - var delim byte - if c := d.buf[pos]; c == ':' || c == ',' { - delim = c - pos += 1 - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - d.peekPos, d.peekErr = -1, err - return invalidKind - } - } - } - next := Kind(d.buf[pos]).normalize() - if d.tokens.needDelim(next) != delim { - pos = d.prevEnd // restore position to right after leading whitespace - pos += consumeWhitespace(d.buf[pos:]) - err = d.tokens.checkDelim(delim, next) - err = d.injectSyntacticErrorWithPosition(err, pos) - d.peekPos, d.peekErr = -1, err - return invalidKind - } - - // This may set peekPos to zero, which is indistinguishable from - // the uninitialized state. While a small hit to performance, it is correct - // since ReadValue and ReadToken will disregard the cached result and - // recompute the next kind. - d.peekPos, d.peekErr = pos, nil - return next -} - -// SkipValue is semantically equivalent to calling ReadValue and discarding -// the result except that memory is not wasted trying to hold the entire result. -func (d *Decoder) SkipValue() error { - switch d.PeekKind() { - case '{', '[': - // For JSON objects and arrays, keep skipping all tokens - // until the depth matches the starting depth. - depth := d.tokens.depth() - for { - if _, err := d.ReadToken(); err != nil { - return err - } - if depth >= d.tokens.depth() { - return nil - } - } - default: - // Trying to skip a value when the next token is a '}' or ']' - // will result in an error being returned here. - if _, err := d.ReadValue(); err != nil { - return err - } - return nil - } -} - -// ReadToken reads the next Token, advancing the read offset. -// The returned token is only valid until the next Peek, Read, or Skip call. -// It returns io.EOF if there are no more tokens. -func (d *Decoder) ReadToken() (Token, error) { - // Determine the next kind. - var err error - var next Kind - pos := d.peekPos - if pos != 0 { - // Use cached peek result. - if d.peekErr != nil { - err := d.peekErr - d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error - return Token{}, err - } - next = Kind(d.buf[pos]).normalize() - d.peekPos = 0 // reset cache - } else { - d.invalidatePreviousRead() - pos = d.prevEnd - - // Consume leading whitespace. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { - err = io.EOF // EOF possibly if no Tokens present after top-level value - } - return Token{}, err - } - } - - // Consume colon or comma. - var delim byte - if c := d.buf[pos]; c == ':' || c == ',' { - delim = c - pos += 1 - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return Token{}, err - } - } - } - next = Kind(d.buf[pos]).normalize() - if d.tokens.needDelim(next) != delim { - pos = d.prevEnd // restore position to right after leading whitespace - pos += consumeWhitespace(d.buf[pos:]) - err = d.tokens.checkDelim(delim, next) - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } - - // Handle the next token. - var n int - switch next { - case 'n': - if consumeNull(d.buf[pos:]) == 0 { - pos, err = d.consumeLiteral(pos, "null") - if err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } else { - pos += len("null") - } - if err = d.tokens.appendLiteral(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("null")) // report position at start of literal - } - d.prevStart, d.prevEnd = pos, pos - return Null, nil - - case 'f': - if consumeFalse(d.buf[pos:]) == 0 { - pos, err = d.consumeLiteral(pos, "false") - if err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } else { - pos += len("false") - } - if err = d.tokens.appendLiteral(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("false")) // report position at start of literal - } - d.prevStart, d.prevEnd = pos, pos - return False, nil - - case 't': - if consumeTrue(d.buf[pos:]) == 0 { - pos, err = d.consumeLiteral(pos, "true") - if err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } else { - pos += len("true") - } - if err = d.tokens.appendLiteral(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("true")) // report position at start of literal - } - d.prevStart, d.prevEnd = pos, pos - return True, nil - - case '"': - var flags valueFlags // TODO: Preserve this in Token? - if n = consumeSimpleString(d.buf[pos:]); n == 0 { - oldAbsPos := d.baseOffset + int64(pos) - pos, err = d.consumeString(&flags, pos) - newAbsPos := d.baseOffset + int64(pos) - n = int(newAbsPos - oldAbsPos) - if err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } else { - pos += n - } - if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { - if !d.tokens.last.isValidNamespace() { - return Token{}, errInvalidNamespace - } - if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { - err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string - } - d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds - } - if err = d.tokens.appendString(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string - } - d.prevStart, d.prevEnd = pos-n, pos - return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil - - case '0': - // NOTE: Since JSON numbers are not self-terminating, - // we need to make sure that the next byte is not part of a number. - if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { - oldAbsPos := d.baseOffset + int64(pos) - pos, err = d.consumeNumber(pos) - newAbsPos := d.baseOffset + int64(pos) - n = int(newAbsPos - oldAbsPos) - if err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - } else { - pos += n - } - if err = d.tokens.appendNumber(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of number - } - d.prevStart, d.prevEnd = pos-n, pos - return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil - - case '{': - if err = d.tokens.pushObject(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - if !d.options.AllowDuplicateNames { - d.names.push() - d.namespaces.push() - } - pos += 1 - d.prevStart, d.prevEnd = pos, pos - return ObjectStart, nil - - case '}': - if err = d.tokens.popObject(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - if !d.options.AllowDuplicateNames { - d.names.pop() - d.namespaces.pop() - } - pos += 1 - d.prevStart, d.prevEnd = pos, pos - return ObjectEnd, nil - - case '[': - if err = d.tokens.pushArray(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - pos += 1 - d.prevStart, d.prevEnd = pos, pos - return ArrayStart, nil - - case ']': - if err = d.tokens.popArray(); err != nil { - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } - pos += 1 - d.prevStart, d.prevEnd = pos, pos - return ArrayEnd, nil - - default: - err = newInvalidCharacterError(d.buf[pos:], "at start of token") - return Token{}, d.injectSyntacticErrorWithPosition(err, pos) - } -} - -type valueFlags uint - -const ( - _ valueFlags = (1 << iota) / 2 // powers of two starting with zero - - stringNonVerbatim // string cannot be naively treated as valid UTF-8 - stringNonCanonical // string not formatted according to RFC 8785, section 3.2.2.2. - // TODO: Track whether a number is a non-integer? -) - -func (f *valueFlags) set(f2 valueFlags) { *f |= f2 } -func (f valueFlags) isVerbatim() bool { return f&stringNonVerbatim == 0 } -func (f valueFlags) isCanonical() bool { return f&stringNonCanonical == 0 } - -// ReadValue returns the next raw JSON value, advancing the read offset. -// The value is stripped of any leading or trailing whitespace. -// The returned value is only valid until the next Peek, Read, or Skip call and -// may not be mutated while the Decoder remains in use. -// If the decoder is currently at the end token for an object or array, -// then it reports a SyntacticError and the internal state remains unchanged. -// It returns io.EOF if there are no more values. -func (d *Decoder) ReadValue() (RawValue, error) { - var flags valueFlags - return d.readValue(&flags) -} -func (d *Decoder) readValue(flags *valueFlags) (RawValue, error) { - // Determine the next kind. - var err error - var next Kind - pos := d.peekPos - if pos != 0 { - // Use cached peek result. - if d.peekErr != nil { - err := d.peekErr - d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error - return nil, err - } - next = Kind(d.buf[pos]).normalize() - d.peekPos = 0 // reset cache - } else { - d.invalidatePreviousRead() - pos = d.prevEnd - - // Consume leading whitespace. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { - err = io.EOF // EOF possibly if no Tokens present after top-level value - } - return nil, err - } - } - - // Consume colon or comma. - var delim byte - if c := d.buf[pos]; c == ':' || c == ',' { - delim = c - pos += 1 - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return nil, err - } - } - } - next = Kind(d.buf[pos]).normalize() - if d.tokens.needDelim(next) != delim { - pos = d.prevEnd // restore position to right after leading whitespace - pos += consumeWhitespace(d.buf[pos:]) - err = d.tokens.checkDelim(delim, next) - return nil, d.injectSyntacticErrorWithPosition(err, pos) - } - } - - // Handle the next value. - oldAbsPos := d.baseOffset + int64(pos) - pos, err = d.consumeValue(flags, pos) - newAbsPos := d.baseOffset + int64(pos) - n := int(newAbsPos - oldAbsPos) - if err != nil { - return nil, d.injectSyntacticErrorWithPosition(err, pos) - } - switch next { - case 'n', 't', 'f': - err = d.tokens.appendLiteral() - case '"': - if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { - if !d.tokens.last.isValidNamespace() { - err = errInvalidNamespace - break - } - if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { - err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} - break - } - d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds - } - err = d.tokens.appendString() - case '0': - err = d.tokens.appendNumber() - case '{': - if err = d.tokens.pushObject(); err != nil { - break - } - if err = d.tokens.popObject(); err != nil { - panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) - } - case '[': - if err = d.tokens.pushArray(); err != nil { - break - } - if err = d.tokens.popArray(); err != nil { - panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) - } - } - if err != nil { - return nil, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of value - } - d.prevEnd = pos - d.prevStart = pos - n - return d.buf[pos-n : pos : pos], nil -} - -// checkEOF verifies that the input has no more data. -func (d *Decoder) checkEOF() error { - switch pos, err := d.consumeWhitespace(d.prevEnd); err { - case nil: - return newInvalidCharacterError(d.buf[pos:], "after top-level value") - case io.ErrUnexpectedEOF: - return nil - default: - return err - } -} - -// consumeWhitespace consumes all whitespace starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the last whitespace. -// If it returns nil, there is guaranteed to at least be one unread byte. -// -// The following pattern is common in this implementation: -// -// pos += consumeWhitespace(d.buf[pos:]) -// if d.needMore(pos) { -// if pos, err = d.consumeWhitespace(pos); err != nil { -// return ... -// } -// } -// -// It is difficult to simplify this without sacrificing performance since -// consumeWhitespace must be inlined. The body of the if statement is -// executed only in rare situations where we need to fetch more data. -// Since fetching may return an error, we also need to check the error. -func (d *Decoder) consumeWhitespace(pos int) (newPos int, err error) { - for { - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - absPos := d.baseOffset + int64(pos) - err = d.fetch() // will mutate d.buf and invalidate pos - pos = int(absPos - d.baseOffset) - if err != nil { - return pos, err - } - continue - } - return pos, nil - } -} - -// consumeValue consumes a single JSON value starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the value. -func (d *Decoder) consumeValue(flags *valueFlags, pos int) (newPos int, err error) { - for { - var n int - var err error - switch next := Kind(d.buf[pos]).normalize(); next { - case 'n': - if n = consumeNull(d.buf[pos:]); n == 0 { - n, err = consumeLiteral(d.buf[pos:], "null") - } - case 'f': - if n = consumeFalse(d.buf[pos:]); n == 0 { - n, err = consumeLiteral(d.buf[pos:], "false") - } - case 't': - if n = consumeTrue(d.buf[pos:]); n == 0 { - n, err = consumeLiteral(d.buf[pos:], "true") - } - case '"': - if n = consumeSimpleString(d.buf[pos:]); n == 0 { - return d.consumeString(flags, pos) - } - case '0': - // NOTE: Since JSON numbers are not self-terminating, - // we need to make sure that the next byte is not part of a number. - if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { - return d.consumeNumber(pos) - } - case '{': - return d.consumeObject(flags, pos) - case '[': - return d.consumeArray(flags, pos) - default: - return pos, newInvalidCharacterError(d.buf[pos:], "at start of value") - } - if err == io.ErrUnexpectedEOF { - absPos := d.baseOffset + int64(pos) - err = d.fetch() // will mutate d.buf and invalidate pos - pos = int(absPos - d.baseOffset) - if err != nil { - return pos, err - } - continue - } - return pos + n, err - } -} - -// consumeLiteral consumes a single JSON literal starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the literal. -func (d *Decoder) consumeLiteral(pos int, lit string) (newPos int, err error) { - for { - n, err := consumeLiteral(d.buf[pos:], lit) - if err == io.ErrUnexpectedEOF { - absPos := d.baseOffset + int64(pos) - err = d.fetch() // will mutate d.buf and invalidate pos - pos = int(absPos - d.baseOffset) - if err != nil { - return pos, err - } - continue - } - return pos + n, err - } -} - -// consumeString consumes a single JSON string starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the string. -func (d *Decoder) consumeString(flags *valueFlags, pos int) (newPos int, err error) { - var n int - for { - n, err = consumeStringResumable(flags, d.buf[pos:], n, !d.options.AllowInvalidUTF8) - if err == io.ErrUnexpectedEOF { - absPos := d.baseOffset + int64(pos) - err = d.fetch() // will mutate d.buf and invalidate pos - pos = int(absPos - d.baseOffset) - if err != nil { - return pos, err - } - continue - } - return pos + n, err - } -} - -// consumeNumber consumes a single JSON number starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the number. -func (d *Decoder) consumeNumber(pos int) (newPos int, err error) { - var n int - var state consumeNumberState - for { - n, state, err = consumeNumberResumable(d.buf[pos:], n, state) - // NOTE: Since JSON numbers are not self-terminating, - // we need to make sure that the next byte is not part of a number. - if err == io.ErrUnexpectedEOF || d.needMore(pos+n) { - mayTerminate := err == nil - absPos := d.baseOffset + int64(pos) - err = d.fetch() // will mutate d.buf and invalidate pos - pos = int(absPos - d.baseOffset) - if err != nil { - if mayTerminate && err == io.ErrUnexpectedEOF { - return pos + n, nil - } - return pos, err - } - continue - } - return pos + n, err - } -} - -// consumeObject consumes a single JSON object starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the object. -func (d *Decoder) consumeObject(flags *valueFlags, pos int) (newPos int, err error) { - var n int - var names *objectNamespace - if !d.options.AllowDuplicateNames { - d.namespaces.push() - defer d.namespaces.pop() - names = d.namespaces.last() - } - - // Handle before start. - if d.buf[pos] != '{' { - panic("BUG: consumeObject must be called with a buffer that starts with '{'") - } - pos++ - - // Handle after start. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - if d.buf[pos] == '}' { - pos++ - return pos, nil - } - - for { - // Handle before name. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - var flags2 valueFlags - if n = consumeSimpleString(d.buf[pos:]); n == 0 { - oldAbsPos := d.baseOffset + int64(pos) - pos, err = d.consumeString(&flags2, pos) - newAbsPos := d.baseOffset + int64(pos) - n = int(newAbsPos - oldAbsPos) - flags.set(flags2) - if err != nil { - return pos, err - } - } else { - pos += n - } - if !d.options.AllowDuplicateNames && !names.insertQuoted(d.buf[pos-n:pos], flags2.isVerbatim()) { - return pos - n, &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} - } - - // Handle after name. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - if d.buf[pos] != ':' { - return pos, newInvalidCharacterError(d.buf[pos:], "after object name (expecting ':')") - } - pos++ - - // Handle before value. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - pos, err = d.consumeValue(flags, pos) - if err != nil { - return pos, err - } - - // Handle after value. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - switch d.buf[pos] { - case ',': - pos++ - continue - case '}': - pos++ - return pos, nil - default: - return pos, newInvalidCharacterError(d.buf[pos:], "after object value (expecting ',' or '}')") - } - } -} - -// consumeArray consumes a single JSON array starting at d.buf[pos:]. -// It returns the new position in d.buf immediately after the array. -func (d *Decoder) consumeArray(flags *valueFlags, pos int) (newPos int, err error) { - // Handle before start. - if d.buf[pos] != '[' { - panic("BUG: consumeArray must be called with a buffer that starts with '['") - } - pos++ - - // Handle after start. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - if d.buf[pos] == ']' { - pos++ - return pos, nil - } - - for { - // Handle before value. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - pos, err = d.consumeValue(flags, pos) - if err != nil { - return pos, err - } - - // Handle after value. - pos += consumeWhitespace(d.buf[pos:]) - if d.needMore(pos) { - if pos, err = d.consumeWhitespace(pos); err != nil { - return pos, err - } - } - switch d.buf[pos] { - case ',': - pos++ - continue - case ']': - pos++ - return pos, nil - default: - return pos, newInvalidCharacterError(d.buf[pos:], "after array value (expecting ',' or ']')") - } - } -} - -// InputOffset returns the current input byte offset. It gives the location -// of the next byte immediately after the most recently returned token or value. -// The number of bytes actually read from the underlying io.Reader may be more -// than this offset due to internal buffering effects. -func (d *Decoder) InputOffset() int64 { - return d.previousOffsetEnd() -} - -// UnreadBuffer returns the data remaining in the unread buffer, -// which may contain zero or more bytes. -// The returned buffer must not be mutated while Decoder continues to be used. -// The buffer contents are valid until the next Peek, Read, or Skip call. -func (d *Decoder) UnreadBuffer() []byte { - return d.unreadBuffer() -} - -// StackDepth returns the depth of the state machine for read JSON data. -// Each level on the stack represents a nested JSON object or array. -// It is incremented whenever an ObjectStart or ArrayStart token is encountered -// and decremented whenever an ObjectEnd or ArrayEnd token is encountered. -// The depth is zero-indexed, where zero represents the top-level JSON value. -func (d *Decoder) StackDepth() int { - // NOTE: Keep in sync with Encoder.StackDepth. - return d.tokens.depth() - 1 -} - -// StackIndex returns information about the specified stack level. -// It must be a number between 0 and StackDepth, inclusive. -// For each level, it reports the kind: -// -// - 0 for a level of zero, -// - '{' for a level representing a JSON object, and -// - '[' for a level representing a JSON array. -// -// It also reports the length of that JSON object or array. -// Each name and value in a JSON object is counted separately, -// so the effective number of members would be half the length. -// A complete JSON object must have an even length. -func (d *Decoder) StackIndex(i int) (Kind, int) { - // NOTE: Keep in sync with Encoder.StackIndex. - switch s := d.tokens.index(i); { - case i > 0 && s.isObject(): - return '{', s.length() - case i > 0 && s.isArray(): - return '[', s.length() - default: - return 0, s.length() - } -} - -// StackPointer returns a JSON Pointer (RFC 6901) to the most recently read value. -// Object names are only present if AllowDuplicateNames is false, otherwise -// object members are represented using their index within the object. -func (d *Decoder) StackPointer() string { - d.names.copyQuotedBuffer(d.buf) - return string(d.appendStackPointer(nil)) -} - -// consumeWhitespace consumes leading JSON whitespace per RFC 7159, section 2. -func consumeWhitespace(b []byte) (n int) { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - for len(b) > n && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { - n++ - } - return n -} - -// consumeNull consumes the next JSON null literal per RFC 7159, section 3. -// It returns 0 if it is invalid, in which case consumeLiteral should be used. -func consumeNull(b []byte) int { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - const literal = "null" - if len(b) >= len(literal) && string(b[:len(literal)]) == literal { - return len(literal) - } - return 0 -} - -// consumeFalse consumes the next JSON false literal per RFC 7159, section 3. -// It returns 0 if it is invalid, in which case consumeLiteral should be used. -func consumeFalse(b []byte) int { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - const literal = "false" - if len(b) >= len(literal) && string(b[:len(literal)]) == literal { - return len(literal) - } - return 0 -} - -// consumeTrue consumes the next JSON true literal per RFC 7159, section 3. -// It returns 0 if it is invalid, in which case consumeLiteral should be used. -func consumeTrue(b []byte) int { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - const literal = "true" - if len(b) >= len(literal) && string(b[:len(literal)]) == literal { - return len(literal) - } - return 0 -} - -// consumeLiteral consumes the next JSON literal per RFC 7159, section 3. -// If the input appears truncated, it returns io.ErrUnexpectedEOF. -func consumeLiteral(b []byte, lit string) (n int, err error) { - for i := 0; i < len(b) && i < len(lit); i++ { - if b[i] != lit[i] { - return i, newInvalidCharacterError(b[i:], "within literal "+lit+" (expecting "+strconv.QuoteRune(rune(lit[i]))+")") - } - } - if len(b) < len(lit) { - return len(b), io.ErrUnexpectedEOF - } - return len(lit), nil -} - -// consumeSimpleString consumes the next JSON string per RFC 7159, section 7 -// but is limited to the grammar for an ASCII string without escape sequences. -// It returns 0 if it is invalid or more complicated than a simple string, -// in which case consumeString should be called. -func consumeSimpleString(b []byte) (n int) { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - if len(b) > 0 && b[0] == '"' { - n++ - for len(b) > n && (' ' <= b[n] && b[n] != '\\' && b[n] != '"' && b[n] < utf8.RuneSelf) { - n++ - } - if len(b) > n && b[n] == '"' { - n++ - return n - } - } - return 0 -} - -// consumeString consumes the next JSON string per RFC 7159, section 7. -// If validateUTF8 is false, then this allows the presence of invalid UTF-8 -// characters within the string itself. -// It reports the number of bytes consumed and whether an error was encountered. -// If the input appears truncated, it returns io.ErrUnexpectedEOF. -func consumeString(flags *valueFlags, b []byte, validateUTF8 bool) (n int, err error) { - return consumeStringResumable(flags, b, 0, validateUTF8) -} - -// consumeStringResumable is identical to consumeString but supports resuming -// from a previous call that returned io.ErrUnexpectedEOF. -func consumeStringResumable(flags *valueFlags, b []byte, resumeOffset int, validateUTF8 bool) (n int, err error) { - // Consume the leading double quote. - switch { - case resumeOffset > 0: - n = resumeOffset // already handled the leading quote - case uint(len(b)) == 0: - return n, io.ErrUnexpectedEOF - case b[0] == '"': - n++ - default: - return n, newInvalidCharacterError(b[n:], `at start of string (expecting '"')`) - } - - // Consume every character in the string. - for uint(len(b)) > uint(n) { - // Optimize for long sequences of unescaped characters. - noEscape := func(c byte) bool { - return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"' - } - for uint(len(b)) > uint(n) && noEscape(b[n]) { - n++ - } - if uint(len(b)) <= uint(n) { - return n, io.ErrUnexpectedEOF - } - - // Check for terminating double quote. - if b[n] == '"' { - n++ - return n, nil - } - - switch r, rn := utf8.DecodeRune(b[n:]); { - // Handle UTF-8 encoded byte sequence. - // Due to specialized handling of ASCII above, we know that - // all normal sequences at this point must be 2 bytes or larger. - case rn > 1: - n += rn - // Handle escape sequence. - case r == '\\': - flags.set(stringNonVerbatim) - resumeOffset = n - if uint(len(b)) < uint(n+2) { - return resumeOffset, io.ErrUnexpectedEOF - } - switch r := b[n+1]; r { - case '/': - // Forward slash is the only character with 3 representations. - // Per RFC 8785, section 3.2.2.2., this must not be escaped. - flags.set(stringNonCanonical) - n += 2 - case '"', '\\', 'b', 'f', 'n', 'r', 't': - n += 2 - case 'u': - if uint(len(b)) < uint(n+6) { - if !hasEscapeSequencePrefix(b[n:]) { - flags.set(stringNonCanonical) - return n, &SyntacticError{str: "invalid escape sequence " + strconv.Quote(string(b[n:])) + " within string"} - } - return resumeOffset, io.ErrUnexpectedEOF - } - v1, ok := parseHexUint16(b[n+2 : n+6]) - if !ok { - flags.set(stringNonCanonical) - return n, &SyntacticError{str: "invalid escape sequence " + strconv.Quote(string(b[n:n+6])) + " within string"} - } - // Only certain control characters can use the \uFFFF notation - // for canonical formatting (per RFC 8785, section 3.2.2.2.). - switch v1 { - // \uFFFF notation not permitted for these characters. - case '\b', '\f', '\n', '\r', '\t': - flags.set(stringNonCanonical) - default: - // \uFFFF notation only permitted for control characters. - if v1 >= ' ' { - flags.set(stringNonCanonical) - } else { - // \uFFFF notation must be lower case. - for _, c := range b[n+2 : n+6] { - if 'A' <= c && c <= 'F' { - flags.set(stringNonCanonical) - } - } - } - } - n += 6 - - if validateUTF8 && utf16.IsSurrogate(rune(v1)) { - if uint(len(b)) >= uint(n+2) && (b[n] != '\\' || b[n+1] != 'u') { - return n, &SyntacticError{str: "invalid unpaired surrogate half within string"} - } - if uint(len(b)) < uint(n+6) { - if !hasEscapeSequencePrefix(b[n:]) { - flags.set(stringNonCanonical) - return n, &SyntacticError{str: "invalid escape sequence " + strconv.Quote(string(b[n:])) + " within string"} - } - return resumeOffset, io.ErrUnexpectedEOF - } - v2, ok := parseHexUint16(b[n+2 : n+6]) - if !ok { - return n, &SyntacticError{str: "invalid escape sequence " + strconv.Quote(string(b[n:n+6])) + " within string"} - } - if utf16.DecodeRune(rune(v1), rune(v2)) == utf8.RuneError { - return n, &SyntacticError{str: "invalid surrogate pair in string"} - } - n += 6 - } - default: - flags.set(stringNonCanonical) - return n, &SyntacticError{str: "invalid escape sequence " + strconv.Quote(string(b[n:n+2])) + " within string"} - } - // Handle invalid UTF-8. - case r == utf8.RuneError: - if !utf8.FullRune(b[n:]) { - return n, io.ErrUnexpectedEOF - } - flags.set(stringNonVerbatim | stringNonCanonical) - if validateUTF8 { - return n, &SyntacticError{str: "invalid UTF-8 within string"} - } - n++ - // Handle invalid control characters. - case r < ' ': - flags.set(stringNonVerbatim | stringNonCanonical) - return n, newInvalidCharacterError(b[n:], "within string (expecting non-control character)") - default: - panic("BUG: unhandled character " + quoteRune(b[n:])) - } - } - return n, io.ErrUnexpectedEOF -} - -// hasEscapeSequencePrefix reports whether b is possibly -// the truncated prefix of a \uFFFF escape sequence. -func hasEscapeSequencePrefix(b []byte) bool { - for i, c := range b { - switch { - case i == 0 && c != '\\': - return false - case i == 1 && c != 'u': - return false - case i >= 2 && i < 6 && !('0' <= c && c <= '9') && !('a' <= c && c <= 'f') && !('A' <= c && c <= 'F'): - return false - } - } - return true -} - -// unescapeString appends the unescaped form of a JSON string in src to dst. -// Any invalid UTF-8 within the string will be replaced with utf8.RuneError. -// The input must be an entire JSON string with no surrounding whitespace. -func unescapeString(dst, src []byte) (v []byte, ok bool) { - // Consume leading double quote. - if uint(len(src)) == 0 || src[0] != '"' { - return dst, false - } - i, n := 1, 1 - - // Consume every character until completion. - for uint(len(src)) > uint(n) { - // Optimize for long sequences of unescaped characters. - noEscape := func(c byte) bool { - return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"' - } - for uint(len(src)) > uint(n) && noEscape(src[n]) { - n++ - } - if uint(len(src)) <= uint(n) { - break - } - - // Check for terminating double quote. - if src[n] == '"' { - dst = append(dst, src[i:n]...) - n++ - return dst, len(src) == n - } - - switch r, rn := utf8.DecodeRune(src[n:]); { - // Handle UTF-8 encoded byte sequence. - // Due to specialized handling of ASCII above, we know that - // all normal sequences at this point must be 2 bytes or larger. - case rn > 1: - n += rn - // Handle escape sequence. - case r == '\\': - dst = append(dst, src[i:n]...) - if r < ' ' { - return dst, false // invalid control character or unescaped quote - } - - // Handle escape sequence. - if uint(len(src)) < uint(n+2) { - return dst, false // truncated escape sequence - } - switch r := src[n+1]; r { - case '"', '\\', '/': - dst = append(dst, r) - n += 2 - case 'b': - dst = append(dst, '\b') - n += 2 - case 'f': - dst = append(dst, '\f') - n += 2 - case 'n': - dst = append(dst, '\n') - n += 2 - case 'r': - dst = append(dst, '\r') - n += 2 - case 't': - dst = append(dst, '\t') - n += 2 - case 'u': - if uint(len(src)) < uint(n+6) { - return dst, false // truncated escape sequence - } - v1, ok := parseHexUint16(src[n+2 : n+6]) - if !ok { - return dst, false // invalid escape sequence - } - n += 6 - - // Check whether this is a surrogate half. - r := rune(v1) - if utf16.IsSurrogate(r) { - r = utf8.RuneError // assume failure unless the following succeeds - if uint(len(src)) >= uint(n+6) && src[n+0] == '\\' && src[n+1] == 'u' { - if v2, ok := parseHexUint16(src[n+2 : n+6]); ok { - if r = utf16.DecodeRune(rune(v1), rune(v2)); r != utf8.RuneError { - n += 6 - } - } - } - } - - dst = utf8.AppendRune(dst, r) - default: - return dst, false // invalid escape sequence - } - i = n - // Handle invalid UTF-8. - case r == utf8.RuneError: - // NOTE: An unescaped string may be longer than the escaped string - // because invalid UTF-8 bytes are being replaced. - dst = append(dst, src[i:n]...) - dst = append(dst, "\uFFFD"...) - n += rn - i = n - // Handle invalid control characters. - case r < ' ': - dst = append(dst, src[i:n]...) - return dst, false // invalid control character or unescaped quote - default: - panic("BUG: unhandled character " + quoteRune(src[n:])) - } - } - dst = append(dst, src[i:n]...) - return dst, false // truncated input -} - -// unescapeStringMayCopy returns the unescaped form of b. -// If there are no escaped characters, the output is simply a subslice of -// the input with the surrounding quotes removed. -// Otherwise, a new buffer is allocated for the output. -func unescapeStringMayCopy(b []byte, isVerbatim bool) []byte { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - if isVerbatim { - return b[len(`"`) : len(b)-len(`"`)] - } - b, _ = unescapeString(make([]byte, 0, len(b)), b) - return b -} - -// consumeSimpleNumber consumes the next JSON number per RFC 7159, section 6 -// but is limited to the grammar for a positive integer. -// It returns 0 if it is invalid or more complicated than a simple integer, -// in which case consumeNumber should be called. -func consumeSimpleNumber(b []byte) (n int) { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - if len(b) > 0 { - if b[0] == '0' { - n++ - } else if '1' <= b[0] && b[0] <= '9' { - n++ - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - n++ - } - } else { - return 0 - } - if len(b) == n || !(b[n] == '.' || b[n] == 'e' || b[n] == 'E') { - return n - } - } - return 0 -} - -type consumeNumberState uint - -const ( - consumeNumberInit consumeNumberState = iota - beforeIntegerDigits - withinIntegerDigits - beforeFractionalDigits - withinFractionalDigits - beforeExponentDigits - withinExponentDigits -) - -// consumeNumber consumes the next JSON number per RFC 7159, section 6. -// It reports the number of bytes consumed and whether an error was encountered. -// If the input appears truncated, it returns io.ErrUnexpectedEOF. -// -// Note that JSON numbers are not self-terminating. -// If the entire input is consumed, then the caller needs to consider whether -// there may be subsequent unread data that may still be part of this number. -func consumeNumber(b []byte) (n int, err error) { - n, _, err = consumeNumberResumable(b, 0, consumeNumberInit) - return n, err -} - -// consumeNumberResumable is identical to consumeNumber but supports resuming -// from a previous call that returned io.ErrUnexpectedEOF. -func consumeNumberResumable(b []byte, resumeOffset int, state consumeNumberState) (n int, _ consumeNumberState, err error) { - // Jump to the right state when resuming from a partial consumption. - n = resumeOffset - if state > consumeNumberInit { - switch state { - case withinIntegerDigits, withinFractionalDigits, withinExponentDigits: - // Consume leading digits. - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - n++ - } - if len(b) == n { - return n, state, nil // still within the same state - } - state++ // switches "withinX" to "beforeY" where Y is the state after X - } - switch state { - case beforeIntegerDigits: - goto beforeInteger - case beforeFractionalDigits: - goto beforeFractional - case beforeExponentDigits: - goto beforeExponent - default: - return n, state, nil - } - } - - // Consume required integer component (with optional minus sign). -beforeInteger: - resumeOffset = n - if len(b) > 0 && b[0] == '-' { - n++ - } - switch { - case len(b) == n: - return resumeOffset, beforeIntegerDigits, io.ErrUnexpectedEOF - case b[n] == '0': - n++ - state = beforeFractionalDigits - case '1' <= b[n] && b[n] <= '9': - n++ - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - n++ - } - state = withinIntegerDigits - default: - return n, state, newInvalidCharacterError(b[n:], "within number (expecting digit)") - } - - // Consume optional fractional component. -beforeFractional: - if len(b) > n && b[n] == '.' { - resumeOffset = n - n++ - switch { - case len(b) == n: - return resumeOffset, beforeFractionalDigits, io.ErrUnexpectedEOF - case '0' <= b[n] && b[n] <= '9': - n++ - default: - return n, state, newInvalidCharacterError(b[n:], "within number (expecting digit)") - } - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - n++ - } - state = withinFractionalDigits - } - - // Consume optional exponent component. -beforeExponent: - if len(b) > n && (b[n] == 'e' || b[n] == 'E') { - resumeOffset = n - n++ - if len(b) > n && (b[n] == '-' || b[n] == '+') { - n++ - } - switch { - case len(b) == n: - return resumeOffset, beforeExponentDigits, io.ErrUnexpectedEOF - case '0' <= b[n] && b[n] <= '9': - n++ - default: - return n, state, newInvalidCharacterError(b[n:], "within number (expecting digit)") - } - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - n++ - } - state = withinExponentDigits - } - - return n, state, nil -} - -// parseHexUint16 is similar to strconv.ParseUint, -// but operates directly on []byte and is optimized for base-16. -// See https://go.dev/issue/42429. -func parseHexUint16(b []byte) (v uint16, ok bool) { - if len(b) != 4 { - return 0, false - } - for _, c := range b[:4] { - switch { - case '0' <= c && c <= '9': - c = c - '0' - case 'a' <= c && c <= 'f': - c = 10 + c - 'a' - case 'A' <= c && c <= 'F': - c = 10 + c - 'A' - default: - return 0, false - } - v = v*16 + uint16(c) - } - return v, true -} - -// parseDecUint is similar to strconv.ParseUint, -// but operates directly on []byte and is optimized for base-10. -// If the number is syntactically valid but overflows uint64, -// then it returns (math.MaxUint64, false). -// See https://go.dev/issue/42429. -func parseDecUint(b []byte) (v uint64, ok bool) { - // Overflow logic is based on strconv/atoi.go:138-149 from Go1.15, where: - // - cutoff is equal to math.MaxUint64/10+1, and - // - the n1 > maxVal check is unnecessary - // since maxVal is equivalent to math.MaxUint64. - var n int - var overflow bool - for len(b) > n && ('0' <= b[n] && b[n] <= '9') { - overflow = overflow || v >= math.MaxUint64/10+1 - v *= 10 - - v1 := v + uint64(b[n]-'0') - overflow = overflow || v1 < v - v = v1 - - n++ - } - if n == 0 || len(b) != n { - return 0, false - } - if overflow { - return math.MaxUint64, false - } - return v, true -} - -// parseFloat parses a floating point number according to the Go float grammar. -// Note that the JSON number grammar is a strict subset. -// -// If the number overflows the finite representation of a float, -// then we return MaxFloat since any finite value will always be infinitely -// more accurate at representing another finite value than an infinite value. -func parseFloat(b []byte, bits int) (v float64, ok bool) { - // Fast path for exact integer numbers which fit in the - // 24-bit or 53-bit significand of a float32 or float64. - var negLen int // either 0 or 1 - if len(b) > 0 && b[0] == '-' { - negLen = 1 - } - u, ok := parseDecUint(b[negLen:]) - if ok && ((bits == 32 && u <= 1<<24) || (bits == 64 && u <= 1<<53)) { - return math.Copysign(float64(u), float64(-1*negLen)), true - } - - // Note that the []byte->string conversion unfortunately allocates. - // See https://go.dev/issue/42429 for more information. - fv, err := strconv.ParseFloat(string(b), bits) - if math.IsInf(fv, 0) { - switch { - case bits == 32 && math.IsInf(fv, +1): - return +math.MaxFloat32, true - case bits == 64 && math.IsInf(fv, +1): - return +math.MaxFloat64, true - case bits == 32 && math.IsInf(fv, -1): - return -math.MaxFloat32, true - case bits == 64 && math.IsInf(fv, -1): - return -math.MaxFloat64, true - } - } - return fv, err == nil -} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go index e4eefa3de..ff70951ab 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go @@ -2,61 +2,41 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package json implements serialization of JSON -// as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. +// Package json implements semantic processing of JSON as specified in RFC 8259. // JSON is a simple data interchange format that can represent // primitive data types such as booleans, strings, and numbers, // in addition to structured data types such as objects and arrays. // -// # Terminology -// -// This package uses the terms "encode" and "decode" for syntactic functionality -// that is concerned with processing JSON based on its grammar, and -// uses the terms "marshal" and "unmarshal" for semantic functionality -// that determines the meaning of JSON values as Go values and vice-versa. -// It aims to provide a clear distinction between functionality that -// is purely concerned with encoding versus that of marshaling. -// For example, one can directly encode a stream of JSON tokens without -// needing to marshal a concrete Go value representing them. -// Similarly, one can decode a stream of JSON tokens without -// needing to unmarshal them into a concrete Go value. -// -// This package uses JSON terminology when discussing JSON, which may differ -// from related concepts in Go or elsewhere in computing literature. -// -// - A JSON "object" refers to an unordered collection of name/value members. -// - A JSON "array" refers to an ordered sequence of elements. -// - A JSON "value" refers to either a literal (i.e., null, false, or true), -// string, number, object, or array. -// -// See RFC 8259 for more information. -// -// # Specifications -// -// Relevant specifications include RFC 4627, RFC 7159, RFC 7493, RFC 8259, -// and RFC 8785. Each RFC is generally a stricter subset of another RFC. -// In increasing order of strictness: -// -// - RFC 4627 and RFC 7159 do not require (but recommend) the use of UTF-8 -// and also do not require (but recommend) that object names be unique. -// - RFC 8259 requires the use of UTF-8, -// but does not require (but recommends) that object names be unique. -// - RFC 7493 requires the use of UTF-8 -// and also requires that object names be unique. -// - RFC 8785 defines a canonical representation. It requires the use of UTF-8 -// and also requires that object names be unique and in a specific ordering. -// It specifies exactly how strings and numbers must be formatted. -// -// The primary difference between RFC 4627 and RFC 7159 is that the former -// restricted top-level values to only JSON objects and arrays, while -// RFC 7159 and subsequent RFCs permit top-level values to additionally be -// JSON nulls, booleans, strings, or numbers. -// -// By default, this package operates on RFC 7493, but can be configured -// to operate according to the other RFC specifications. -// RFC 7493 is a stricter subset of RFC 8259 and fully compliant with it. -// In particular, it makes specific choices about behavior that RFC 8259 -// leaves as undefined in order to ensure greater interoperability. +// [Marshal] and [Unmarshal] encode and decode Go values +// to/from JSON text contained within a []byte. +// [MarshalWrite] and [UnmarshalRead] operate on JSON text +// by writing to or reading from an [io.Writer] or [io.Reader]. +// [MarshalEncode] and [UnmarshalDecode] operate on JSON text +// by encoding to or decoding from a [jsontext.Encoder] or [jsontext.Decoder]. +// [Options] may be passed to each of the marshal or unmarshal functions +// to configure the semantic behavior of marshaling and unmarshaling +// (i.e., alter how JSON data is understood as Go data and vice versa). +// [jsontext.Options] may also be passed to the marshal or unmarshal functions +// to configure the syntactic behavior of encoding or decoding. +// +// The data types of JSON are mapped to/from the data types of Go based on +// the closest logical equivalent between the two type systems. For example, +// a JSON boolean corresponds with a Go bool, +// a JSON string corresponds with a Go string, +// a JSON number corresponds with a Go int, uint or float, +// a JSON array corresponds with a Go slice or array, and +// a JSON object corresponds with a Go struct or map. +// See the documentation on [Marshal] and [Unmarshal] for a comprehensive list +// of how the JSON and Go type systems correspond. +// +// Arbitrary Go types can customize their JSON representation by implementing +// [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom]. +// This provides authors of Go types with control over how their types are +// serialized as JSON. Alternatively, users can implement functions that match +// [MarshalFunc], [MarshalToFunc], [UnmarshalFunc], or [UnmarshalFromFunc] +// to specify the JSON representation for arbitrary types. +// This provides callers of JSON functionality with control over +// how any arbitrary type is serialized as JSON. // // # JSON Representation of Go structs // @@ -68,12 +48,14 @@ // into the corresponding Go struct fields. // Object members that do not match any struct fields, // also known as “unknown members”, are ignored by default or rejected -// if UnmarshalOptions.RejectUnknownMembers is specified. +// if [RejectUnknownMembers] is specified. // // The representation of each struct field can be customized in the // "json" struct field tag, where the tag is a comma separated list of options. // As a special case, if the entire tag is `json:"-"`, // then the field is ignored with regard to its JSON representation. +// Some options also have equivalent behavior controlled by a caller-specified [Options]. +// Field-specified options take precedence over caller-specified options. // // The first option is the JSON object name override for the Go struct field. // If the name is not specified, then the Go struct field name @@ -98,21 +80,23 @@ // encoded as a JSON null, empty string, empty object, or empty array. // This option has no effect when unmarshaling. // -// - string: The "string" option specifies that -// MarshalOptions.StringifyNumbers and UnmarshalOptions.StringifyNumbers +// - string: The "string" option specifies that [StringifyNumbers] // be set when marshaling or unmarshaling a struct field value. // This causes numeric types to be encoded as a JSON number -// within a JSON string, and to be decoded from either a JSON number or -// a JSON string containing a JSON number. +// within a JSON string, and to be decoded from a JSON string +// containing the JSON number without any surrounding whitespace. // This extra level of encoding is often necessary since // many JSON parsers cannot precisely represent 64-bit integers. // -// - nocase: When unmarshaling, the "nocase" option specifies that -// if the JSON object name does not exactly match the JSON name -// for any of the struct fields, then it attempts to match the struct field -// using a case-insensitive match that also ignores dashes and underscores. -// If multiple fields match, the first declared field in breadth-first order -// takes precedence. This option has no effect when marshaling. +// - case: When unmarshaling, the "case" option specifies how +// JSON object names are matched with the JSON name for Go struct fields. +// The option is a key-value pair specified as "case:value" where +// the value must either be 'ignore' or 'strict'. +// The 'ignore' value specifies that matching is case-insensitive +// where dashes and underscores are also ignored. If multiple fields match, +// the first declared field in breadth-first order takes precedence. +// The 'strict' value specifies that matching is case-sensitive. +// This takes precedence over the [MatchCaseInsensitiveNames] option. // // - inline: The "inline" option specifies that // the JSON representable content of this field type is to be promoted @@ -120,10 +104,10 @@ // It is the JSON equivalent of Go struct embedding. // A Go embedded field is implicitly inlined unless an explicit JSON name // is specified. The inlined field must be a Go struct -// (that does not implement any JSON methods), RawValue, map[string]T, -// or an unnamed pointer to such types. When marshaling, +// (that does not implement any JSON methods), [jsontext.Value], +// map[~string]T, or an unnamed pointer to such types. When marshaling, // inlined fields from a pointer type are omitted if it is nil. -// Inlined fields of type RawValue and map[string]T are called +// Inlined fields of type [jsontext.Value] and map[~string]T are called // “inlined fallbacks” as they can represent all possible // JSON object members not directly handled by the parent struct. // Only one inlined fallback field may be specified in a struct, @@ -132,11 +116,11 @@ // // - unknown: The "unknown" option is a specialized variant // of the inlined fallback to indicate that this Go struct field -// contains any number of unknown JSON object members. The field type -// must be a RawValue, map[string]T, or an unnamed pointer to such types. -// If MarshalOptions.DiscardUnknownMembers is specified when marshaling, +// contains any number of unknown JSON object members. The field type must +// be a [jsontext.Value], map[~string]T, or an unnamed pointer to such types. +// If [DiscardUnknownMembers] is specified when marshaling, // the contents of this field are ignored. -// If UnmarshalOptions.RejectUnknownMembers is specified when unmarshaling, +// If [RejectUnknownMembers] is specified when unmarshaling, // any unknown object members are rejected regardless of whether // an inlined fallback with the "unknown" option exists. This option // must not be specified with any other option (including the JSON name). @@ -156,7 +140,7 @@ // For example, only a nil slice or map is omitted under "omitzero", while // an empty slice or map is omitted under "omitempty" regardless of nilness. // The "omitzero" option is useful for types with a well-defined zero value -// (e.g., netip.Addr) or have an IsZero method (e.g., time.Time). +// (e.g., [net/netip.Addr]) or have an IsZero method (e.g., [time.Time.IsZero]). // // Every Go struct corresponds to a list of JSON representable fields // which is constructed by performing a breadth-first search over @@ -167,12 +151,108 @@ // at shallowest depth takes precedence and the other fields at deeper depths // are excluded from the list of JSON representable fields. // If multiple fields at the shallowest depth have the same JSON name, -// then all of those fields are excluded from the list. This is analogous to -// Go visibility rules for struct field selection with embedded struct types. +// but exactly one is explicitly tagged with a JSON name, +// then that field takes precedence and all others are excluded from the list. +// This is analogous to Go visibility rules for struct field selection +// with embedded struct types. // // Marshaling or unmarshaling a non-empty struct -// without any JSON representable fields results in a SemanticError. +// without any JSON representable fields results in a [SemanticError]. // Unexported fields must not have any `json` tags except for `json:"-"`. +// +// # Security Considerations +// +// JSON is frequently used as a data interchange format to communicate +// between different systems, possibly implemented in different languages. +// For interoperability and security reasons, it is important that +// all implementations agree upon the semantic meaning of the data. +// +// [For example, suppose we have two micro-services.] +// The first service is responsible for authenticating a JSON request, +// while the second service is responsible for executing the request +// (having assumed that the prior service authenticated the request). +// If an attacker were able to maliciously craft a JSON request such that +// both services believe that the same request is from different users, +// it could bypass the authenticator with valid credentials for one user, +// but maliciously perform an action on behalf of a different user. +// +// According to RFC 8259, there unfortunately exist many JSON texts +// that are syntactically valid but semantically ambiguous. +// For example, the standard does not define how to interpret duplicate +// names within an object. +// +// The v1 [encoding/json] and [encoding/json/v2] packages +// interpret some inputs in different ways. In particular: +// +// - The standard specifies that JSON must be encoded using UTF-8. +// By default, v1 replaces invalid bytes of UTF-8 in JSON strings +// with the Unicode replacement character, +// while v2 rejects inputs with invalid UTF-8. +// To change the default, specify the [jsontext.AllowInvalidUTF8] option. +// The replacement of invalid UTF-8 is a form of data corruption +// that alters the precise meaning of strings. +// +// - The standard does not specify a particular behavior when +// duplicate names are encountered within a JSON object, +// which means that different implementations may behave differently. +// By default, v1 allows for the presence of duplicate names, +// while v2 rejects duplicate names. +// To change the default, specify the [jsontext.AllowDuplicateNames] option. +// If allowed, object members are processed in the order they are observed, +// meaning that later values will replace or be merged into prior values, +// depending on the Go value type. +// +// - The standard defines a JSON object as an unordered collection of name/value pairs. +// While ordering can be observed through the underlying [jsontext] API, +// both v1 and v2 generally avoid exposing the ordering. +// No application should semantically depend on the order of object members. +// Allowing duplicate names is a vector through which ordering of members +// can accidentally be observed and depended upon. +// +// - The standard suggests that JSON object names are typically compared +// based on equality of the sequence of Unicode code points, +// which implies that comparing names is often case-sensitive. +// When unmarshaling a JSON object into a Go struct, +// by default, v1 uses a (loose) case-insensitive match on the name, +// while v2 uses a (strict) case-sensitive match on the name. +// To change the default, specify the [MatchCaseInsensitiveNames] option. +// The use of case-insensitive matching provides another vector through +// which duplicate names can occur. Allowing case-insensitive matching +// means that v1 or v2 might interpret JSON objects differently from most +// other JSON implementations (which typically use a case-sensitive match). +// +// - The standard does not specify a particular behavior when +// an unknown name in a JSON object is encountered. +// When unmarshaling a JSON object into a Go struct, by default +// both v1 and v2 ignore unknown names and their corresponding values. +// To change the default, specify the [RejectUnknownMembers] option. +// +// - The standard suggests that implementations may use a float64 +// to represent a JSON number. Consequently, large JSON integers +// may lose precision when stored as a floating-point type. +// Both v1 and v2 correctly preserve precision when marshaling and +// unmarshaling a concrete integer type. However, even if v1 and v2 +// preserve precision for concrete types, other JSON implementations +// may not be able to preserve precision for outputs produced by v1 or v2. +// The `string` tag option can be used to specify that an integer type +// is to be quoted within a JSON string to avoid loss of precision. +// Furthermore, v1 and v2 may still lose precision when unmarshaling +// into an any interface value, where unmarshal uses a float64 +// by default to represent a JSON number. +// To change the default, specify the [WithUnmarshalers] option +// with a custom unmarshaler that pre-populates the interface value +// with a concrete Go type that can preserve precision. +// +// RFC 8785 specifies a canonical form for any JSON text, +// which explicitly defines specific behaviors that RFC 8259 leaves undefined. +// In theory, if a text can successfully [jsontext.Value.Canonicalize] +// without changing the semantic meaning of the data, then it provides a +// greater degree of confidence that the data is more secure and interoperable. +// +// The v2 API generally chooses more secure defaults than v1, +// but care should still be taken with large integers or unknown members. +// +// [For example, suppose we have two micro-services.]: https://www.youtube.com/watch?v=avilmOcHKHE&t=1057s package json // requireKeyedLiterals can be embedded in a struct to require keyed literals. diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go deleted file mode 100644 index 5b81ca15a..000000000 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go +++ /dev/null @@ -1,1170 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package json - -import ( - "bytes" - "io" - "math" - "math/bits" - "strconv" - "unicode/utf16" - "unicode/utf8" -) - -// EncodeOptions configures how JSON encoding operates. -// The zero value is equivalent to the default settings, -// which is compliant with both RFC 7493 and RFC 8259. -type EncodeOptions struct { - requireKeyedLiterals - nonComparable - - // multiline specifies whether the encoder should emit multiline output. - multiline bool - - // omitTopLevelNewline specifies whether to omit the newline - // that is appended after every top-level JSON value when streaming. - omitTopLevelNewline bool - - // AllowDuplicateNames specifies that JSON objects may contain - // duplicate member names. Disabling the duplicate name check may provide - // performance benefits, but breaks compliance with RFC 7493, section 2.3. - // The output will still be compliant with RFC 8259, - // which leaves the handling of duplicate names as unspecified behavior. - AllowDuplicateNames bool - - // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, - // which will be mangled as the Unicode replacement character, U+FFFD. - // This causes the encoder to break compliance with - // RFC 7493, section 2.1, and RFC 8259, section 8.1. - AllowInvalidUTF8 bool - - // preserveRawStrings specifies that WriteToken and WriteValue should not - // reformat any JSON string, but keep the formatting verbatim. - preserveRawStrings bool - - // canonicalizeNumbers specifies that WriteToken and WriteValue should - // reformat any JSON numbers according to RFC 8785, section 3.2.2.3. - canonicalizeNumbers bool - - // EscapeRune reports whether the provided character should be escaped - // as a hexadecimal Unicode codepoint (e.g., \ufffd). - // If nil, the shortest and simplest encoding will be used, - // which is also the formatting specified by RFC 8785, section 3.2.2.2. - EscapeRune func(rune) bool - - // Indent (if non-empty) specifies that the encoder should emit multiline - // output where each element in a JSON object or array begins on a new, - // indented line beginning with the indent prefix followed by one or more - // copies of indent according to the indentation nesting. - // It may only be composed of space or tab characters. - Indent string - - // IndentPrefix is prepended to each line within a JSON object or array. - // The purpose of the indent prefix is to encode data that can more easily - // be embedded inside other formatted JSON data. - // It may only be composed of space or tab characters. - // It is ignored if Indent is empty. - IndentPrefix string -} - -// Encoder is a streaming encoder from raw JSON tokens and values. -// It is used to write a stream of top-level JSON values, -// each terminated with a newline character. -// -// WriteToken and WriteValue calls may be interleaved. -// For example, the following JSON value: -// -// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} -// -// can be composed with the following calls (ignoring errors for brevity): -// -// e.WriteToken(ObjectStart) // { -// e.WriteToken(String("name")) // "name" -// e.WriteToken(String("value")) // "value" -// e.WriteValue(RawValue(`"array"`)) // "array" -// e.WriteToken(ArrayStart) // [ -// e.WriteToken(Null) // null -// e.WriteToken(False) // false -// e.WriteValue(RawValue("true")) // true -// e.WriteToken(Float(3.14159)) // 3.14159 -// e.WriteToken(ArrayEnd) // ] -// e.WriteValue(RawValue(`"object"`)) // "object" -// e.WriteValue(RawValue(`{"k":"v"}`)) // {"k":"v"} -// e.WriteToken(ObjectEnd) // } -// -// The above is one of many possible sequence of calls and -// may not represent the most sensible method to call for any given token/value. -// For example, it is probably more common to call WriteToken with a string -// for object names. -type Encoder struct { - state - encodeBuffer - options EncodeOptions - - seenPointers seenPointers // only used when marshaling -} - -// encodeBuffer is a buffer split into 2 segments: -// -// - buf[0:len(buf)] // written (but unflushed) portion of the buffer -// - buf[len(buf):cap(buf)] // unused portion of the buffer -type encodeBuffer struct { - buf []byte // may alias wr if it is a bytes.Buffer - - // baseOffset is added to len(buf) to obtain the absolute offset - // relative to the start of io.Writer stream. - baseOffset int64 - - wr io.Writer - - // maxValue is the approximate maximum RawValue size passed to WriteValue. - maxValue int - // unusedCache is the buffer returned by the UnusedBuffer method. - unusedCache []byte - // bufStats is statistics about buffer utilization. - // It is only used with pooled encoders in pools.go. - bufStats bufferStatistics -} - -// NewEncoder constructs a new streaming encoder writing to w. -func NewEncoder(w io.Writer) *Encoder { - return EncodeOptions{}.NewEncoder(w) -} - -// NewEncoder constructs a new streaming encoder writing to w -// configured with the provided options. -// It flushes the internal buffer when the buffer is sufficiently full or -// when a top-level value has been written. -// -// If w is a bytes.Buffer, then the encoder appends directly into the buffer -// without copying the contents from an intermediate buffer. -func (o EncodeOptions) NewEncoder(w io.Writer) *Encoder { - e := new(Encoder) - o.ResetEncoder(e, w) - return e -} - -// ResetEncoder resets an encoder such that it is writing afresh to w and -// configured with the provided options. -func (o EncodeOptions) ResetEncoder(e *Encoder, w io.Writer) { - if e == nil { - panic("json: invalid nil Encoder") - } - if w == nil { - panic("json: invalid nil io.Writer") - } - e.reset(nil, w, o) -} - -func (e *Encoder) reset(b []byte, w io.Writer, o EncodeOptions) { - if len(o.Indent) > 0 { - o.multiline = true - if s := trimLeftSpaceTab(o.IndentPrefix); len(s) > 0 { - panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") - } - if s := trimLeftSpaceTab(o.Indent); len(s) > 0 { - panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") - } - } - e.state.reset() - e.encodeBuffer = encodeBuffer{buf: b, wr: w, bufStats: e.bufStats} - e.options = o - if bb, ok := w.(*bytes.Buffer); ok && bb != nil { - e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb - } -} - -// Reset resets an encoder such that it is writing afresh to w but -// keeps any pre-existing encoder options. -func (e *Encoder) Reset(w io.Writer) { - e.options.ResetEncoder(e, w) -} - -// needFlush determines whether to flush at this point. -func (e *Encoder) needFlush() bool { - // NOTE: This function is carefully written to be inlineable. - - // Avoid flushing if e.wr is nil since there is no underlying writer. - // Flush if less than 25% of the capacity remains. - // Flushing at some constant fraction ensures that the buffer stops growing - // so long as the largest Token or Value fits within that unused capacity. - return e.wr != nil && (e.tokens.depth() == 1 || len(e.buf) > 3*cap(e.buf)/4) -} - -// flush flushes the buffer to the underlying io.Writer. -// It may append a trailing newline after the top-level value. -func (e *Encoder) flush() error { - if e.wr == nil || e.avoidFlush() { - return nil - } - - // In streaming mode, always emit a newline after the top-level value. - if e.tokens.depth() == 1 && !e.options.omitTopLevelNewline { - e.buf = append(e.buf, '\n') - } - - // Inform objectNameStack that we are about to flush the buffer content. - e.names.copyQuotedBuffer(e.buf) - - // Specialize bytes.Buffer for better performance. - if bb, ok := e.wr.(*bytes.Buffer); ok { - // If e.buf already aliases the internal buffer of bb, - // then the Write call simply increments the internal offset, - // otherwise Write operates as expected. - // See https://go.dev/issue/42986. - n, _ := bb.Write(e.buf) // never fails unless bb is nil - e.baseOffset += int64(n) - - // If the internal buffer of bytes.Buffer is too small, - // append operations elsewhere in the Encoder may grow the buffer. - // This would be semantically correct, but hurts performance. - // As such, ensure 25% of the current length is always available - // to reduce the probability that other appends must allocate. - if avail := bb.Cap() - bb.Len(); avail < bb.Len()/4 { - bb.Grow(avail + 1) - } - - e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb - return nil - } - - // Flush the internal buffer to the underlying io.Writer. - n, err := e.wr.Write(e.buf) - e.baseOffset += int64(n) - if err != nil { - // In the event of an error, preserve the unflushed portion. - // Thus, write errors aren't fatal so long as the io.Writer - // maintains consistent state after errors. - if n > 0 { - e.buf = e.buf[:copy(e.buf, e.buf[n:])] - } - return &ioError{action: "write", err: err} - } - e.buf = e.buf[:0] - - // Check whether to grow the buffer. - // Note that cap(e.buf) may already exceed maxBufferSize since - // an append elsewhere already grew it to store a large token. - const maxBufferSize = 4 << 10 - const growthSizeFactor = 2 // higher value is faster - const growthRateFactor = 2 // higher value is slower - // By default, grow if below the maximum buffer size. - grow := cap(e.buf) <= maxBufferSize/growthSizeFactor - // Growing can be expensive, so only grow - // if a sufficient number of bytes have been processed. - grow = grow && int64(cap(e.buf)) < e.previousOffsetEnd()/growthRateFactor - if grow { - e.buf = make([]byte, 0, cap(e.buf)*growthSizeFactor) - } - - return nil -} - -func (e *encodeBuffer) previousOffsetEnd() int64 { return e.baseOffset + int64(len(e.buf)) } -func (e *encodeBuffer) unflushedBuffer() []byte { return e.buf } - -// avoidFlush indicates whether to avoid flushing to ensure there is always -// enough in the buffer to unwrite the last object member if it were empty. -func (e *Encoder) avoidFlush() bool { - switch { - case e.tokens.last.length() == 0: - // Never flush after ObjectStart or ArrayStart since we don't know yet - // if the object or array will end up being empty. - return true - case e.tokens.last.needObjectValue(): - // Never flush before the object value since we don't know yet - // if the object value will end up being empty. - return true - case e.tokens.last.needObjectName() && len(e.buf) >= 2: - // Never flush after the object value if it does turn out to be empty. - switch string(e.buf[len(e.buf)-2:]) { - case `ll`, `""`, `{}`, `[]`: // last two bytes of every empty value - return true - } - } - return false -} - -// unwriteEmptyObjectMember unwrites the last object member if it is empty -// and reports whether it performed an unwrite operation. -func (e *Encoder) unwriteEmptyObjectMember(prevName *string) bool { - if last := e.tokens.last; !last.isObject() || !last.needObjectName() || last.length() == 0 { - panic("BUG: must be called on an object after writing a value") - } - - // The flushing logic is modified to never flush a trailing empty value. - // The encoder never writes trailing whitespace eagerly. - b := e.unflushedBuffer() - - // Detect whether the last value was empty. - var n int - if len(b) >= 3 { - switch string(b[len(b)-2:]) { - case "ll": // last two bytes of `null` - n = len(`null`) - case `""`: - // It is possible for a non-empty string to have `""` as a suffix - // if the second to the last quote was escaped. - if b[len(b)-3] == '\\' { - return false // e.g., `"\""` is not empty - } - n = len(`""`) - case `{}`: - n = len(`{}`) - case `[]`: - n = len(`[]`) - } - } - if n == 0 { - return false - } - - // Unwrite the value, whitespace, colon, name, whitespace, and comma. - b = b[:len(b)-n] - b = trimSuffixWhitespace(b) - b = trimSuffixByte(b, ':') - b = trimSuffixString(b) - b = trimSuffixWhitespace(b) - b = trimSuffixByte(b, ',') - e.buf = b // store back truncated unflushed buffer - - // Undo state changes. - e.tokens.last.decrement() // for object member value - e.tokens.last.decrement() // for object member name - if !e.options.AllowDuplicateNames { - if e.tokens.last.isActiveNamespace() { - e.namespaces.last().removeLast() - } - e.names.clearLast() - if prevName != nil { - e.names.copyQuotedBuffer(e.buf) // required by objectNameStack.replaceLastUnquotedName - e.names.replaceLastUnquotedName(*prevName) - } - } - return true -} - -// unwriteOnlyObjectMemberName unwrites the only object member name -// and returns the unquoted name. -func (e *Encoder) unwriteOnlyObjectMemberName() string { - if last := e.tokens.last; !last.isObject() || last.length() != 1 { - panic("BUG: must be called on an object after writing first name") - } - - // Unwrite the name and whitespace. - b := trimSuffixString(e.buf) - isVerbatim := bytes.IndexByte(e.buf[len(b):], '\\') < 0 - name := string(unescapeStringMayCopy(e.buf[len(b):], isVerbatim)) - e.buf = trimSuffixWhitespace(b) - - // Undo state changes. - e.tokens.last.decrement() - if !e.options.AllowDuplicateNames { - if e.tokens.last.isActiveNamespace() { - e.namespaces.last().removeLast() - } - e.names.clearLast() - } - return name -} - -func trimSuffixWhitespace(b []byte) []byte { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - n := len(b) - 1 - for n >= 0 && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { - n-- - } - return b[:n+1] -} - -func trimSuffixString(b []byte) []byte { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - if len(b) > 0 && b[len(b)-1] == '"' { - b = b[:len(b)-1] - } - for len(b) >= 2 && !(b[len(b)-1] == '"' && b[len(b)-2] != '\\') { - b = b[:len(b)-1] // trim all characters except an unescaped quote - } - if len(b) > 0 && b[len(b)-1] == '"' { - b = b[:len(b)-1] - } - return b -} - -func hasSuffixByte(b []byte, c byte) bool { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - return len(b) > 0 && b[len(b)-1] == c -} - -func trimSuffixByte(b []byte, c byte) []byte { - // NOTE: The arguments and logic are kept simple to keep this inlineable. - if len(b) > 0 && b[len(b)-1] == c { - return b[:len(b)-1] - } - return b -} - -// WriteToken writes the next token and advances the internal write offset. -// -// The provided token kind must be consistent with the JSON grammar. -// For example, it is an error to provide a number when the encoder -// is expecting an object name (which is always a string), or -// to provide an end object delimiter when the encoder is finishing an array. -// If the provided token is invalid, then it reports a SyntacticError and -// the internal state remains unchanged. -func (e *Encoder) WriteToken(t Token) error { - k := t.Kind() - b := e.buf // use local variable to avoid mutating e in case of error - - // Append any delimiters or optional whitespace. - b = e.tokens.mayAppendDelim(b, k) - if e.options.multiline { - b = e.appendWhitespace(b, k) - } - - // Append the token to the output and to the state machine. - var err error - switch k { - case 'n': - b = append(b, "null"...) - err = e.tokens.appendLiteral() - case 'f': - b = append(b, "false"...) - err = e.tokens.appendLiteral() - case 't': - b = append(b, "true"...) - err = e.tokens.appendLiteral() - case '"': - n0 := len(b) // offset before calling t.appendString - if b, err = t.appendString(b, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune); err != nil { - break - } - if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { - if !e.tokens.last.isValidNamespace() { - err = errInvalidNamespace - break - } - if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { - err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} - break - } - e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds - } - err = e.tokens.appendString() - case '0': - if b, err = t.appendNumber(b, e.options.canonicalizeNumbers); err != nil { - break - } - err = e.tokens.appendNumber() - case '{': - b = append(b, '{') - if err = e.tokens.pushObject(); err != nil { - break - } - if !e.options.AllowDuplicateNames { - e.names.push() - e.namespaces.push() - } - case '}': - b = append(b, '}') - if err = e.tokens.popObject(); err != nil { - break - } - if !e.options.AllowDuplicateNames { - e.names.pop() - e.namespaces.pop() - } - case '[': - b = append(b, '[') - err = e.tokens.pushArray() - case ']': - b = append(b, ']') - err = e.tokens.popArray() - default: - return &SyntacticError{str: "invalid json.Token"} - } - if err != nil { - return err - } - - // Finish off the buffer and store it back into e. - e.buf = b - if e.needFlush() { - return e.flush() - } - return nil -} - -const ( - rawIntNumber = -1 - rawUintNumber = -2 -) - -// writeNumber is specialized version of WriteToken, but optimized for numbers. -// As a special-case, if bits is -1 or -2, it will treat v as -// the raw-encoded bits of an int64 or uint64, respectively. -// It is only called from arshal_default.go. -func (e *Encoder) writeNumber(v float64, bits int, quote bool) error { - b := e.buf // use local variable to avoid mutating e in case of error - - // Append any delimiters or optional whitespace. - b = e.tokens.mayAppendDelim(b, '0') - if e.options.multiline { - b = e.appendWhitespace(b, '0') - } - - if quote { - // Append the value to the output. - n0 := len(b) // offset before appending the number - b = append(b, '"') - switch bits { - case rawIntNumber: - b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) - case rawUintNumber: - b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) - default: - b = appendNumber(b, v, bits) - } - b = append(b, '"') - - // Escape the string if necessary. - if e.options.EscapeRune != nil { - b2 := append(e.unusedCache, b[n0+len(`"`):len(b)-len(`"`)]...) - b, _ = appendString(b[:n0], string(b2), false, e.options.EscapeRune) - e.unusedCache = b2[:0] - } - - // Update the state machine. - if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { - if !e.tokens.last.isValidNamespace() { - return errInvalidNamespace - } - if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { - return &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} - } - e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds - } - if err := e.tokens.appendString(); err != nil { - return err - } - } else { - switch bits { - case rawIntNumber: - b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) - case rawUintNumber: - b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) - default: - b = appendNumber(b, v, bits) - } - if err := e.tokens.appendNumber(); err != nil { - return err - } - } - - // Finish off the buffer and store it back into e. - e.buf = b - if e.needFlush() { - return e.flush() - } - return nil -} - -// WriteValue writes the next raw value and advances the internal write offset. -// The Encoder does not simply copy the provided value verbatim, but -// parses it to ensure that it is syntactically valid and reformats it -// according to how the Encoder is configured to format whitespace and strings. -// -// The provided value kind must be consistent with the JSON grammar -// (see examples on Encoder.WriteToken). If the provided value is invalid, -// then it reports a SyntacticError and the internal state remains unchanged. -func (e *Encoder) WriteValue(v RawValue) error { - e.maxValue |= len(v) // bitwise OR is a fast approximation of max - - k := v.Kind() - b := e.buf // use local variable to avoid mutating e in case of error - - // Append any delimiters or optional whitespace. - b = e.tokens.mayAppendDelim(b, k) - if e.options.multiline { - b = e.appendWhitespace(b, k) - } - - // Append the value the output. - var err error - v = v[consumeWhitespace(v):] - n0 := len(b) // offset before calling e.reformatValue - b, v, err = e.reformatValue(b, v, e.tokens.depth()) - if err != nil { - return err - } - v = v[consumeWhitespace(v):] - if len(v) > 0 { - return newInvalidCharacterError(v[0:], "after top-level value") - } - - // Append the kind to the state machine. - switch k { - case 'n', 'f', 't': - err = e.tokens.appendLiteral() - case '"': - if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { - if !e.tokens.last.isValidNamespace() { - err = errInvalidNamespace - break - } - if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { - err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} - break - } - e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds - } - err = e.tokens.appendString() - case '0': - err = e.tokens.appendNumber() - case '{': - if err = e.tokens.pushObject(); err != nil { - break - } - if err = e.tokens.popObject(); err != nil { - panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) - } - case '[': - if err = e.tokens.pushArray(); err != nil { - break - } - if err = e.tokens.popArray(); err != nil { - panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) - } - } - if err != nil { - return err - } - - // Finish off the buffer and store it back into e. - e.buf = b - if e.needFlush() { - return e.flush() - } - return nil -} - -// appendWhitespace appends whitespace that immediately precedes the next token. -func (e *Encoder) appendWhitespace(b []byte, next Kind) []byte { - if e.tokens.needDelim(next) == ':' { - return append(b, ' ') - } else { - return e.appendIndent(b, e.tokens.needIndent(next)) - } -} - -// appendIndent appends the appropriate number of indentation characters -// for the current nested level, n. -func (e *Encoder) appendIndent(b []byte, n int) []byte { - if n == 0 { - return b - } - b = append(b, '\n') - b = append(b, e.options.IndentPrefix...) - for ; n > 1; n-- { - b = append(b, e.options.Indent...) - } - return b -} - -// reformatValue parses a JSON value from the start of src and -// appends it to the end of dst, reformatting whitespace and strings as needed. -// It returns the updated versions of dst and src. -func (e *Encoder) reformatValue(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { - // TODO: Should this update valueFlags as input? - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - var n int - var err error - switch k := Kind(src[0]).normalize(); k { - case 'n': - if n = consumeNull(src); n == 0 { - n, err = consumeLiteral(src, "null") - } - case 'f': - if n = consumeFalse(src); n == 0 { - n, err = consumeLiteral(src, "false") - } - case 't': - if n = consumeTrue(src); n == 0 { - n, err = consumeLiteral(src, "true") - } - case '"': - if n := consumeSimpleString(src); n > 0 && e.options.EscapeRune == nil { - dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim - return dst, src, nil - } - return reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) - case '0': - if n := consumeSimpleNumber(src); n > 0 && !e.options.canonicalizeNumbers { - dst, src = append(dst, src[:n]...), src[n:] // copy simple numbers verbatim - return dst, src, nil - } - return reformatNumber(dst, src, e.options.canonicalizeNumbers) - case '{': - return e.reformatObject(dst, src, depth) - case '[': - return e.reformatArray(dst, src, depth) - default: - return dst, src, newInvalidCharacterError(src, "at start of value") - } - if err != nil { - return dst, src, err - } - dst, src = append(dst, src[:n]...), src[n:] - return dst, src, nil -} - -// reformatObject parses a JSON object from the start of src and -// appends it to the end of src, reformatting whitespace and strings as needed. -// It returns the updated versions of dst and src. -func (e *Encoder) reformatObject(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { - // Append object start. - if src[0] != '{' { - panic("BUG: reformatObject must be called with a buffer that starts with '{'") - } - dst, src = append(dst, '{'), src[1:] - - // Append (possible) object end. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - if src[0] == '}' { - dst, src = append(dst, '}'), src[1:] - return dst, src, nil - } - - var err error - var names *objectNamespace - if !e.options.AllowDuplicateNames { - e.namespaces.push() - defer e.namespaces.pop() - names = e.namespaces.last() - } - depth++ - for { - // Append optional newline and indentation. - if e.options.multiline { - dst = e.appendIndent(dst, depth) - } - - // Append object name. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - n0 := len(dst) // offset before calling reformatString - n := consumeSimpleString(src) - if n > 0 && e.options.EscapeRune == nil { - dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim - } else { - dst, src, err = reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) - } - if err != nil { - return dst, src, err - } - if !e.options.AllowDuplicateNames && !names.insertQuoted(dst[n0:], false) { - return dst, src, &SyntacticError{str: "duplicate name " + string(dst[n0:]) + " in object"} - } - - // Append colon. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - if src[0] != ':' { - return dst, src, newInvalidCharacterError(src, "after object name (expecting ':')") - } - dst, src = append(dst, ':'), src[1:] - if e.options.multiline { - dst = append(dst, ' ') - } - - // Append object value. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - dst, src, err = e.reformatValue(dst, src, depth) - if err != nil { - return dst, src, err - } - - // Append comma or object end. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - switch src[0] { - case ',': - dst, src = append(dst, ','), src[1:] - continue - case '}': - if e.options.multiline { - dst = e.appendIndent(dst, depth-1) - } - dst, src = append(dst, '}'), src[1:] - return dst, src, nil - default: - return dst, src, newInvalidCharacterError(src, "after object value (expecting ',' or '}')") - } - } -} - -// reformatArray parses a JSON array from the start of src and -// appends it to the end of dst, reformatting whitespace and strings as needed. -// It returns the updated versions of dst and src. -func (e *Encoder) reformatArray(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { - // Append array start. - if src[0] != '[' { - panic("BUG: reformatArray must be called with a buffer that starts with '['") - } - dst, src = append(dst, '['), src[1:] - - // Append (possible) array end. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - if src[0] == ']' { - dst, src = append(dst, ']'), src[1:] - return dst, src, nil - } - - var err error - depth++ - for { - // Append optional newline and indentation. - if e.options.multiline { - dst = e.appendIndent(dst, depth) - } - - // Append array value. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - dst, src, err = e.reformatValue(dst, src, depth) - if err != nil { - return dst, src, err - } - - // Append comma or array end. - src = src[consumeWhitespace(src):] - if len(src) == 0 { - return dst, src, io.ErrUnexpectedEOF - } - switch src[0] { - case ',': - dst, src = append(dst, ','), src[1:] - continue - case ']': - if e.options.multiline { - dst = e.appendIndent(dst, depth-1) - } - dst, src = append(dst, ']'), src[1:] - return dst, src, nil - default: - return dst, src, newInvalidCharacterError(src, "after array value (expecting ',' or ']')") - } - } -} - -// OutputOffset returns the current output byte offset. It gives the location -// of the next byte immediately after the most recently written token or value. -// The number of bytes actually written to the underlying io.Writer may be less -// than this offset due to internal buffering effects. -func (e *Encoder) OutputOffset() int64 { - return e.previousOffsetEnd() -} - -// UnusedBuffer returns a zero-length buffer with a possible non-zero capacity. -// This buffer is intended to be used to populate a RawValue -// being passed to an immediately succeeding WriteValue call. -// -// Example usage: -// -// b := d.UnusedBuffer() -// b = append(b, '"') -// b = appendString(b, v) // append the string formatting of v -// b = append(b, '"') -// ... := d.WriteValue(b) -// -// It is the user's responsibility to ensure that the value is valid JSON. -func (e *Encoder) UnusedBuffer() []byte { - // NOTE: We don't return e.buf[len(e.buf):cap(e.buf)] since WriteValue would - // need to take special care to avoid mangling the data while reformatting. - // WriteValue can't easily identify whether the input RawValue aliases e.buf - // without using unsafe.Pointer. Thus, we just return a different buffer. - // Should this ever alias e.buf, we need to consider how it operates with - // the specialized performance optimization for bytes.Buffer. - n := 1 << bits.Len(uint(e.maxValue|63)) // fast approximation for max length - if cap(e.unusedCache) < n { - e.unusedCache = make([]byte, 0, n) - } - return e.unusedCache -} - -// StackDepth returns the depth of the state machine for written JSON data. -// Each level on the stack represents a nested JSON object or array. -// It is incremented whenever an ObjectStart or ArrayStart token is encountered -// and decremented whenever an ObjectEnd or ArrayEnd token is encountered. -// The depth is zero-indexed, where zero represents the top-level JSON value. -func (e *Encoder) StackDepth() int { - // NOTE: Keep in sync with Decoder.StackDepth. - return e.tokens.depth() - 1 -} - -// StackIndex returns information about the specified stack level. -// It must be a number between 0 and StackDepth, inclusive. -// For each level, it reports the kind: -// -// - 0 for a level of zero, -// - '{' for a level representing a JSON object, and -// - '[' for a level representing a JSON array. -// -// It also reports the length of that JSON object or array. -// Each name and value in a JSON object is counted separately, -// so the effective number of members would be half the length. -// A complete JSON object must have an even length. -func (e *Encoder) StackIndex(i int) (Kind, int) { - // NOTE: Keep in sync with Decoder.StackIndex. - switch s := e.tokens.index(i); { - case i > 0 && s.isObject(): - return '{', s.length() - case i > 0 && s.isArray(): - return '[', s.length() - default: - return 0, s.length() - } -} - -// StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value. -// Object names are only present if AllowDuplicateNames is false, otherwise -// object members are represented using their index within the object. -func (e *Encoder) StackPointer() string { - e.names.copyQuotedBuffer(e.buf) - return string(e.appendStackPointer(nil)) -} - -// appendString appends src to dst as a JSON string per RFC 7159, section 7. -// -// If validateUTF8 is specified, this rejects input that contains invalid UTF-8 -// otherwise invalid bytes are replaced with the Unicode replacement character. -// If escapeRune is provided, it specifies which runes to escape using -// hexadecimal sequences. If nil, the shortest representable form is used, -// which is also the canonical form for strings (RFC 8785, section 3.2.2.2). -// -// Note that this API allows full control over the formatting of strings -// except for whether a forward solidus '/' may be formatted as '\/' and -// the casing of hexadecimal Unicode escape sequences. -func appendString(dst []byte, src string, validateUTF8 bool, escapeRune func(rune) bool) ([]byte, error) { - appendEscapedASCII := func(dst []byte, c byte) []byte { - switch c { - case '"', '\\': - dst = append(dst, '\\', c) - case '\b': - dst = append(dst, "\\b"...) - case '\f': - dst = append(dst, "\\f"...) - case '\n': - dst = append(dst, "\\n"...) - case '\r': - dst = append(dst, "\\r"...) - case '\t': - dst = append(dst, "\\t"...) - default: - dst = append(dst, "\\u"...) - dst = appendHexUint16(dst, uint16(c)) - } - return dst - } - appendEscapedUnicode := func(dst []byte, r rune) []byte { - if r1, r2 := utf16.EncodeRune(r); r1 != '\ufffd' && r2 != '\ufffd' { - dst = append(dst, "\\u"...) - dst = appendHexUint16(dst, uint16(r1)) - dst = append(dst, "\\u"...) - dst = appendHexUint16(dst, uint16(r2)) - } else { - dst = append(dst, "\\u"...) - dst = appendHexUint16(dst, uint16(r)) - } - return dst - } - - // Optimize for when escapeRune is nil. - if escapeRune == nil { - var i, n int - dst = append(dst, '"') - for uint(len(src)) > uint(n) { - // Handle single-byte ASCII. - if c := src[n]; c < utf8.RuneSelf { - n++ - if c < ' ' || c == '"' || c == '\\' { - dst = append(dst, src[i:n-1]...) - dst = appendEscapedASCII(dst, c) - i = n - } - continue - } - - // Handle multi-byte Unicode. - _, rn := utf8.DecodeRuneInString(src[n:]) - n += rn - if rn == 1 { // must be utf8.RuneError since we already checked for single-byte ASCII - dst = append(dst, src[i:n-rn]...) - if validateUTF8 { - return dst, &SyntacticError{str: "invalid UTF-8 within string"} - } - dst = append(dst, "\ufffd"...) - i = n - } - } - dst = append(dst, src[i:n]...) - dst = append(dst, '"') - return dst, nil - } - - // Slower implementation for when escapeRune is non-nil. - var i, n int - dst = append(dst, '"') - for uint(len(src)) > uint(n) { - switch r, rn := utf8.DecodeRuneInString(src[n:]); { - case r == utf8.RuneError && rn == 1: - dst = append(dst, src[i:n]...) - if validateUTF8 { - return dst, &SyntacticError{str: "invalid UTF-8 within string"} - } - if escapeRune('\ufffd') { - dst = append(dst, `\ufffd`...) - } else { - dst = append(dst, "\ufffd"...) - } - n += rn - i = n - case escapeRune(r): - dst = append(dst, src[i:n]...) - dst = appendEscapedUnicode(dst, r) - n += rn - i = n - case r < ' ' || r == '"' || r == '\\': - dst = append(dst, src[i:n]...) - dst = appendEscapedASCII(dst, byte(r)) - n += rn - i = n - default: - n += rn - } - } - dst = append(dst, src[i:n]...) - dst = append(dst, '"') - return dst, nil -} - -// reformatString consumes a JSON string from src and appends it to dst, -// reformatting it if necessary for the given escapeRune parameter. -// It returns the appended output and the remainder of the input. -func reformatString(dst, src []byte, validateUTF8, preserveRaw bool, escapeRune func(rune) bool) ([]byte, []byte, error) { - // TODO: Should this update valueFlags as input? - var flags valueFlags - n, err := consumeString(&flags, src, validateUTF8) - if err != nil { - return dst, src[n:], err - } - if preserveRaw || (escapeRune == nil && flags.isCanonical()) { - dst = append(dst, src[:n]...) // copy the string verbatim - return dst, src[n:], nil - } - - // TODO: Implement a direct, raw-to-raw reformat for strings. - // If the escapeRune option would have resulted in no changes to the output, - // it would be faster to simply append src to dst without going through - // an intermediary representation in a separate buffer. - b, _ := unescapeString(make([]byte, 0, n), src[:n]) - dst, _ = appendString(dst, string(b), validateUTF8, escapeRune) - return dst, src[n:], nil -} - -// appendNumber appends src to dst as a JSON number per RFC 7159, section 6. -// It formats numbers similar to the ES6 number-to-string conversion. -// See https://go.dev/issue/14135. -// -// The output is identical to ECMA-262, 6th edition, section 7.1.12.1 and with -// RFC 8785, section 3.2.2.3 for 64-bit floating-point numbers except for -0, -// which is formatted as -0 instead of just 0. -// -// For 32-bit floating-point numbers, -// the output is a 32-bit equivalent of the algorithm. -// Note that ECMA-262 specifies no algorithm for 32-bit numbers. -func appendNumber(dst []byte, src float64, bits int) []byte { - if bits == 32 { - src = float64(float32(src)) - } - - abs := math.Abs(src) - fmt := byte('f') - if abs != 0 { - if bits == 64 && (float64(abs) < 1e-6 || float64(abs) >= 1e21) || - bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { - fmt = 'e' - } - } - dst = strconv.AppendFloat(dst, src, fmt, -1, bits) - if fmt == 'e' { - // Clean up e-09 to e-9. - n := len(dst) - if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' { - dst[n-2] = dst[n-1] - dst = dst[:n-1] - } - } - return dst -} - -// reformatNumber consumes a JSON string from src and appends it to dst, -// canonicalizing it if specified. -// It returns the appended output and the remainder of the input. -func reformatNumber(dst, src []byte, canonicalize bool) ([]byte, []byte, error) { - n, err := consumeNumber(src) - if err != nil { - return dst, src[n:], err - } - if !canonicalize { - dst = append(dst, src[:n]...) // copy the number verbatim - return dst, src[n:], nil - } - - // Canonicalize the number per RFC 8785, section 3.2.2.3. - // As an optimization, we can copy integer numbers below 2⁵³ verbatim. - const maxExactIntegerDigits = 16 // len(strconv.AppendUint(nil, 1<<53, 10)) - if n < maxExactIntegerDigits && consumeSimpleNumber(src[:n]) == n { - dst = append(dst, src[:n]...) // copy the number verbatim - return dst, src[n:], nil - } - fv, _ := strconv.ParseFloat(string(src[:n]), 64) - switch { - case fv == 0: - fv = 0 // normalize negative zero as just zero - case math.IsInf(fv, +1): - fv = +math.MaxFloat64 - case math.IsInf(fv, -1): - fv = -math.MaxFloat64 - } - return appendNumber(dst, fv, 64), src[n:], nil -} - -// appendHexUint16 appends src to dst as a 4-byte hexadecimal number. -func appendHexUint16(dst []byte, src uint16) []byte { - dst = append(dst, "0000"[1+(bits.Len16(src)-1)/4:]...) - dst = strconv.AppendUint(dst, uint64(src), 16) - return dst -} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go index 35be8601e..1df765384 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go @@ -5,40 +5,56 @@ package json import ( + "cmp" "errors" + "fmt" "reflect" "strconv" "strings" - "unicode/utf8" -) + "sync" -const errorPrefix = "json: " + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" +) -// Error matches errors returned by this package according to errors.Is. -const Error = jsonError("json error") +// ErrUnknownName indicates that a JSON object member could not be +// unmarshaled because the name is not known to the target Go struct. +// This error is directly wrapped within a [SemanticError] when produced. +// +// The name of an unknown JSON object member can be extracted as: +// +// err := ... +// var serr json.SemanticError +// if errors.As(err, &serr) && serr.Err == json.ErrUnknownName { +// ptr := serr.JSONPointer // JSON pointer to unknown name +// name := ptr.LastToken() // unknown name itself +// ... +// } +// +// This error is only returned if [RejectUnknownMembers] is true. +var ErrUnknownName = errors.New("unknown object member name") -type jsonError string +const errorPrefix = "json: " -func (e jsonError) Error() string { - return string(e) -} -func (e jsonError) Is(target error) bool { - return e == target || target == Error +func isSemanticError(err error) bool { + _, ok := err.(*SemanticError) + return ok } -type ioError struct { - action string // either "read" or "write" - err error +func isSyntacticError(err error) bool { + _, ok := err.(*jsontext.SyntacticError) + return ok } -func (e *ioError) Error() string { - return errorPrefix + e.action + " error: " + e.err.Error() -} -func (e *ioError) Unwrap() error { - return e.err -} -func (e *ioError) Is(target error) bool { - return e == target || target == Error || errors.Is(e.err, target) +// isFatalError reports whether this error must terminate asharling. +// All errors are considered fatal unless operating under +// [jsonflags.ReportErrorsWithLegacySemantics] in which case only +// syntactic errors and I/O errors are considered fatal. +func isFatalError(err error, flags jsonflags.Flags) bool { + return !flags.Get(jsonflags.ReportErrorsWithLegacySemantics) || + isSyntacticError(err) || export.IsIOError(err) } // SemanticError describes an error determining the meaning @@ -55,10 +71,13 @@ type SemanticError struct { ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). - JSONPointer string + JSONPointer jsontext.Pointer // JSONKind is the JSON kind that could not be handled. - JSONKind Kind // may be zero if unknown + JSONKind jsontext.Kind // may be zero if unknown + // JSONValue is the JSON number or string that could not be unmarshaled. + // It is not populated during marshaling. + JSONValue jsontext.Value // may be nil if irrelevant or unknown // GoType is the Go type that could not be handled. GoType reflect.Type // may be nil if unknown @@ -66,18 +85,228 @@ type SemanticError struct { Err error // may be nil } -func (e *SemanticError) Error() string { - var sb strings.Builder - sb.WriteString(errorPrefix) +// coder is implemented by [jsontext.Encoder] or [jsontext.Decoder]. +type coder interface { + StackPointer() jsontext.Pointer + Options() Options +} + +// newInvalidFormatError wraps err in a SemanticError because +// the current type t cannot handle the provided options format. +// This error must be called before producing or consuming the next value. +// +// If [jsonflags.ReportErrorsWithLegacySemantics] is specified, +// then this automatically skips the next value when unmarshaling +// to ensure that the value is fully consumed. +func newInvalidFormatError(c coder, t reflect.Type) error { + err := fmt.Errorf("invalid format flag %q", c.Options().(*jsonopts.Struct).Format) + switch c := c.(type) { + case *jsontext.Encoder: + err = newMarshalErrorBefore(c, t, err) + case *jsontext.Decoder: + err = newUnmarshalErrorBeforeWithSkipping(c, t, err) + } + return err +} + +// newMarshalErrorBefore wraps err in a SemanticError assuming that e +// is positioned right before the next token or value, which causes an error. +func newMarshalErrorBefore(e *jsontext.Encoder, t reflect.Type, err error) error { + return &SemanticError{action: "marshal", GoType: t, Err: err, + ByteOffset: e.OutputOffset() + int64(export.Encoder(e).CountNextDelimWhitespace()), + JSONPointer: jsontext.Pointer(export.Encoder(e).AppendStackPointer(nil, +1))} +} + +// newUnmarshalErrorBefore wraps err in a SemanticError assuming that d +// is positioned right before the next token or value, which causes an error. +// It does not record the next JSON kind as this error is used to indicate +// the receiving Go value is invalid to unmarshal into (and not a JSON error). +// However, if [jsonflags.ReportErrorsWithLegacySemantics] is specified, +// then it does record the next JSON kind for historical reporting reasons. +func newUnmarshalErrorBefore(d *jsontext.Decoder, t reflect.Type, err error) error { + var k jsontext.Kind + if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + k = d.PeekKind() + } + return &SemanticError{action: "unmarshal", GoType: t, Err: err, + ByteOffset: d.InputOffset() + int64(export.Decoder(d).CountNextDelimWhitespace()), + JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, +1)), + JSONKind: k} +} + +// newUnmarshalErrorBeforeWithSkipping is like [newUnmarshalErrorBefore], +// but automatically skips the next value if +// [jsonflags.ReportErrorsWithLegacySemantics] is specified. +func newUnmarshalErrorBeforeWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error { + err = newUnmarshalErrorBefore(d, t, err) + if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + if err2 := export.Decoder(d).SkipValue(); err2 != nil { + return err2 + } + } + return err +} + +// newUnmarshalErrorAfter wraps err in a SemanticError assuming that d +// is positioned right after the previous token or value, which caused an error. +func newUnmarshalErrorAfter(d *jsontext.Decoder, t reflect.Type, err error) error { + tokOrVal := export.Decoder(d).PreviousTokenOrValue() + return &SemanticError{action: "unmarshal", GoType: t, Err: err, + ByteOffset: d.InputOffset() - int64(len(tokOrVal)), + JSONPointer: jsontext.Pointer(export.Decoder(d).AppendStackPointer(nil, -1)), + JSONKind: jsontext.Value(tokOrVal).Kind()} +} + +// newUnmarshalErrorAfter wraps err in a SemanticError assuming that d +// is positioned right after the previous token or value, which caused an error. +// It also stores a copy of the last JSON value if it is a string or number. +func newUnmarshalErrorAfterWithValue(d *jsontext.Decoder, t reflect.Type, err error) error { + serr := newUnmarshalErrorAfter(d, t, err).(*SemanticError) + if serr.JSONKind == '"' || serr.JSONKind == '0' { + serr.JSONValue = jsontext.Value(export.Decoder(d).PreviousTokenOrValue()).Clone() + } + return serr +} + +// newUnmarshalErrorAfterWithSkipping is like [newUnmarshalErrorAfter], +// but automatically skips the remainder of the current value if +// [jsonflags.ReportErrorsWithLegacySemantics] is specified. +func newUnmarshalErrorAfterWithSkipping(d *jsontext.Decoder, t reflect.Type, err error) error { + err = newUnmarshalErrorAfter(d, t, err) + if export.Decoder(d).Flags.Get(jsonflags.ReportErrorsWithLegacySemantics) { + if err2 := export.Decoder(d).SkipValueRemainder(); err2 != nil { + return err2 + } + } + return err +} - // Hyrum-proof the error message by deliberately switching between - // two equivalent renderings of the same error message. - // The randomization is tied to the Hyrum-proofing already applied - // on map iteration in Go. +// newSemanticErrorWithPosition wraps err in a SemanticError assuming that +// the error occurred at the provided depth, and length. +// If err is already a SemanticError, then position information is only +// injected if it is currently unpopulated. +// +// If the position is unpopulated, it is ambiguous where the error occurred +// in the user code, whether it was before or after the current position. +// For the byte offset, we assume that the error occurred before the last read +// token or value when decoding, or before the next value when encoding. +// For the JSON pointer, we point to the parent object or array unless +// we can be certain that it happened with an object member. +// +// This is used to annotate errors returned by user-provided +// v2 MarshalJSON or UnmarshalJSON methods or functions. +func newSemanticErrorWithPosition(c coder, t reflect.Type, prevDepth int, prevLength int64, err error) error { + serr, _ := err.(*SemanticError) + if serr == nil { + serr = &SemanticError{Err: err} + } + var currDepth int + var currLength int64 + var coderState interface{ AppendStackPointer([]byte, int) []byte } + var offset int64 + switch c := c.(type) { + case *jsontext.Encoder: + e := export.Encoder(c) + serr.action = cmp.Or(serr.action, "marshal") + currDepth, currLength = e.Tokens.DepthLength() + offset = c.OutputOffset() + int64(export.Encoder(c).CountNextDelimWhitespace()) + coderState = e + case *jsontext.Decoder: + d := export.Decoder(c) + serr.action = cmp.Or(serr.action, "unmarshal") + currDepth, currLength = d.Tokens.DepthLength() + tokOrVal := d.PreviousTokenOrValue() + offset = c.InputOffset() - int64(len(tokOrVal)) + if (prevDepth == currDepth && prevLength == currLength) || len(tokOrVal) == 0 { + // If no Read method was called in the user-defined method or + // if the Peek method was called, then use the offset of the next value. + offset = c.InputOffset() + int64(export.Decoder(c).CountNextDelimWhitespace()) + } + coderState = d + } + serr.ByteOffset = cmp.Or(serr.ByteOffset, offset) + if serr.JSONPointer == "" { + where := 0 // default to ambiguous positioning + switch { + case prevDepth == currDepth && prevLength+0 == currLength: + where = +1 + case prevDepth == currDepth && prevLength+1 == currLength: + where = -1 + } + serr.JSONPointer = jsontext.Pointer(coderState.AppendStackPointer(nil, where)) + } + serr.GoType = cmp.Or(serr.GoType, t) + return serr +} + +// collapseSemanticErrors collapses double SemanticErrors at the outer levels +// into a single SemanticError by preserving the inner error, +// but prepending the ByteOffset and JSONPointer with the outer error. +// +// For example: +// +// collapseSemanticErrors(&SemanticError{ +// ByteOffset: len64(`[0,{"alpha":[0,1,`), +// JSONPointer: "/1/alpha/2", +// GoType: reflect.TypeFor[outerType](), +// Err: &SemanticError{ +// ByteOffset: len64(`{"foo":"bar","fizz":[0,`), +// JSONPointer: "/fizz/1", +// GoType: reflect.TypeFor[innerType](), +// Err: ..., +// }, +// }) +// +// results in: +// +// &SemanticError{ +// ByteOffset: len64(`[0,{"alpha":[0,1,`) + len64(`{"foo":"bar","fizz":[0,`), +// JSONPointer: "/1/alpha/2" + "/fizz/1", +// GoType: reflect.TypeFor[innerType](), +// Err: ..., +// } +// +// This is used to annotate errors returned by user-provided +// v1 MarshalJSON or UnmarshalJSON methods with precise position information +// if they themselves happened to return a SemanticError. +// Since MarshalJSON and UnmarshalJSON are not operating on the root JSON value, +// their positioning must be relative to the nested JSON value +// returned by UnmarshalJSON or passed to MarshalJSON. +// Therefore, we can construct an absolute position by concatenating +// the outer with the inner positions. +// +// Note that we do not use collapseSemanticErrors with user-provided functions +// that take in an [jsontext.Encoder] or [jsontext.Decoder] since they contain +// methods to report position relative to the root JSON value. +// We assume user-constructed errors are correctly precise about position. +func collapseSemanticErrors(err error) error { + if serr1, ok := err.(*SemanticError); ok { + if serr2, ok := serr1.Err.(*SemanticError); ok { + serr2.ByteOffset = serr1.ByteOffset + serr2.ByteOffset + serr2.JSONPointer = serr1.JSONPointer + serr2.JSONPointer + *serr1 = *serr2 + } + } + return err +} + +// errorModalVerb is a modal verb like "cannot" or "unable to". +// +// Once per process, Hyrum-proof the error message by deliberately +// switching between equivalent renderings of the same error message. +// The randomization is tied to the Hyrum-proofing already applied +// on map iteration in Go. +var errorModalVerb = sync.OnceValue(func() string { for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} { - sb.WriteString(phrase) - break // use whichever phrase we get in the first iteration + return phrase // use whichever phrase we get in the first iteration } + return "" +}) + +func (e *SemanticError) Error() string { + var sb strings.Builder + sb.WriteString(errorPrefix) + sb.WriteString(errorModalVerb()) // Format action. var preposition string @@ -94,7 +323,6 @@ func (e *SemanticError) Error() string { } // Format JSON kind. - var omitPreposition bool switch e.JSONKind { case 'n': sb.WriteString(" JSON null") @@ -109,75 +337,92 @@ func (e *SemanticError) Error() string { case '[', ']': sb.WriteString(" JSON array") default: - omitPreposition = true + if e.action == "" { + preposition = "" + } + } + if len(e.JSONValue) > 0 && len(e.JSONValue) < 100 { + sb.WriteByte(' ') + sb.Write(e.JSONValue) } // Format Go type. if e.GoType != nil { - if !omitPreposition { - sb.WriteString(preposition) + typeString := e.GoType.String() + if len(typeString) > 100 { + // An excessively long type string most likely occurs for + // an anonymous struct declaration with many fields. + // Reduce the noise by just printing the kind, + // and optionally prepending it with the package name + // if the struct happens to include an unexported field. + typeString = e.GoType.Kind().String() + if e.GoType.Kind() == reflect.Struct && e.GoType.Name() == "" { + for i := range e.GoType.NumField() { + if pkgPath := e.GoType.Field(i).PkgPath; pkgPath != "" { + typeString = pkgPath[strings.LastIndexByte(pkgPath, '/')+len("/"):] + ".struct" + break + } + } + } + } + sb.WriteString(preposition) + sb.WriteString(" Go ") + sb.WriteString(typeString) + } + + // Special handling for unknown names. + if e.Err == ErrUnknownName { + sb.WriteString(": ") + sb.WriteString(ErrUnknownName.Error()) + sb.WriteString(" ") + sb.WriteString(strconv.Quote(e.JSONPointer.LastToken())) + if parent := e.JSONPointer.Parent(); parent != "" { + sb.WriteString(" within ") + sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(parent), 100))) } - sb.WriteString(" Go value of type ") - sb.WriteString(e.GoType.String()) + return sb.String() } // Format where. - switch { + // Avoid printing if it overlaps with a wrapped SyntacticError. + switch serr, _ := e.Err.(*jsontext.SyntacticError); { case e.JSONPointer != "": - sb.WriteString(" within JSON value at ") - sb.WriteString(strconv.Quote(e.JSONPointer)) + if serr == nil || !e.JSONPointer.Contains(serr.JSONPointer) { + sb.WriteString(" within ") + sb.WriteString(strconv.Quote(jsonwire.TruncatePointer(string(e.JSONPointer), 100))) + } case e.ByteOffset > 0: - sb.WriteString(" after byte offset ") - sb.WriteString(strconv.FormatInt(e.ByteOffset, 10)) + if serr == nil || !(e.ByteOffset <= serr.ByteOffset) { + sb.WriteString(" after offset ") + sb.WriteString(strconv.FormatInt(e.ByteOffset, 10)) + } } // Format underlying error. if e.Err != nil { + errString := e.Err.Error() + if isSyntacticError(e.Err) { + errString = strings.TrimPrefix(errString, "jsontext: ") + } sb.WriteString(": ") - sb.WriteString(e.Err.Error()) + sb.WriteString(errString) } return sb.String() } -func (e *SemanticError) Is(target error) bool { - return e == target || target == Error || errors.Is(e.Err, target) -} + func (e *SemanticError) Unwrap() error { return e.Err } -// SyntacticError is a description of a syntactic error that occurred when -// encoding or decoding JSON according to the grammar. -// -// The contents of this error as produced by this package may change over time. -type SyntacticError struct { - requireKeyedLiterals - nonComparable - - // ByteOffset indicates that an error occurred after this byte offset. - ByteOffset int64 - str string -} - -func (e *SyntacticError) Error() string { - return errorPrefix + e.str -} -func (e *SyntacticError) Is(target error) bool { - return e == target || target == Error -} -func (e *SyntacticError) withOffset(pos int64) error { - return &SyntacticError{ByteOffset: pos, str: e.str} -} - -func newInvalidCharacterError(prefix []byte, where string) *SyntacticError { - what := quoteRune(prefix) - return &SyntacticError{str: "invalid character " + what + " " + where} -} - -func quoteRune(b []byte) string { - r, n := utf8.DecodeRune(b) - if r == utf8.RuneError && n == 1 { - return `'\x` + strconv.FormatUint(uint64(b[0]), 16) + `'` +func newDuplicateNameError(ptr jsontext.Pointer, quotedName []byte, offset int64) error { + if quotedName != nil { + name, _ := jsonwire.AppendUnquote(nil, quotedName) + ptr = ptr.AppendToken(string(name)) + } + return &jsontext.SyntacticError{ + ByteOffset: offset, + JSONPointer: ptr, + Err: jsontext.ErrDuplicateName, } - return strconv.QuoteRune(r) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go index c0ee36166..d539feedd 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go @@ -5,24 +5,26 @@ package json import ( + "cmp" "errors" "fmt" "io" "reflect" - "sort" + "slices" "strconv" "strings" "unicode" "unicode/utf8" -) -var errIgnoredField = errors.New("ignored field") + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) type isZeroer interface { IsZero() bool } -var isZeroerType = reflect.TypeOf((*isZeroer)(nil)).Elem() +var isZeroerType = reflect.TypeFor[isZeroer]() type structFields struct { flattened []structField // listed in depth-first ordering @@ -31,9 +33,37 @@ type structFields struct { inlinedFallback *structField } +// reindex recomputes index to avoid bounds check during runtime. +// +// During the construction of each [structField] in [makeStructFields], +// the index field is 0-indexed. However, before it returns, +// the 0th field is stored in index0 and index stores the remainder. +func (sf *structFields) reindex() { + reindex := func(f *structField) { + f.index0 = f.index[0] + f.index = f.index[1:] + if len(f.index) == 0 { + f.index = nil // avoid pinning the backing slice + } + } + for i := range sf.flattened { + reindex(&sf.flattened[i]) + } + if sf.inlinedFallback != nil { + reindex(sf.inlinedFallback) + } +} + +// lookupByFoldedName looks up name by a case-insensitive match +// that also ignores the presence of dashes and underscores. +func (fs *structFields) lookupByFoldedName(name []byte) []*structField { + return fs.byFoldedName[string(foldName(name))] +} + type structField struct { id int // unique numeric ID in breadth-first ordering - index []int // index into a struct according to reflect.Type.FieldByIndex + index0 int // 0th index into a struct according to [reflect.Type.FieldByIndex] + index []int // 1st index and remainder according to [reflect.Type.FieldByIndex] typ reflect.Type fncs *arshaler isZero func(addressableValue) bool @@ -41,18 +71,12 @@ type structField struct { fieldOptions } -func makeStructFields(root reflect.Type) (structFields, *SemanticError) { - var fs structFields - fs.byActualName = make(map[string]*structField, root.NumField()) - fs.byFoldedName = make(map[string][]*structField, root.NumField()) +var errNoExportedFields = errors.New("Go struct has no exported fields") - // ambiguous is a sentinel value to indicate that at least two fields - // at the same depth have the same name, and thus cancel each other out. - // This follows the same rules as selecting a field on embedded structs - // where the shallowest field takes precedence. If more than one field - // exists at the shallowest depth, then the selection is illegal. - // See https://go.dev/ref/spec#Selectors. - ambiguous := new(structField) +func makeStructFields(root reflect.Type) (fs structFields, serr *SemanticError) { + orErrorf := func(serr *SemanticError, t reflect.Type, f string, a ...any) *SemanticError { + return cmp.Or(serr, &SemanticError{GoType: t, Err: fmt.Errorf(f, a...)}) + } // Setup a queue for a breath-first search. var queueIndex int @@ -66,6 +90,7 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { // Perform a breadth-first search over all reachable fields. // This ensures that len(f.index) will be monotonically increasing. + var allFields, inlinedFallbacks []structField for queueIndex < len(queue) { qe := queue[queueIndex] queueIndex++ @@ -75,16 +100,16 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { namesIndex := make(map[string]int) // index of each field with a given JSON object name in current struct var hasAnyJSONTag bool // whether any Go struct field has a `json` tag var hasAnyJSONField bool // whether any JSON serializable fields exist in current struct - for i := 0; i < t.NumField(); i++ { + for i := range t.NumField() { sf := t.Field(i) _, hasTag := sf.Tag.Lookup("json") hasAnyJSONTag = hasAnyJSONTag || hasTag - options, err := parseFieldOptions(sf) + options, ignored, err := parseFieldOptions(sf) if err != nil { - if err == errIgnoredField { - continue - } - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = cmp.Or(serr, &SemanticError{GoType: t, Err: err}) + } + if ignored { + continue } hasAnyJSONField = true f := structField{ @@ -96,84 +121,104 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { fieldOptions: options, } if sf.Anonymous && !f.hasName { - f.inline = true // implied by use of Go embedding without an explicit name + if indirectType(f.typ).Kind() != reflect.Struct { + serr = orErrorf(serr, t, "embedded Go struct field %s of non-struct type must be explicitly given a JSON name", sf.Name) + } else { + f.inline = true // implied by use of Go embedding without an explicit name + } } if f.inline || f.unknown { // Handle an inlined field that serializes to/from // zero or more JSON object members. - if f.inline && f.unknown { - err := fmt.Errorf("Go struct field %s cannot have both `inline` and `unknown` specified", sf.Name) - return structFields{}, &SemanticError{GoType: t, Err: err} - } switch f.fieldOptions { case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true}: case fieldOptions{name: f.name, quotedName: f.quotedName, unknown: true}: + case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true, unknown: true}: + serr = orErrorf(serr, t, "Go struct field %s cannot have both `inline` and `unknown` specified", sf.Name) + f.inline = false // let `unknown` take precedence default: - err := fmt.Errorf("Go struct field %s cannot have any options other than `inline` or `unknown` specified", sf.Name) - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = orErrorf(serr, t, "Go struct field %s cannot have any options other than `inline` or `unknown` specified", sf.Name) + if f.hasName { + continue // invalid inlined field; treat as ignored + } + f.fieldOptions = fieldOptions{name: f.name, quotedName: f.quotedName, inline: f.inline, unknown: f.unknown} + if f.inline && f.unknown { + f.inline = false // let `unknown` take precedence + } } - // Unwrap one level of pointer indirection similar to how Go - // only allows embedding either T or *T, but not **T. - tf := f.typ - if tf.Kind() == reflect.Pointer && tf.Name() == "" { - tf = tf.Elem() - } // Reject any types with custom serialization otherwise // it becomes impossible to know what sub-fields to inline. - if which, _ := implementsWhich(tf, - jsonMarshalerV2Type, jsonMarshalerV1Type, textMarshalerType, - jsonUnmarshalerV2Type, jsonUnmarshalerV1Type, textUnmarshalerType, - ); which != nil && tf != rawValueType { - err := fmt.Errorf("inlined Go struct field %s of type %s must not implement JSON marshal or unmarshal methods", sf.Name, tf) - return structFields{}, &SemanticError{GoType: t, Err: err} + tf := indirectType(f.typ) + if implementsAny(tf, allMethodTypes...) && tf != jsontextValueType { + serr = orErrorf(serr, t, "inlined Go struct field %s of type %s must not implement marshal or unmarshal methods", sf.Name, tf) } // Handle an inlined field that serializes to/from // a finite number of JSON object members backed by a Go struct. if tf.Kind() == reflect.Struct { if f.unknown { - err := fmt.Errorf("inlined Go struct field %s of type %s with `unknown` tag must be a Go map of string key or a json.RawValue", sf.Name, tf) - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = orErrorf(serr, t, "inlined Go struct field %s of type %s with `unknown` tag must be a Go map of string key or a jsontext.Value", sf.Name, tf) + continue // invalid inlined field; treat as ignored } if qe.visitChildren { queue = append(queue, queueEntry{tf, f.index, !seen[tf]}) } seen[tf] = true continue + } else if !sf.IsExported() { + serr = orErrorf(serr, t, "inlined Go struct field %s is not exported", sf.Name) + continue // invalid inlined field; treat as ignored } // Handle an inlined field that serializes to/from any number of - // JSON object members back by a Go map or RawValue. + // JSON object members back by a Go map or jsontext.Value. switch { - case tf == rawValueType: + case tf == jsontextValueType: f.fncs = nil // specially handled in arshal_inlined.go - case tf.Kind() == reflect.Map && tf.Key() == stringType: + case tf.Kind() == reflect.Map && tf.Key().Kind() == reflect.String: + if implementsAny(tf.Key(), allMethodTypes...) { + serr = orErrorf(serr, t, "inlined map field %s of type %s must have a string key that does not implement marshal or unmarshal methods", sf.Name, tf) + continue // invalid inlined field; treat as ignored + } f.fncs = lookupArshaler(tf.Elem()) default: - err := fmt.Errorf("inlined Go struct field %s of type %s must be a Go struct, Go map of string key, or json.RawValue", sf.Name, tf) - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = orErrorf(serr, t, "inlined Go struct field %s of type %s must be a Go struct, Go map of string key, or jsontext.Value", sf.Name, tf) + continue // invalid inlined field; treat as ignored } // Reject multiple inlined fallback fields within the same struct. if inlinedFallbackIndex >= 0 { - err := fmt.Errorf("inlined Go struct fields %s and %s cannot both be a Go map or json.RawValue", t.Field(inlinedFallbackIndex).Name, sf.Name) - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = orErrorf(serr, t, "inlined Go struct fields %s and %s cannot both be a Go map or jsontext.Value", t.Field(inlinedFallbackIndex).Name, sf.Name) + // Still append f to inlinedFallbacks as there is still a + // check for a dominant inlined fallback before returning. } inlinedFallbackIndex = i - // Multiple inlined fallback fields across different structs - // follow the same precedence rules as Go struct embedding. - if fs.inlinedFallback == nil { - fs.inlinedFallback = &f // store first occurrence at lowest depth - } else if len(fs.inlinedFallback.index) == len(f.index) { - fs.inlinedFallback = ambiguous // at least two occurrences at same depth - } + inlinedFallbacks = append(inlinedFallbacks, f) } else { // Handle normal Go struct field that serializes to/from // a single JSON object member. + // Unexported fields cannot be serialized except for + // embedded fields of a struct type, + // which might promote exported fields of their own. + if !sf.IsExported() { + tf := indirectType(f.typ) + if !(sf.Anonymous && tf.Kind() == reflect.Struct) { + serr = orErrorf(serr, t, "Go struct field %s is not exported", sf.Name) + continue + } + // Unfortunately, methods on the unexported field + // still cannot be called. + if implementsAny(tf, allMethodTypes...) || + (f.omitzero && implementsAny(tf, isZeroerType)) { + serr = orErrorf(serr, t, "Go struct field %s is not exported for method calls", sf.Name) + continue + } + } + // Provide a function that uses a type's IsZero method. switch { case sf.Type.Kind() == reflect.Interface && sf.Type.Implements(isZeroerType): @@ -202,29 +247,17 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { f.isEmpty = func(va addressableValue) bool { return va.IsNil() } } - f.id = len(fs.flattened) - f.fncs = lookupArshaler(sf.Type) - fs.flattened = append(fs.flattened, f) - - // Reject user-specified names with invalid UTF-8. - if !utf8.ValidString(f.name) { - err := fmt.Errorf("Go struct field %s has JSON object name %q with invalid UTF-8", sf.Name, f.name) - return structFields{}, &SemanticError{GoType: t, Err: err} - } // Reject multiple fields with same name within the same struct. if j, ok := namesIndex[f.name]; ok { - err := fmt.Errorf("Go struct fields %s and %s conflict over JSON object name %q", t.Field(j).Name, sf.Name, f.name) - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = orErrorf(serr, t, "Go struct fields %s and %s conflict over JSON object name %q", t.Field(j).Name, sf.Name, f.name) + // Still append f to allFields as there is still a + // check for a dominant field before returning. } namesIndex[f.name] = i - // Multiple fields of the same name across different structs - // follow the same precedence rules as Go struct embedding. - if f2 := fs.byActualName[f.name]; f2 == nil { - fs.byActualName[f.name] = &fs.flattened[len(fs.flattened)-1] // store first occurrence at lowest depth - } else if len(f2.index) == len(f.index) { - fs.byActualName[f.name] = ambiguous // at least two occurrences at same depth - } + f.id = len(allFields) + f.fncs = lookupArshaler(sf.Type) + allFields = append(allFields, f) } } @@ -239,58 +272,58 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { // errors returned by errors.New would fail to serialize. isEmptyStruct := t.NumField() == 0 if !isEmptyStruct && !hasAnyJSONTag && !hasAnyJSONField { - err := errors.New("Go struct has no exported fields") - return structFields{}, &SemanticError{GoType: t, Err: err} + serr = cmp.Or(serr, &SemanticError{GoType: t, Err: errNoExportedFields}) } } - // Remove all fields that are duplicates. - // This may move elements forward to fill the holes from removed fields. - var n int - for _, f := range fs.flattened { - switch f2 := fs.byActualName[f.name]; { - case f2 == ambiguous: - delete(fs.byActualName, f.name) - case f2 == nil: - continue // may be nil due to previous delete - // TODO(https://go.dev/issue/45955): Use slices.Equal. - case reflect.DeepEqual(f.index, f2.index): - f.id = n - fs.flattened[n] = f - fs.byActualName[f.name] = &fs.flattened[n] // fix pointer to new location + // Sort the fields by exact name (breaking ties by depth and + // then by presence of an explicitly provided JSON name). + // Select the dominant field from each set of fields with the same name. + // If multiple fields have the same name, then the dominant field + // is the one that exists alone at the shallowest depth, + // or the one that is uniquely tagged with a JSON name. + // Otherwise, no dominant field exists for the set. + flattened := allFields[:0] + slices.SortStableFunc(allFields, func(x, y structField) int { + return cmp.Or( + strings.Compare(x.name, y.name), + cmp.Compare(len(x.index), len(y.index)), + boolsCompare(!x.hasName, !y.hasName)) + }) + for len(allFields) > 0 { + n := 1 // number of fields with the same exact name + for n < len(allFields) && allFields[n-1].name == allFields[n].name { n++ } + if n == 1 || len(allFields[0].index) != len(allFields[1].index) || allFields[0].hasName != allFields[1].hasName { + flattened = append(flattened, allFields[0]) // only keep field if there is a dominant field + } + allFields = allFields[n:] } - fs.flattened = fs.flattened[:n] - if fs.inlinedFallback == ambiguous { - fs.inlinedFallback = nil - } - if len(fs.flattened) != len(fs.byActualName) { - panic(fmt.Sprintf("BUG: flattened list of fields mismatches fields mapped by name: %d != %d", len(fs.flattened), len(fs.byActualName))) + + // Sort the fields according to a breadth-first ordering + // so that we can re-number IDs with the smallest possible values. + // This optimizes use of uintSet such that it fits in the 64-entry bit set. + slices.SortFunc(flattened, func(x, y structField) int { + return cmp.Compare(x.id, y.id) + }) + for i := range flattened { + flattened[i].id = i } - // Sort the fields according to a depth-first ordering. - // This operation will cause pointers in byActualName to become incorrect, - // which we will correct in another loop shortly thereafter. - sort.Slice(fs.flattened, func(i, j int) bool { - si := fs.flattened[i].index - sj := fs.flattened[j].index - for len(si) > 0 && len(sj) > 0 { - switch { - case si[0] < sj[0]: - return true - case si[0] > sj[0]: - return false - default: - si = si[1:] - sj = sj[1:] - } - } - return len(si) < len(sj) + // Sort the fields according to a depth-first ordering + // as the typical order that fields are marshaled. + slices.SortFunc(flattened, func(x, y structField) int { + return slices.Compare(x.index, y.index) }) - // Recompute the mapping of fields in the byActualName map. + // Compute the mapping of fields in the byActualName map. // Pre-fold all names so that we can lookup folded names quickly. + fs = structFields{ + flattened: flattened, + byActualName: make(map[string]*structField, len(flattened)), + byFoldedName: make(map[string][]*structField, len(flattened)), + } for i, f := range fs.flattened { foldedName := string(foldName([]byte(f.name))) fs.byActualName[f.name] = &fs.flattened[i] @@ -298,58 +331,99 @@ func makeStructFields(root reflect.Type) (structFields, *SemanticError) { } for foldedName, fields := range fs.byFoldedName { if len(fields) > 1 { - // The precedence order for conflicting nocase names + // The precedence order for conflicting ignoreCase names // is by breadth-first order, rather than depth-first order. - sort.Slice(fields, func(i, j int) bool { - return fields[i].id < fields[j].id + slices.SortFunc(fields, func(x, y *structField) int { + return cmp.Compare(x.id, y.id) }) fs.byFoldedName[foldedName] = fields } } + if n := len(inlinedFallbacks); n == 1 || (n > 1 && len(inlinedFallbacks[0].index) != len(inlinedFallbacks[1].index)) { + fs.inlinedFallback = &inlinedFallbacks[0] // dominant inlined fallback field + } + fs.reindex() + return fs, serr +} + +// indirectType unwraps one level of pointer indirection +// similar to how Go only allows embedding either T or *T, +// but not **T or P (which is a named pointer). +func indirectType(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Pointer && t.Name() == "" { + t = t.Elem() + } + return t +} - return fs, nil +// matchFoldedName matches a case-insensitive name depending on the options. +// It assumes that foldName(f.name) == foldName(name). +// +// Case-insensitive matching is used if the `case:ignore` tag option is specified +// or the MatchCaseInsensitiveNames call option is specified +// (and the `case:strict` tag option is not specified). +// Functionally, the `case:ignore` and `case:strict` tag options take precedence. +// +// The v1 definition of case-insensitivity operated under strings.EqualFold +// and would strictly compare dashes and underscores, +// while the v2 definition would ignore the presence of dashes and underscores. +// Thus, if the MatchCaseSensitiveDelimiter call option is specified, +// the match is further restricted to using strings.EqualFold. +func (f *structField) matchFoldedName(name []byte, flags *jsonflags.Flags) bool { + if f.casing == caseIgnore || (flags.Get(jsonflags.MatchCaseInsensitiveNames) && f.casing != caseStrict) { + if !flags.Get(jsonflags.MatchCaseSensitiveDelimiter) || strings.EqualFold(string(name), f.name) { + return true + } + } + return false } +const ( + caseIgnore = 1 + caseStrict = 2 +) + type fieldOptions struct { - name string - quotedName string // quoted name per RFC 8785, section 3.2.2.2. - hasName bool - nocase bool - inline bool - unknown bool - omitzero bool - omitempty bool - string bool - format string + name string + quotedName string // quoted name per RFC 8785, section 3.2.2.2. + hasName bool + nameNeedEscape bool + casing int8 // either 0, caseIgnore, or caseStrict + inline bool + unknown bool + omitzero bool + omitempty bool + string bool + format string } // parseFieldOptions parses the `json` tag in a Go struct field as // a structured set of options configuring parameters such as // the JSON member name and other features. -// As a special case, it returns errIgnoredField if the field is ignored. -func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { +func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool, err error) { tag, hasTag := sf.Tag.Lookup("json") + tagOrig := tag // Check whether this field is explicitly ignored. if tag == "-" { - return fieldOptions{}, errIgnoredField + return fieldOptions{}, true, nil } - // Check whether this field is unexported. - if !sf.IsExported() { - // In contrast to v1, v2 no longer forwards exported fields from - // embedded fields of unexported types since Go reflection does not - // allow the same set of operations that are available in normal cases - // of purely exported fields. - // See https://go.dev/issue/21357 and https://go.dev/issue/24153. - if sf.Anonymous { - return fieldOptions{}, fmt.Errorf("embedded Go struct field %s of an unexported type must be explicitly ignored with a `json:\"-\"` tag", sf.Type.Name()) - } + // Check whether this field is unexported and not embedded, + // which Go reflection cannot mutate for the sake of serialization. + // + // An embedded field of an unexported type is still capable of + // forwarding exported fields, which may be JSON serialized. + // This technically operates on the edge of what is permissible by + // the Go language, but the most recent decision is to permit this. + // + // See https://go.dev/issue/24153 and https://go.dev/issue/32772. + if !sf.IsExported() && !sf.Anonymous { // Tag options specified on an unexported field suggests user error. if hasTag { - return fieldOptions{}, fmt.Errorf("unexported Go struct field %s cannot have non-ignored `json:%q` tag", sf.Name, tag) + err = cmp.Or(err, fmt.Errorf("unexported Go struct field %s cannot have non-ignored `json:%q` tag", sf.Name, tag)) } - return fieldOptions{}, errIgnoredField + return fieldOptions{}, true, err } // Determine the JSON member name for this Go field. A user-specified name @@ -362,20 +436,38 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { n := len(tag) - len(strings.TrimLeftFunc(tag, func(r rune) bool { return !strings.ContainsRune(",\\'\"`", r) // reserve comma, backslash, and quotes })) - opt := tag[:n] - if n == 0 { - // Allow a single quoted string for arbitrary names. - opt, n, err = consumeTagOption(tag) - if err != nil { - return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) + name := tag[:n] + + // If the next character is not a comma, then the name is either + // malformed (if n > 0) or a single-quoted name. + // In either case, call consumeTagOption to handle it further. + var err2 error + if !strings.HasPrefix(tag[n:], ",") && len(name) != len(tag) { + name, n, err2 = consumeTagOption(tag) + if err2 != nil { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err2)) } } - out.hasName = true - out.name = opt + if !utf8.ValidString(name) { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has JSON object name %q with invalid UTF-8", sf.Name, name)) + name = string([]rune(name)) // replace invalid UTF-8 with utf8.RuneError + } + if name == "-" && tag[0] == '-' { + defer func() { // defer to let other errors take precedence + err = cmp.Or(err, fmt.Errorf("Go struct field %s has JSON object name %q; either "+ + "use `json:\"-\"` to ignore the field or "+ + "use `json:\"'-'%s` to specify %q as the name", sf.Name, out.name, strings.TrimPrefix(strconv.Quote(tagOrig), `"-`), name)) + }() + } + if err2 == nil { + out.hasName = true + out.name = name + } tag = tag[n:] } - b, _ := appendString(nil, out.name, false, nil) + b, _ := jsonwire.AppendQuote(nil, out.name, &jsonflags.Flags{}) out.quotedName = string(b) + out.nameNeedEscape = jsonwire.NeedEscape(out.name) // Handle any additional tag options (if any). var wasFormat bool @@ -383,29 +475,53 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { for len(tag) > 0 { // Consume comma delimiter. if tag[0] != ',' { - return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", sf.Name, tag[0]) - } - tag = tag[len(","):] - if len(tag) == 0 { - return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid trailing ',' character", sf.Name) + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", sf.Name, tag[0])) + } else { + tag = tag[len(","):] + if len(tag) == 0 { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid trailing ',' character", sf.Name)) + break + } } // Consume and process the tag option. - opt, n, err := consumeTagOption(tag) - if err != nil { - return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) + opt, n, err2 := consumeTagOption(tag) + if err2 != nil { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err2)) } rawOpt := tag[:n] tag = tag[n:] switch { case wasFormat: - return fieldOptions{}, fmt.Errorf("Go struct field %s has `format` tag option that was not specified last", sf.Name) + err = cmp.Or(err, fmt.Errorf("Go struct field %s has `format` tag option that was not specified last", sf.Name)) case strings.HasPrefix(rawOpt, "'") && strings.TrimFunc(opt, isLetterOrDigit) == "": - return fieldOptions{}, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", sf.Name, rawOpt, opt) + err = cmp.Or(err, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", sf.Name, rawOpt, opt)) } switch opt { - case "nocase": - out.nocase = true + case "case": + if !strings.HasPrefix(tag, ":") { + err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `case` tag option; specify `case:ignore` or `case:strict` instead", sf.Name)) + break + } + tag = tag[len(":"):] + opt, n, err2 := consumeTagOption(tag) + if err2 != nil { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `case` tag option: %v", sf.Name, err2)) + break + } + rawOpt := tag[:n] + tag = tag[n:] + if strings.HasPrefix(rawOpt, "'") { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `case:%s` tag option; specify `case:%s` instead", sf.Name, rawOpt, opt)) + } + switch opt { + case "ignore": + out.casing |= caseIgnore + case "strict": + out.casing |= caseStrict + default: + err = cmp.Or(err, fmt.Errorf("Go struct field %s has unknown `case:%s` tag value", sf.Name, rawOpt)) + } case "inline": out.inline = true case "unknown": @@ -418,12 +534,14 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { out.string = true case "format": if !strings.HasPrefix(tag, ":") { - return fieldOptions{}, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name) + err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name)) + break } tag = tag[len(":"):] - opt, n, err := consumeTagOption(tag) - if err != nil { - return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err) + opt, n, err2 := consumeTagOption(tag) + if err2 != nil { + err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err2)) + break } tag = tag[n:] out.format = opt @@ -433,8 +551,8 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { // This catches invalid mutants such as "omitEmpty" or "omit_empty". normOpt := strings.ReplaceAll(strings.ToLower(opt), "_", "") switch normOpt { - case "nocase", "inline", "unknown", "omitzero", "omitempty", "string", "format": - return fieldOptions{}, fmt.Errorf("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", sf.Name, opt, normOpt) + case "case", "inline", "unknown", "omitzero", "omitempty", "string", "format": + err = cmp.Or(err, fmt.Errorf("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", sf.Name, opt, normOpt)) } // NOTE: Everything else is ignored. This does not mean it is @@ -443,15 +561,28 @@ func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { } // Reject duplicates. - if seenOpts[opt] { - return fieldOptions{}, fmt.Errorf("Go struct field %s has duplicate appearance of `%s` tag option", sf.Name, rawOpt) + switch { + case out.casing == caseIgnore|caseStrict: + err = cmp.Or(err, fmt.Errorf("Go struct field %s cannot have both `case:ignore` and `case:strict` tag options", sf.Name)) + case seenOpts[opt]: + err = cmp.Or(err, fmt.Errorf("Go struct field %s has duplicate appearance of `%s` tag option", sf.Name, rawOpt)) } seenOpts[opt] = true } - return out, nil + return out, false, err } +// consumeTagOption consumes the next option, +// which is either a Go identifier or a single-quoted string. +// If the next option is invalid, it returns all of in until the next comma, +// and reports an error. func consumeTagOption(in string) (string, int, error) { + // For legacy compatibility with v1, assume options are comma-separated. + i := strings.IndexByte(in, ',') + if i < 0 { + i = len(in) + } + switch r, _ := utf8.DecodeRuneInString(in); { // Option as a Go identifier. case r == '_' || unicode.IsLetter(r): @@ -486,7 +617,7 @@ func consumeTagOption(in string) (string, int, error) { n += len(`'`) out, err := strconv.Unquote(string(b)) if err != nil { - return "", 0, fmt.Errorf("invalid single-quoted string: %s", in[:n]) + return in[:i], i, fmt.Errorf("invalid single-quoted string: %s", in[:n]) } return out, n, nil } @@ -496,14 +627,26 @@ func consumeTagOption(in string) (string, int, error) { if n > 10 { n = 10 // limit the amount of context printed in the error } - return "", 0, fmt.Errorf("single-quoted string not terminated: %s...", in[:n]) + return in[:i], i, fmt.Errorf("single-quoted string not terminated: %s...", in[:n]) case len(in) == 0: - return "", 0, io.ErrUnexpectedEOF + return in[:i], i, io.ErrUnexpectedEOF default: - return "", 0, fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", r) + return in[:i], i, fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", r) } } func isLetterOrDigit(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r) } + +// boolsCompare compares x and y, ordering false before true. +func boolsCompare(x, y bool) int { + switch { + case !x && y: + return -1 + default: + return 0 + case x && !y: + return +1 + } +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go index 700a56db0..42fc3d471 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go @@ -10,12 +10,12 @@ import ( ) // stringCache is a cache for strings converted from a []byte. -type stringCache [256]string // 256*unsafe.Sizeof(string("")) => 4KiB +type stringCache = [256]string // 256*unsafe.Sizeof(string("")) => 4KiB -// make returns the string form of b. +// makeString returns the string form of b. // It returns a pre-allocated string from c if present, otherwise // it allocates a new string, inserts it into the cache, and returns it. -func (c *stringCache) make(b []byte) string { +func makeString(c *stringCache, b []byte) string { const ( minCachedLen = 2 // single byte strings are already interned by the runtime maxCachedLen = 256 // large enough for UUIDs, IPv6 addresses, SHA-256 checksums, etc. diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/internal.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/internal.go new file mode 100644 index 000000000..05801c6b2 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/internal.go @@ -0,0 +1,40 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +import "errors" + +// NotForPublicUse is a marker type that an API is for internal use only. +// It does not perfectly prevent usage of that API, but helps to restrict usage. +// Anything with this marker is not covered by the Go compatibility agreement. +type NotForPublicUse struct{} + +// AllowInternalUse is passed from "json" to "jsontext" to authenticate +// that the caller can have access to internal functionality. +var AllowInternalUse NotForPublicUse + +// Sentinel error values internally shared between jsonv1 and jsonv2. +var ( + ErrCycle = errors.New("encountered a cycle") + ErrNonNilReference = errors.New("value must be passed as a non-nil pointer reference") + ErrNilInterface = errors.New("cannot derive concrete type for nil interface with finite type set") +) + +var ( + // TransformMarshalError converts a v2 error into a v1 error. + // It is called only at the top-level of a Marshal function. + TransformMarshalError func(any, error) error + // NewMarshalerError constructs a jsonv1.MarshalerError. + // It is called after a user-defined Marshal method/function fails. + NewMarshalerError func(any, error, string) error + // TransformUnmarshalError converts a v2 error into a v1 error. + // It is called only at the top-level of a Unmarshal function. + TransformUnmarshalError func(any, error) error + + // NewRawNumber returns new(jsonv1.Number). + NewRawNumber func() any + // RawNumberOf returns jsonv1.Number(b). + RawNumberOf func(b []byte) any +) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags/flags.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags/flags.go new file mode 100644 index 000000000..810128b51 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags/flags.go @@ -0,0 +1,213 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// jsonflags implements all the optional boolean flags. +// These flags are shared across both "json", "jsontext", and "jsonopts". +package jsonflags + +import "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + +// Bools represents zero or more boolean flags, all set to true or false. +// The least-significant bit is the boolean value of all flags in the set. +// The remaining bits identify which particular flags. +// +// In common usage, this is OR'd with 0 or 1. For example: +// - (AllowInvalidUTF8 | 0) means "AllowInvalidUTF8 is false" +// - (Multiline | Indent | 1) means "Multiline and Indent are true" +type Bools uint64 + +func (Bools) JSONOptions(internal.NotForPublicUse) {} + +const ( + // AllFlags is the set of all flags. + AllFlags = AllCoderFlags | AllArshalV2Flags | AllArshalV1Flags + + // AllCoderFlags is the set of all encoder/decoder flags. + AllCoderFlags = (maxCoderFlag - 1) - initFlag + + // AllArshalV2Flags is the set of all v2 marshal/unmarshal flags. + AllArshalV2Flags = (maxArshalV2Flag - 1) - (maxCoderFlag - 1) + + // AllArshalV1Flags is the set of all v1 marshal/unmarshal flags. + AllArshalV1Flags = (maxArshalV1Flag - 1) - (maxArshalV2Flag - 1) + + // NonBooleanFlags is the set of non-boolean flags, + // where the value is some other concrete Go type. + // The value of the flag is stored within jsonopts.Struct. + NonBooleanFlags = 0 | + Indent | + IndentPrefix | + ByteLimit | + DepthLimit | + Marshalers | + Unmarshalers + + // DefaultV1Flags is the set of booleans flags that default to true under + // v1 semantics. None of the non-boolean flags differ between v1 and v2. + DefaultV1Flags = 0 | + AllowDuplicateNames | + AllowInvalidUTF8 | + EscapeForHTML | + EscapeForJS | + PreserveRawStrings | + Deterministic | + FormatNilMapAsNull | + FormatNilSliceAsNull | + MatchCaseInsensitiveNames | + CallMethodsWithLegacySemantics | + FormatByteArrayAsArray | + FormatBytesWithLegacySemantics | + FormatDurationAsNano | + MatchCaseSensitiveDelimiter | + MergeWithLegacySemantics | + OmitEmptyWithLegacySemantics | + ParseBytesWithLooseRFC4648 | + ParseTimeWithLooseRFC3339 | + ReportErrorsWithLegacySemantics | + StringifyWithLegacySemantics | + UnmarshalArrayFromAnyLength + + // AnyWhitespace reports whether the encoded output might have any whitespace. + AnyWhitespace = Multiline | SpaceAfterColon | SpaceAfterComma + + // WhitespaceFlags is the set of flags related to whitespace formatting. + // In contrast to AnyWhitespace, this includes Indent and IndentPrefix + // as those settings take no effect if Multiline is false. + WhitespaceFlags = AnyWhitespace | Indent | IndentPrefix + + // AnyEscape is the set of flags related to escaping in a JSON string. + AnyEscape = EscapeForHTML | EscapeForJS + + // CanonicalizeNumbers is the set of flags related to raw number canonicalization. + CanonicalizeNumbers = CanonicalizeRawInts | CanonicalizeRawFloats +) + +// Encoder and decoder flags. +const ( + initFlag Bools = 1 << iota // reserved for the boolean value itself + + AllowDuplicateNames // encode or decode + AllowInvalidUTF8 // encode or decode + WithinArshalCall // encode or decode; for internal use by json.Marshal and json.Unmarshal + OmitTopLevelNewline // encode only; for internal use by json.Marshal and json.MarshalWrite + PreserveRawStrings // encode only + CanonicalizeRawInts // encode only + CanonicalizeRawFloats // encode only + ReorderRawObjects // encode only + EscapeForHTML // encode only + EscapeForJS // encode only + Multiline // encode only + SpaceAfterColon // encode only + SpaceAfterComma // encode only + Indent // encode only; non-boolean flag + IndentPrefix // encode only; non-boolean flag + ByteLimit // encode or decode; non-boolean flag + DepthLimit // encode or decode; non-boolean flag + + maxCoderFlag +) + +// Marshal and Unmarshal flags (for v2). +const ( + _ Bools = (maxCoderFlag >> 1) << iota + + StringifyNumbers // marshal or unmarshal + Deterministic // marshal only + FormatNilMapAsNull // marshal only + FormatNilSliceAsNull // marshal only + OmitZeroStructFields // marshal only + MatchCaseInsensitiveNames // marshal or unmarshal + DiscardUnknownMembers // marshal only + RejectUnknownMembers // unmarshal only + Marshalers // marshal only; non-boolean flag + Unmarshalers // unmarshal only; non-boolean flag + + maxArshalV2Flag +) + +// Marshal and Unmarshal flags (for v1). +const ( + _ Bools = (maxArshalV2Flag >> 1) << iota + + CallMethodsWithLegacySemantics // marshal or unmarshal + FormatByteArrayAsArray // marshal or unmarshal + FormatBytesWithLegacySemantics // marshal or unmarshal + FormatDurationAsNano // marshal or unmarshal + MatchCaseSensitiveDelimiter // marshal or unmarshal + MergeWithLegacySemantics // unmarshal + OmitEmptyWithLegacySemantics // marshal + ParseBytesWithLooseRFC4648 // unmarshal + ParseTimeWithLooseRFC3339 // unmarshal + ReportErrorsWithLegacySemantics // marshal or unmarshal + StringifyWithLegacySemantics // marshal or unmarshal + StringifyBoolsAndStrings // marshal or unmarshal; for internal use by jsonv2.makeStructArshaler + UnmarshalAnyWithRawNumber // unmarshal; for internal use by jsonv1.Decoder.UseNumber + UnmarshalArrayFromAnyLength // unmarshal + + maxArshalV1Flag +) + +// bitsUsed is the number of bits used in the 64-bit boolean flags +const bitsUsed = 42 + +// Static compile check that bitsUsed and maxArshalV1Flag are in sync. +const _ = uint64((1< 0b_110_11011 + dst.Values &= ^src.Presence // e.g., 0b_1000_0011 & 0b_1010_0101 -> 0b_100_00001 + dst.Values |= src.Values // e.g., 0b_1000_0001 | 0b_1001_0010 -> 0b_100_10011 +} + +// Set sets both the presence and value for the provided bool (or set of bools). +func (fs *Flags) Set(f Bools) { + // Select out the bits for the flag identifiers (everything except LSB), + // then set the presence for all the identifier bits (using OR), + // then invert the identifier bits to clear out the values (using AND-NOT), + // then copy over all the identifier bits to the value if LSB is 1. + // e.g., fs := Flags{Presence: 0b_0101_0010, Value: 0b_0001_0010} + // e.g., f := 0b_1001_0001 + id := uint64(f) &^ uint64(1) // e.g., 0b_1001_0001 & 0b_1111_1110 -> 0b_1001_0000 + fs.Presence |= id // e.g., 0b_0101_0010 | 0b_1001_0000 -> 0b_1101_0011 + fs.Values &= ^id // e.g., 0b_0001_0010 & 0b_0110_1111 -> 0b_0000_0010 + fs.Values |= uint64(f&1) * id // e.g., 0b_0000_0010 | 0b_1001_0000 -> 0b_1001_0010 +} + +// Get reports whether the bool (or any of the bools) is true. +// This is generally only used with a singular bool. +// The value bit of f (i.e., the LSB) is ignored. +func (fs Flags) Get(f Bools) bool { + return fs.Values&uint64(f) > 0 +} + +// Has reports whether the bool (or any of the bools) is set. +// The value bit of f (i.e., the LSB) is ignored. +func (fs Flags) Has(f Bools) bool { + return fs.Presence&uint64(f) > 0 +} + +// Clear clears both the presence and value for the provided bool or bools. +// The value bit of f (i.e., the LSB) is ignored. +func (fs *Flags) Clear(f Bools) { + // Invert f to produce a mask to clear all bits in f (using AND). + // e.g., fs := Flags{Presence: 0b_0101_0010, Value: 0b_0001_0010} + // e.g., f := 0b_0001_1000 + mask := uint64(^f) // e.g., 0b_0001_1000 -> 0b_1110_0111 + fs.Presence &= mask // e.g., 0b_0101_0010 & 0b_1110_0111 -> 0b_0100_0010 + fs.Values &= mask // e.g., 0b_0001_0010 & 0b_1110_0111 -> 0b_0000_0010 +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts/options.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts/options.go new file mode 100644 index 000000000..142653518 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts/options.go @@ -0,0 +1,200 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonopts + +import ( + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" +) + +// Options is the common options type shared across json packages. +type Options interface { + // JSONOptions is exported so related json packages can implement Options. + JSONOptions(internal.NotForPublicUse) +} + +// Struct is the combination of all options in struct form. +// This is efficient to pass down the call stack and to query. +type Struct struct { + Flags jsonflags.Flags + + CoderValues + ArshalValues +} + +type CoderValues struct { + Indent string // jsonflags.Indent + IndentPrefix string // jsonflags.IndentPrefix + ByteLimit int64 // jsonflags.ByteLimit + DepthLimit int // jsonflags.DepthLimit +} + +type ArshalValues struct { + // The Marshalers and Unmarshalers fields use the any type to avoid a + // concrete dependency on *json.Marshalers and *json.Unmarshalers, + // which would in turn create a dependency on the "reflect" package. + + Marshalers any // jsonflags.Marshalers + Unmarshalers any // jsonflags.Unmarshalers + + Format string + FormatDepth int +} + +// DefaultOptionsV2 is the set of all options that define default v2 behavior. +var DefaultOptionsV2 = Struct{ + Flags: jsonflags.Flags{ + Presence: uint64(jsonflags.AllFlags & ^jsonflags.WhitespaceFlags), + Values: uint64(0), + }, +} + +// DefaultOptionsV1 is the set of all options that define default v1 behavior. +var DefaultOptionsV1 = Struct{ + Flags: jsonflags.Flags{ + Presence: uint64(jsonflags.AllFlags & ^jsonflags.WhitespaceFlags), + Values: uint64(jsonflags.DefaultV1Flags), + }, +} + +func (*Struct) JSONOptions(internal.NotForPublicUse) {} + +// GetUnknownOption is injected by the "json" package to handle Options +// declared in that package so that "jsonopts" can handle them. +var GetUnknownOption = func(Struct, Options) (any, bool) { panic("unknown option") } + +func GetOption[T any](opts Options, setter func(T) Options) (T, bool) { + // Collapse the options to *Struct to simplify lookup. + structOpts, ok := opts.(*Struct) + if !ok { + var structOpts2 Struct + structOpts2.Join(opts) + structOpts = &structOpts2 + } + + // Lookup the option based on the return value of the setter. + var zero T + switch opt := setter(zero).(type) { + case jsonflags.Bools: + v := structOpts.Flags.Get(opt) + ok := structOpts.Flags.Has(opt) + return any(v).(T), ok + case Indent: + if !structOpts.Flags.Has(jsonflags.Indent) { + return zero, false + } + return any(structOpts.Indent).(T), true + case IndentPrefix: + if !structOpts.Flags.Has(jsonflags.IndentPrefix) { + return zero, false + } + return any(structOpts.IndentPrefix).(T), true + case ByteLimit: + if !structOpts.Flags.Has(jsonflags.ByteLimit) { + return zero, false + } + return any(structOpts.ByteLimit).(T), true + case DepthLimit: + if !structOpts.Flags.Has(jsonflags.DepthLimit) { + return zero, false + } + return any(structOpts.DepthLimit).(T), true + default: + v, ok := GetUnknownOption(*structOpts, opt) + return v.(T), ok + } +} + +// JoinUnknownOption is injected by the "json" package to handle Options +// declared in that package so that "jsonopts" can handle them. +var JoinUnknownOption = func(Struct, Options) Struct { panic("unknown option") } + +func (dst *Struct) Join(srcs ...Options) { + dst.join(false, srcs...) +} + +func (dst *Struct) JoinWithoutCoderOptions(srcs ...Options) { + dst.join(true, srcs...) +} + +func (dst *Struct) join(excludeCoderOptions bool, srcs ...Options) { + for _, src := range srcs { + switch src := src.(type) { + case nil: + continue + case jsonflags.Bools: + if excludeCoderOptions { + src &= ^jsonflags.AllCoderFlags + } + dst.Flags.Set(src) + case Indent: + if excludeCoderOptions { + continue + } + dst.Flags.Set(jsonflags.Multiline | jsonflags.Indent | 1) + dst.Indent = string(src) + case IndentPrefix: + if excludeCoderOptions { + continue + } + dst.Flags.Set(jsonflags.Multiline | jsonflags.IndentPrefix | 1) + dst.IndentPrefix = string(src) + case ByteLimit: + if excludeCoderOptions { + continue + } + dst.Flags.Set(jsonflags.ByteLimit | 1) + dst.ByteLimit = int64(src) + case DepthLimit: + if excludeCoderOptions { + continue + } + dst.Flags.Set(jsonflags.DepthLimit | 1) + dst.DepthLimit = int(src) + case *Struct: + srcFlags := src.Flags // shallow copy the flags + if excludeCoderOptions { + srcFlags.Clear(jsonflags.AllCoderFlags) + } + dst.Flags.Join(srcFlags) + if srcFlags.Has(jsonflags.NonBooleanFlags) { + if srcFlags.Has(jsonflags.Indent) { + dst.Indent = src.Indent + } + if srcFlags.Has(jsonflags.IndentPrefix) { + dst.IndentPrefix = src.IndentPrefix + } + if srcFlags.Has(jsonflags.ByteLimit) { + dst.ByteLimit = src.ByteLimit + } + if srcFlags.Has(jsonflags.DepthLimit) { + dst.DepthLimit = src.DepthLimit + } + if srcFlags.Has(jsonflags.Marshalers) { + dst.Marshalers = src.Marshalers + } + if srcFlags.Has(jsonflags.Unmarshalers) { + dst.Unmarshalers = src.Unmarshalers + } + } + default: + *dst = JoinUnknownOption(*dst, src) + } + } +} + +type ( + Indent string // jsontext.WithIndent + IndentPrefix string // jsontext.WithIndentPrefix + ByteLimit int64 // jsontext.WithByteLimit + DepthLimit int // jsontext.WithDepthLimit + // type for jsonflags.Marshalers declared in "json" package + // type for jsonflags.Unmarshalers declared in "json" package +) + +func (Indent) JSONOptions(internal.NotForPublicUse) {} +func (IndentPrefix) JSONOptions(internal.NotForPublicUse) {} +func (ByteLimit) JSONOptions(internal.NotForPublicUse) {} +func (DepthLimit) JSONOptions(internal.NotForPublicUse) {} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/decode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/decode.go new file mode 100644 index 000000000..02787719c --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/decode.go @@ -0,0 +1,627 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonwire + +import ( + "io" + "math" + "slices" + "strconv" + "unicode/utf16" + "unicode/utf8" +) + +type ValueFlags uint + +const ( + _ ValueFlags = (1 << iota) / 2 // powers of two starting with zero + + stringNonVerbatim // string cannot be naively treated as valid UTF-8 + stringNonCanonical // string not formatted according to RFC 8785, section 3.2.2.2. + // TODO: Track whether a number is a non-integer? +) + +func (f *ValueFlags) Join(f2 ValueFlags) { *f |= f2 } +func (f ValueFlags) IsVerbatim() bool { return f&stringNonVerbatim == 0 } +func (f ValueFlags) IsCanonical() bool { return f&stringNonCanonical == 0 } + +// ConsumeWhitespace consumes leading JSON whitespace per RFC 7159, section 2. +func ConsumeWhitespace(b []byte) (n int) { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + for len(b) > n && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { + n++ + } + return n +} + +// ConsumeNull consumes the next JSON null literal per RFC 7159, section 3. +// It returns 0 if it is invalid, in which case consumeLiteral should be used. +func ConsumeNull(b []byte) int { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + const literal = "null" + if len(b) >= len(literal) && string(b[:len(literal)]) == literal { + return len(literal) + } + return 0 +} + +// ConsumeFalse consumes the next JSON false literal per RFC 7159, section 3. +// It returns 0 if it is invalid, in which case consumeLiteral should be used. +func ConsumeFalse(b []byte) int { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + const literal = "false" + if len(b) >= len(literal) && string(b[:len(literal)]) == literal { + return len(literal) + } + return 0 +} + +// ConsumeTrue consumes the next JSON true literal per RFC 7159, section 3. +// It returns 0 if it is invalid, in which case consumeLiteral should be used. +func ConsumeTrue(b []byte) int { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + const literal = "true" + if len(b) >= len(literal) && string(b[:len(literal)]) == literal { + return len(literal) + } + return 0 +} + +// ConsumeLiteral consumes the next JSON literal per RFC 7159, section 3. +// If the input appears truncated, it returns io.ErrUnexpectedEOF. +func ConsumeLiteral(b []byte, lit string) (n int, err error) { + for i := 0; i < len(b) && i < len(lit); i++ { + if b[i] != lit[i] { + return i, NewInvalidCharacterError(b[i:], "in literal "+lit+" (expecting "+strconv.QuoteRune(rune(lit[i]))+")") + } + } + if len(b) < len(lit) { + return len(b), io.ErrUnexpectedEOF + } + return len(lit), nil +} + +// ConsumeSimpleString consumes the next JSON string per RFC 7159, section 7 +// but is limited to the grammar for an ASCII string without escape sequences. +// It returns 0 if it is invalid or more complicated than a simple string, +// in which case consumeString should be called. +// +// It rejects '<', '>', and '&' for compatibility reasons since these were +// always escaped in the v1 implementation. Thus, if this function reports +// non-zero then we know that the string would be encoded the same way +// under both v1 or v2 escape semantics. +func ConsumeSimpleString(b []byte) (n int) { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + if len(b) > 0 && b[0] == '"' { + n++ + for len(b) > n && b[n] < utf8.RuneSelf && escapeASCII[b[n]] == 0 { + n++ + } + if uint(len(b)) > uint(n) && b[n] == '"' { + n++ + return n + } + } + return 0 +} + +// ConsumeString consumes the next JSON string per RFC 7159, section 7. +// If validateUTF8 is false, then this allows the presence of invalid UTF-8 +// characters within the string itself. +// It reports the number of bytes consumed and whether an error was encountered. +// If the input appears truncated, it returns io.ErrUnexpectedEOF. +func ConsumeString(flags *ValueFlags, b []byte, validateUTF8 bool) (n int, err error) { + return ConsumeStringResumable(flags, b, 0, validateUTF8) +} + +// ConsumeStringResumable is identical to consumeString but supports resuming +// from a previous call that returned io.ErrUnexpectedEOF. +func ConsumeStringResumable(flags *ValueFlags, b []byte, resumeOffset int, validateUTF8 bool) (n int, err error) { + // Consume the leading double quote. + switch { + case resumeOffset > 0: + n = resumeOffset // already handled the leading quote + case uint(len(b)) == 0: + return n, io.ErrUnexpectedEOF + case b[0] == '"': + n++ + default: + return n, NewInvalidCharacterError(b[n:], `at start of string (expecting '"')`) + } + + // Consume every character in the string. + for uint(len(b)) > uint(n) { + // Optimize for long sequences of unescaped characters. + noEscape := func(c byte) bool { + return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"' + } + for uint(len(b)) > uint(n) && noEscape(b[n]) { + n++ + } + if uint(len(b)) <= uint(n) { + return n, io.ErrUnexpectedEOF + } + + // Check for terminating double quote. + if b[n] == '"' { + n++ + return n, nil + } + + switch r, rn := utf8.DecodeRune(b[n:]); { + // Handle UTF-8 encoded byte sequence. + // Due to specialized handling of ASCII above, we know that + // all normal sequences at this point must be 2 bytes or larger. + case rn > 1: + n += rn + // Handle escape sequence. + case r == '\\': + flags.Join(stringNonVerbatim) + resumeOffset = n + if uint(len(b)) < uint(n+2) { + return resumeOffset, io.ErrUnexpectedEOF + } + switch r := b[n+1]; r { + case '/': + // Forward slash is the only character with 3 representations. + // Per RFC 8785, section 3.2.2.2., this must not be escaped. + flags.Join(stringNonCanonical) + n += 2 + case '"', '\\', 'b', 'f', 'n', 'r', 't': + n += 2 + case 'u': + if uint(len(b)) < uint(n+6) { + if hasEscapedUTF16Prefix(b[n:], false) { + return resumeOffset, io.ErrUnexpectedEOF + } + flags.Join(stringNonCanonical) + return n, NewInvalidEscapeSequenceError(b[n:]) + } + v1, ok := parseHexUint16(b[n+2 : n+6]) + if !ok { + flags.Join(stringNonCanonical) + return n, NewInvalidEscapeSequenceError(b[n : n+6]) + } + // Only certain control characters can use the \uFFFF notation + // for canonical formatting (per RFC 8785, section 3.2.2.2.). + switch v1 { + // \uFFFF notation not permitted for these characters. + case '\b', '\f', '\n', '\r', '\t': + flags.Join(stringNonCanonical) + default: + // \uFFFF notation only permitted for control characters. + if v1 >= ' ' { + flags.Join(stringNonCanonical) + } else { + // \uFFFF notation must be lower case. + for _, c := range b[n+2 : n+6] { + if 'A' <= c && c <= 'F' { + flags.Join(stringNonCanonical) + } + } + } + } + n += 6 + + r := rune(v1) + if validateUTF8 && utf16.IsSurrogate(r) { + if uint(len(b)) < uint(n+6) { + if hasEscapedUTF16Prefix(b[n:], true) { + return resumeOffset, io.ErrUnexpectedEOF + } + flags.Join(stringNonCanonical) + return n - 6, NewInvalidEscapeSequenceError(b[n-6:]) + } else if v2, ok := parseHexUint16(b[n+2 : n+6]); b[n] != '\\' || b[n+1] != 'u' || !ok { + flags.Join(stringNonCanonical) + return n - 6, NewInvalidEscapeSequenceError(b[n-6 : n+6]) + } else if r = utf16.DecodeRune(rune(v1), rune(v2)); r == utf8.RuneError { + flags.Join(stringNonCanonical) + return n - 6, NewInvalidEscapeSequenceError(b[n-6 : n+6]) + } else { + n += 6 + } + } + default: + flags.Join(stringNonCanonical) + return n, NewInvalidEscapeSequenceError(b[n : n+2]) + } + // Handle invalid UTF-8. + case r == utf8.RuneError: + if !utf8.FullRune(b[n:]) { + return n, io.ErrUnexpectedEOF + } + flags.Join(stringNonVerbatim | stringNonCanonical) + if validateUTF8 { + return n, ErrInvalidUTF8 + } + n++ + // Handle invalid control characters. + case r < ' ': + flags.Join(stringNonVerbatim | stringNonCanonical) + return n, NewInvalidCharacterError(b[n:], "in string (expecting non-control character)") + default: + panic("BUG: unhandled character " + QuoteRune(b[n:])) + } + } + return n, io.ErrUnexpectedEOF +} + +// AppendUnquote appends the unescaped form of a JSON string in src to dst. +// Any invalid UTF-8 within the string will be replaced with utf8.RuneError, +// but the error will be specified as having encountered such an error. +// The input must be an entire JSON string with no surrounding whitespace. +func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) (v []byte, err error) { + dst = slices.Grow(dst, len(src)) + + // Consume the leading double quote. + var i, n int + switch { + case uint(len(src)) == 0: + return dst, io.ErrUnexpectedEOF + case src[0] == '"': + i, n = 1, 1 + default: + return dst, NewInvalidCharacterError(src, `at start of string (expecting '"')`) + } + + // Consume every character in the string. + for uint(len(src)) > uint(n) { + // Optimize for long sequences of unescaped characters. + noEscape := func(c byte) bool { + return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"' + } + for uint(len(src)) > uint(n) && noEscape(src[n]) { + n++ + } + if uint(len(src)) <= uint(n) { + dst = append(dst, src[i:n]...) + return dst, io.ErrUnexpectedEOF + } + + // Check for terminating double quote. + if src[n] == '"' { + dst = append(dst, src[i:n]...) + n++ + if n < len(src) { + err = NewInvalidCharacterError(src[n:], "after string value") + } + return dst, err + } + + switch r, rn := utf8.DecodeRuneInString(string(truncateMaxUTF8(src[n:]))); { + // Handle UTF-8 encoded byte sequence. + // Due to specialized handling of ASCII above, we know that + // all normal sequences at this point must be 2 bytes or larger. + case rn > 1: + n += rn + // Handle escape sequence. + case r == '\\': + dst = append(dst, src[i:n]...) + + // Handle escape sequence. + if uint(len(src)) < uint(n+2) { + return dst, io.ErrUnexpectedEOF + } + switch r := src[n+1]; r { + case '"', '\\', '/': + dst = append(dst, r) + n += 2 + case 'b': + dst = append(dst, '\b') + n += 2 + case 'f': + dst = append(dst, '\f') + n += 2 + case 'n': + dst = append(dst, '\n') + n += 2 + case 'r': + dst = append(dst, '\r') + n += 2 + case 't': + dst = append(dst, '\t') + n += 2 + case 'u': + if uint(len(src)) < uint(n+6) { + if hasEscapedUTF16Prefix(src[n:], false) { + return dst, io.ErrUnexpectedEOF + } + return dst, NewInvalidEscapeSequenceError(src[n:]) + } + v1, ok := parseHexUint16(src[n+2 : n+6]) + if !ok { + return dst, NewInvalidEscapeSequenceError(src[n : n+6]) + } + n += 6 + + // Check whether this is a surrogate half. + r := rune(v1) + if utf16.IsSurrogate(r) { + r = utf8.RuneError // assume failure unless the following succeeds + if uint(len(src)) < uint(n+6) { + if hasEscapedUTF16Prefix(src[n:], true) { + return utf8.AppendRune(dst, r), io.ErrUnexpectedEOF + } + err = NewInvalidEscapeSequenceError(src[n-6:]) + } else if v2, ok := parseHexUint16(src[n+2 : n+6]); src[n] != '\\' || src[n+1] != 'u' || !ok { + err = NewInvalidEscapeSequenceError(src[n-6 : n+6]) + } else if r = utf16.DecodeRune(rune(v1), rune(v2)); r == utf8.RuneError { + err = NewInvalidEscapeSequenceError(src[n-6 : n+6]) + } else { + n += 6 + } + } + + dst = utf8.AppendRune(dst, r) + default: + return dst, NewInvalidEscapeSequenceError(src[n : n+2]) + } + i = n + // Handle invalid UTF-8. + case r == utf8.RuneError: + dst = append(dst, src[i:n]...) + if !utf8.FullRuneInString(string(truncateMaxUTF8(src[n:]))) { + return dst, io.ErrUnexpectedEOF + } + // NOTE: An unescaped string may be longer than the escaped string + // because invalid UTF-8 bytes are being replaced. + dst = append(dst, "\uFFFD"...) + n += rn + i = n + err = ErrInvalidUTF8 + // Handle invalid control characters. + case r < ' ': + dst = append(dst, src[i:n]...) + return dst, NewInvalidCharacterError(src[n:], "in string (expecting non-control character)") + default: + panic("BUG: unhandled character " + QuoteRune(src[n:])) + } + } + dst = append(dst, src[i:n]...) + return dst, io.ErrUnexpectedEOF +} + +// hasEscapedUTF16Prefix reports whether b is possibly +// the truncated prefix of a \uFFFF escape sequence. +func hasEscapedUTF16Prefix[Bytes ~[]byte | ~string](b Bytes, lowerSurrogateHalf bool) bool { + for i := range len(b) { + switch c := b[i]; { + case i == 0 && c != '\\': + return false + case i == 1 && c != 'u': + return false + case i == 2 && lowerSurrogateHalf && c != 'd' && c != 'D': + return false // not within ['\uDC00':'\uDFFF'] + case i == 3 && lowerSurrogateHalf && !('c' <= c && c <= 'f') && !('C' <= c && c <= 'F'): + return false // not within ['\uDC00':'\uDFFF'] + case i >= 2 && i < 6 && !('0' <= c && c <= '9') && !('a' <= c && c <= 'f') && !('A' <= c && c <= 'F'): + return false + } + } + return true +} + +// UnquoteMayCopy returns the unescaped form of b. +// If there are no escaped characters, the output is simply a subslice of +// the input with the surrounding quotes removed. +// Otherwise, a new buffer is allocated for the output. +// It assumes the input is valid. +func UnquoteMayCopy(b []byte, isVerbatim bool) []byte { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + if isVerbatim { + return b[len(`"`) : len(b)-len(`"`)] + } + b, _ = AppendUnquote(nil, b) + return b +} + +// ConsumeSimpleNumber consumes the next JSON number per RFC 7159, section 6 +// but is limited to the grammar for a positive integer. +// It returns 0 if it is invalid or more complicated than a simple integer, +// in which case consumeNumber should be called. +func ConsumeSimpleNumber(b []byte) (n int) { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + if len(b) > 0 { + if b[0] == '0' { + n++ + } else if '1' <= b[0] && b[0] <= '9' { + n++ + for len(b) > n && ('0' <= b[n] && b[n] <= '9') { + n++ + } + } else { + return 0 + } + if uint(len(b)) <= uint(n) || (b[n] != '.' && b[n] != 'e' && b[n] != 'E') { + return n + } + } + return 0 +} + +type ConsumeNumberState uint + +const ( + consumeNumberInit ConsumeNumberState = iota + beforeIntegerDigits + withinIntegerDigits + beforeFractionalDigits + withinFractionalDigits + beforeExponentDigits + withinExponentDigits +) + +// ConsumeNumber consumes the next JSON number per RFC 7159, section 6. +// It reports the number of bytes consumed and whether an error was encountered. +// If the input appears truncated, it returns io.ErrUnexpectedEOF. +// +// Note that JSON numbers are not self-terminating. +// If the entire input is consumed, then the caller needs to consider whether +// there may be subsequent unread data that may still be part of this number. +func ConsumeNumber(b []byte) (n int, err error) { + n, _, err = ConsumeNumberResumable(b, 0, consumeNumberInit) + return n, err +} + +// ConsumeNumberResumable is identical to consumeNumber but supports resuming +// from a previous call that returned io.ErrUnexpectedEOF. +func ConsumeNumberResumable(b []byte, resumeOffset int, state ConsumeNumberState) (n int, _ ConsumeNumberState, err error) { + // Jump to the right state when resuming from a partial consumption. + n = resumeOffset + if state > consumeNumberInit { + switch state { + case withinIntegerDigits, withinFractionalDigits, withinExponentDigits: + // Consume leading digits. + for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') { + n++ + } + if uint(len(b)) <= uint(n) { + return n, state, nil // still within the same state + } + state++ // switches "withinX" to "beforeY" where Y is the state after X + } + switch state { + case beforeIntegerDigits: + goto beforeInteger + case beforeFractionalDigits: + goto beforeFractional + case beforeExponentDigits: + goto beforeExponent + default: + return n, state, nil + } + } + + // Consume required integer component (with optional minus sign). +beforeInteger: + resumeOffset = n + if uint(len(b)) > 0 && b[0] == '-' { + n++ + } + switch { + case uint(len(b)) <= uint(n): + return resumeOffset, beforeIntegerDigits, io.ErrUnexpectedEOF + case b[n] == '0': + n++ + state = beforeFractionalDigits + case '1' <= b[n] && b[n] <= '9': + n++ + for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') { + n++ + } + state = withinIntegerDigits + default: + return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)") + } + + // Consume optional fractional component. +beforeFractional: + if uint(len(b)) > uint(n) && b[n] == '.' { + resumeOffset = n + n++ + switch { + case uint(len(b)) <= uint(n): + return resumeOffset, beforeFractionalDigits, io.ErrUnexpectedEOF + case '0' <= b[n] && b[n] <= '9': + n++ + default: + return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)") + } + for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') { + n++ + } + state = withinFractionalDigits + } + + // Consume optional exponent component. +beforeExponent: + if uint(len(b)) > uint(n) && (b[n] == 'e' || b[n] == 'E') { + resumeOffset = n + n++ + if uint(len(b)) > uint(n) && (b[n] == '-' || b[n] == '+') { + n++ + } + switch { + case uint(len(b)) <= uint(n): + return resumeOffset, beforeExponentDigits, io.ErrUnexpectedEOF + case '0' <= b[n] && b[n] <= '9': + n++ + default: + return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)") + } + for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') { + n++ + } + state = withinExponentDigits + } + + return n, state, nil +} + +// parseHexUint16 is similar to strconv.ParseUint, +// but operates directly on []byte and is optimized for base-16. +// See https://go.dev/issue/42429. +func parseHexUint16[Bytes ~[]byte | ~string](b Bytes) (v uint16, ok bool) { + if len(b) != 4 { + return 0, false + } + for i := range 4 { + c := b[i] + switch { + case '0' <= c && c <= '9': + c = c - '0' + case 'a' <= c && c <= 'f': + c = 10 + c - 'a' + case 'A' <= c && c <= 'F': + c = 10 + c - 'A' + default: + return 0, false + } + v = v*16 + uint16(c) + } + return v, true +} + +// ParseUint parses b as a decimal unsigned integer according to +// a strict subset of the JSON number grammar, returning the value if valid. +// It returns (0, false) if there is a syntax error and +// returns (math.MaxUint64, false) if there is an overflow. +func ParseUint(b []byte) (v uint64, ok bool) { + const unsafeWidth = 20 // len(fmt.Sprint(uint64(math.MaxUint64))) + var n int + for ; len(b) > n && ('0' <= b[n] && b[n] <= '9'); n++ { + v = 10*v + uint64(b[n]-'0') + } + switch { + case n == 0 || len(b) != n || (b[0] == '0' && string(b) != "0"): + return 0, false + case n >= unsafeWidth && (b[0] != '1' || v < 1e19 || n > unsafeWidth): + return math.MaxUint64, false + } + return v, true +} + +// ParseFloat parses a floating point number according to the Go float grammar. +// Note that the JSON number grammar is a strict subset. +// +// If the number overflows the finite representation of a float, +// then we return MaxFloat since any finite value will always be infinitely +// more accurate at representing another finite value than an infinite value. +func ParseFloat(b []byte, bits int) (v float64, ok bool) { + fv, err := strconv.ParseFloat(string(b), bits) + if math.IsInf(fv, 0) { + switch { + case bits == 32 && math.IsInf(fv, +1): + fv = +math.MaxFloat32 + case bits == 64 && math.IsInf(fv, +1): + fv = +math.MaxFloat64 + case bits == 32 && math.IsInf(fv, -1): + fv = -math.MaxFloat32 + case bits == 64 && math.IsInf(fv, -1): + fv = -math.MaxFloat64 + } + } + return fv, err == nil +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/encode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/encode.go new file mode 100644 index 000000000..35b238a2e --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/encode.go @@ -0,0 +1,288 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonwire + +import ( + "math" + "slices" + "strconv" + "unicode/utf16" + "unicode/utf8" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" +) + +// escapeASCII reports whether the ASCII character needs to be escaped. +// It conservatively assumes EscapeForHTML. +var escapeASCII = [...]uint8{ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // escape control characters + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // escape control characters + 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // escape '"' and '&' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, // escape '<' and '>' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // escape '\\' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} + +// NeedEscape reports whether src needs escaping of any characters. +// It conservatively assumes EscapeForHTML and EscapeForJS. +// It reports true for inputs with invalid UTF-8. +func NeedEscape[Bytes ~[]byte | ~string](src Bytes) bool { + var i int + for uint(len(src)) > uint(i) { + if c := src[i]; c < utf8.RuneSelf { + if escapeASCII[c] > 0 { + return true + } + i++ + } else { + r, rn := utf8.DecodeRuneInString(string(truncateMaxUTF8(src[i:]))) + if r == utf8.RuneError || r == '\u2028' || r == '\u2029' { + return true + } + i += rn + } + } + return false +} + +// AppendQuote appends src to dst as a JSON string per RFC 7159, section 7. +// +// It takes in flags and respects the following: +// - EscapeForHTML escapes '<', '>', and '&'. +// - EscapeForJS escapes '\u2028' and '\u2029'. +// - AllowInvalidUTF8 avoids reporting an error for invalid UTF-8. +// +// Regardless of whether AllowInvalidUTF8 is specified, +// invalid bytes are replaced with the Unicode replacement character ('\ufffd'). +// If no escape flags are set, then the shortest representable form is used, +// which is also the canonical form for strings (RFC 8785, section 3.2.2.2). +func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes, flags *jsonflags.Flags) ([]byte, error) { + var i, n int + var hasInvalidUTF8 bool + dst = slices.Grow(dst, len(`"`)+len(src)+len(`"`)) + dst = append(dst, '"') + for uint(len(src)) > uint(n) { + if c := src[n]; c < utf8.RuneSelf { + // Handle single-byte ASCII. + n++ + if escapeASCII[c] == 0 { + continue // no escaping possibly needed + } + // Handle escaping of single-byte ASCII. + if !(c == '<' || c == '>' || c == '&') || flags.Get(jsonflags.EscapeForHTML) { + dst = append(dst, src[i:n-1]...) + dst = appendEscapedASCII(dst, c) + i = n + } + } else { + // Handle multi-byte Unicode. + r, rn := utf8.DecodeRuneInString(string(truncateMaxUTF8(src[n:]))) + n += rn + if r != utf8.RuneError && r != '\u2028' && r != '\u2029' { + continue // no escaping possibly needed + } + // Handle escaping of multi-byte Unicode. + switch { + case isInvalidUTF8(r, rn): + hasInvalidUTF8 = true + dst = append(dst, src[i:n-rn]...) + dst = append(dst, "\ufffd"...) + i = n + case (r == '\u2028' || r == '\u2029') && flags.Get(jsonflags.EscapeForJS): + dst = append(dst, src[i:n-rn]...) + dst = appendEscapedUnicode(dst, r) + i = n + } + } + } + dst = append(dst, src[i:n]...) + dst = append(dst, '"') + if hasInvalidUTF8 && !flags.Get(jsonflags.AllowInvalidUTF8) { + return dst, ErrInvalidUTF8 + } + return dst, nil +} + +func appendEscapedASCII(dst []byte, c byte) []byte { + switch c { + case '"', '\\': + dst = append(dst, '\\', c) + case '\b': + dst = append(dst, "\\b"...) + case '\f': + dst = append(dst, "\\f"...) + case '\n': + dst = append(dst, "\\n"...) + case '\r': + dst = append(dst, "\\r"...) + case '\t': + dst = append(dst, "\\t"...) + default: + dst = appendEscapedUTF16(dst, uint16(c)) + } + return dst +} + +func appendEscapedUnicode(dst []byte, r rune) []byte { + if r1, r2 := utf16.EncodeRune(r); r1 != '\ufffd' && r2 != '\ufffd' { + dst = appendEscapedUTF16(dst, uint16(r1)) + dst = appendEscapedUTF16(dst, uint16(r2)) + } else { + dst = appendEscapedUTF16(dst, uint16(r)) + } + return dst +} + +func appendEscapedUTF16(dst []byte, x uint16) []byte { + const hex = "0123456789abcdef" + return append(dst, '\\', 'u', hex[(x>>12)&0xf], hex[(x>>8)&0xf], hex[(x>>4)&0xf], hex[(x>>0)&0xf]) +} + +// ReformatString consumes a JSON string from src and appends it to dst, +// reformatting it if necessary according to the specified flags. +// It returns the appended output and the number of consumed input bytes. +func ReformatString(dst, src []byte, flags *jsonflags.Flags) ([]byte, int, error) { + // TODO: Should this update ValueFlags as input? + var valFlags ValueFlags + n, err := ConsumeString(&valFlags, src, !flags.Get(jsonflags.AllowInvalidUTF8)) + if err != nil { + return dst, n, err + } + + // If the output requires no special escapes, and the input + // is already in canonical form or should be preserved verbatim, + // then directly copy the input to the output. + if !flags.Get(jsonflags.AnyEscape) && + (valFlags.IsCanonical() || flags.Get(jsonflags.PreserveRawStrings)) { + dst = append(dst, src[:n]...) // copy the string verbatim + return dst, n, nil + } + + // Under [jsonflags.PreserveRawStrings], any pre-escaped sequences + // remain escaped, however we still need to respect the + // [jsonflags.EscapeForHTML] and [jsonflags.EscapeForJS] options. + if flags.Get(jsonflags.PreserveRawStrings) { + var i, lastAppendIndex int + for i < n { + if c := src[i]; c < utf8.RuneSelf { + if (c == '<' || c == '>' || c == '&') && flags.Get(jsonflags.EscapeForHTML) { + dst = append(dst, src[lastAppendIndex:i]...) + dst = appendEscapedASCII(dst, c) + lastAppendIndex = i + 1 + } + i++ + } else { + r, rn := utf8.DecodeRune(truncateMaxUTF8(src[i:])) + if (r == '\u2028' || r == '\u2029') && flags.Get(jsonflags.EscapeForJS) { + dst = append(dst, src[lastAppendIndex:i]...) + dst = appendEscapedUnicode(dst, r) + lastAppendIndex = i + rn + } + i += rn + } + } + return append(dst, src[lastAppendIndex:n]...), n, nil + } + + // The input contains characters that might need escaping, + // unnecessary escape sequences, or invalid UTF-8. + // Perform a round-trip unquote and quote to properly reformat + // these sequences according the current flags. + b, _ := AppendUnquote(nil, src[:n]) + dst, _ = AppendQuote(dst, b, flags) + return dst, n, nil +} + +// AppendFloat appends src to dst as a JSON number per RFC 7159, section 6. +// It formats numbers similar to the ES6 number-to-string conversion. +// See https://go.dev/issue/14135. +// +// The output is identical to ECMA-262, 6th edition, section 7.1.12.1 and with +// RFC 8785, section 3.2.2.3 for 64-bit floating-point numbers except for -0, +// which is formatted as -0 instead of just 0. +// +// For 32-bit floating-point numbers, +// the output is a 32-bit equivalent of the algorithm. +// Note that ECMA-262 specifies no algorithm for 32-bit numbers. +func AppendFloat(dst []byte, src float64, bits int) []byte { + if bits == 32 { + src = float64(float32(src)) + } + + abs := math.Abs(src) + fmt := byte('f') + if abs != 0 { + if bits == 64 && (float64(abs) < 1e-6 || float64(abs) >= 1e21) || + bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { + fmt = 'e' + } + } + dst = strconv.AppendFloat(dst, src, fmt, -1, bits) + if fmt == 'e' { + // Clean up e-09 to e-9. + n := len(dst) + if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' { + dst[n-2] = dst[n-1] + dst = dst[:n-1] + } + } + return dst +} + +// ReformatNumber consumes a JSON string from src and appends it to dst, +// canonicalizing it if specified. +// It returns the appended output and the number of consumed input bytes. +func ReformatNumber(dst, src []byte, flags *jsonflags.Flags) ([]byte, int, error) { + n, err := ConsumeNumber(src) + if err != nil { + return dst, n, err + } + if !flags.Get(jsonflags.CanonicalizeNumbers) { + dst = append(dst, src[:n]...) // copy the number verbatim + return dst, n, nil + } + + // Identify the kind of number. + var isFloat bool + for _, c := range src[:n] { + if c == '.' || c == 'e' || c == 'E' { + isFloat = true // has fraction or exponent + break + } + } + + // Check if need to canonicalize this kind of number. + switch { + case string(src[:n]) == "-0": + break // canonicalize -0 as 0 regardless of kind + case isFloat: + if !flags.Get(jsonflags.CanonicalizeRawFloats) { + dst = append(dst, src[:n]...) // copy the number verbatim + return dst, n, nil + } + default: + // As an optimization, we can copy integer numbers below 2⁵³ verbatim + // since the canonical form is always identical. + const maxExactIntegerDigits = 16 // len(strconv.AppendUint(nil, 1<<53, 10)) + if !flags.Get(jsonflags.CanonicalizeRawInts) || n < maxExactIntegerDigits { + dst = append(dst, src[:n]...) // copy the number verbatim + return dst, n, nil + } + } + + // Parse and reformat the number (which uses a canonical format). + fv, _ := strconv.ParseFloat(string(src[:n]), 64) + switch { + case fv == 0: + fv = 0 // normalize negative zero as just zero + case math.IsInf(fv, +1): + fv = +math.MaxFloat64 + case math.IsInf(fv, -1): + fv = -math.MaxFloat64 + } + return AppendFloat(dst, fv, 64), n, nil +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/wire.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/wire.go new file mode 100644 index 000000000..1831a66bd --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire/wire.go @@ -0,0 +1,215 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jsonwire implements stateless functionality for handling JSON text. +package jsonwire + +import ( + "cmp" + "errors" + "strconv" + "strings" + "unicode" + "unicode/utf16" + "unicode/utf8" +) + +// TrimSuffixWhitespace trims JSON from the end of b. +func TrimSuffixWhitespace(b []byte) []byte { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + n := len(b) - 1 + for n >= 0 && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { + n-- + } + return b[:n+1] +} + +// TrimSuffixString trims a valid JSON string at the end of b. +// The behavior is undefined if there is not a valid JSON string present. +func TrimSuffixString(b []byte) []byte { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + if len(b) > 0 && b[len(b)-1] == '"' { + b = b[:len(b)-1] + } + for len(b) >= 2 && !(b[len(b)-1] == '"' && b[len(b)-2] != '\\') { + b = b[:len(b)-1] // trim all characters except an unescaped quote + } + if len(b) > 0 && b[len(b)-1] == '"' { + b = b[:len(b)-1] + } + return b +} + +// HasSuffixByte reports whether b ends with c. +func HasSuffixByte(b []byte, c byte) bool { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + return len(b) > 0 && b[len(b)-1] == c +} + +// TrimSuffixByte removes c from the end of b if it is present. +func TrimSuffixByte(b []byte, c byte) []byte { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + if len(b) > 0 && b[len(b)-1] == c { + return b[:len(b)-1] + } + return b +} + +// QuoteRune quotes the first rune in the input. +func QuoteRune[Bytes ~[]byte | ~string](b Bytes) string { + r, n := utf8.DecodeRuneInString(string(truncateMaxUTF8(b))) + if r == utf8.RuneError && n == 1 { + return `'\x` + strconv.FormatUint(uint64(b[0]), 16) + `'` + } + return strconv.QuoteRune(r) +} + +// CompareUTF16 lexicographically compares x to y according +// to the UTF-16 codepoints of the UTF-8 encoded input strings. +// This implements the ordering specified in RFC 8785, section 3.2.3. +func CompareUTF16[Bytes ~[]byte | ~string](x, y Bytes) int { + // NOTE: This is an optimized, mostly allocation-free implementation + // of CompareUTF16Simple in wire_test.go. FuzzCompareUTF16 verifies that the + // two implementations agree on the result of comparing any two strings. + isUTF16Self := func(r rune) bool { + return ('\u0000' <= r && r <= '\uD7FF') || ('\uE000' <= r && r <= '\uFFFF') + } + + for { + if len(x) == 0 || len(y) == 0 { + return cmp.Compare(len(x), len(y)) + } + + // ASCII fast-path. + if x[0] < utf8.RuneSelf || y[0] < utf8.RuneSelf { + if x[0] != y[0] { + return cmp.Compare(x[0], y[0]) + } + x, y = x[1:], y[1:] + continue + } + + // Decode next pair of runes as UTF-8. + rx, nx := utf8.DecodeRuneInString(string(truncateMaxUTF8(x))) + ry, ny := utf8.DecodeRuneInString(string(truncateMaxUTF8(y))) + + selfx := isUTF16Self(rx) + selfy := isUTF16Self(ry) + switch { + // The x rune is a single UTF-16 codepoint, while + // the y rune is a surrogate pair of UTF-16 codepoints. + case selfx && !selfy: + ry, _ = utf16.EncodeRune(ry) + // The y rune is a single UTF-16 codepoint, while + // the x rune is a surrogate pair of UTF-16 codepoints. + case selfy && !selfx: + rx, _ = utf16.EncodeRune(rx) + } + if rx != ry { + return cmp.Compare(rx, ry) + } + + // Check for invalid UTF-8, in which case, + // we just perform a byte-for-byte comparison. + if isInvalidUTF8(rx, nx) || isInvalidUTF8(ry, ny) { + if x[0] != y[0] { + return cmp.Compare(x[0], y[0]) + } + } + x, y = x[nx:], y[ny:] + } +} + +// truncateMaxUTF8 truncates b such it contains at least one rune. +// +// The utf8 package currently lacks generic variants, which complicates +// generic functions that operates on either []byte or string. +// As a hack, we always call the utf8 function operating on strings, +// but always truncate the input such that the result is identical. +// +// Example usage: +// +// utf8.DecodeRuneInString(string(truncateMaxUTF8(b))) +// +// Converting a []byte to a string is stack allocated since +// truncateMaxUTF8 guarantees that the []byte is short. +func truncateMaxUTF8[Bytes ~[]byte | ~string](b Bytes) Bytes { + // TODO(https://go.dev/issue/56948): Remove this function and + // instead directly call generic utf8 functions wherever used. + if len(b) > utf8.UTFMax { + return b[:utf8.UTFMax] + } + return b +} + +// TODO(https://go.dev/issue/70547): Use utf8.ErrInvalid instead. +var ErrInvalidUTF8 = errors.New("invalid UTF-8") + +func NewInvalidCharacterError[Bytes ~[]byte | ~string](prefix Bytes, where string) error { + what := QuoteRune(prefix) + return errors.New("invalid character " + what + " " + where) +} + +func NewInvalidEscapeSequenceError[Bytes ~[]byte | ~string](what Bytes) error { + label := "escape sequence" + if len(what) > 6 { + label = "surrogate pair" + } + needEscape := strings.IndexFunc(string(what), func(r rune) bool { + return r == '`' || r == utf8.RuneError || unicode.IsSpace(r) || !unicode.IsPrint(r) + }) >= 0 + if needEscape { + return errors.New("invalid " + label + " " + strconv.Quote(string(what)) + " in string") + } else { + return errors.New("invalid " + label + " `" + string(what) + "` in string") + } +} + +// TruncatePointer optionally truncates the JSON pointer, +// enforcing that the length roughly does not exceed n. +func TruncatePointer(s string, n int) string { + if len(s) <= n { + return s + } + i := n / 2 + j := len(s) - n/2 + + // Avoid truncating a name if there are multiple names present. + if k := strings.LastIndexByte(s[:i], '/'); k > 0 { + i = k + } + if k := strings.IndexByte(s[j:], '/'); k >= 0 { + j += k + len("/") + } + + // Avoid truncation in the middle of a UTF-8 rune. + for i > 0 && isInvalidUTF8(utf8.DecodeLastRuneInString(s[:i])) { + i-- + } + for j < len(s) && isInvalidUTF8(utf8.DecodeRuneInString(s[j:])) { + j++ + } + + // Determine the right middle fragment to use. + var middle string + switch strings.Count(s[i:j], "/") { + case 0: + middle = "…" + case 1: + middle = "…/…" + default: + middle = "…/…/…" + } + if strings.HasPrefix(s[i:j], "/") && middle != "…" { + middle = strings.TrimPrefix(middle, "…") + } + if strings.HasSuffix(s[i:j], "/") && middle != "…" { + middle = strings.TrimSuffix(middle, "…") + } + return s[:i] + middle + s[j:] +} + +func isInvalidUTF8(r rune, rn int) bool { + return r == utf8.RuneError && rn == 1 +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/decode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/decode.go new file mode 100644 index 000000000..96fd5c27c --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/decode.go @@ -0,0 +1,1177 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "bytes" + "errors" + "io" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +// NOTE: The logic for decoding is complicated by the fact that reading from +// an io.Reader into a temporary buffer means that the buffer may contain a +// truncated portion of some valid input, requiring the need to fetch more data. +// +// This file is structured in the following way: +// +// - consumeXXX functions parse an exact JSON token from a []byte. +// If the buffer appears truncated, then it returns io.ErrUnexpectedEOF. +// The consumeSimpleXXX functions are so named because they only handle +// a subset of the grammar for the JSON token being parsed. +// They do not handle the full grammar to keep these functions inlinable. +// +// - Decoder.consumeXXX methods parse the next JSON token from Decoder.buf, +// automatically fetching more input if necessary. These methods take +// a position relative to the start of Decoder.buf as an argument and +// return the end of the consumed JSON token as a position, +// also relative to the start of Decoder.buf. +// +// - In the event of an I/O errors or state machine violations, +// the implementation avoids mutating the state of Decoder +// (aside from the book-keeping needed to implement Decoder.fetch). +// For this reason, only Decoder.ReadToken and Decoder.ReadValue are +// responsible for updated Decoder.prevStart and Decoder.prevEnd. +// +// - For performance, much of the implementation uses the pattern of calling +// the inlinable consumeXXX functions first, and if more work is necessary, +// then it calls the slower Decoder.consumeXXX methods. +// TODO: Revisit this pattern if the Go compiler provides finer control +// over exactly which calls are inlined or not. + +// Decoder is a streaming decoder for raw JSON tokens and values. +// It is used to read a stream of top-level JSON values, +// each separated by optional whitespace characters. +// +// [Decoder.ReadToken] and [Decoder.ReadValue] calls may be interleaved. +// For example, the following JSON value: +// +// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} +// +// can be parsed with the following calls (ignoring errors for brevity): +// +// d.ReadToken() // { +// d.ReadToken() // "name" +// d.ReadToken() // "value" +// d.ReadValue() // "array" +// d.ReadToken() // [ +// d.ReadToken() // null +// d.ReadToken() // false +// d.ReadValue() // true +// d.ReadToken() // 3.14159 +// d.ReadToken() // ] +// d.ReadValue() // "object" +// d.ReadValue() // {"k":"v"} +// d.ReadToken() // } +// +// The above is one of many possible sequence of calls and +// may not represent the most sensible method to call for any given token/value. +// For example, it is probably more common to call [Decoder.ReadToken] to obtain a +// string token for object names. +type Decoder struct { + s decoderState +} + +// decoderState is the low-level state of Decoder. +// It has exported fields and method for use by the "json" package. +type decoderState struct { + state + decodeBuffer + jsonopts.Struct + + StringCache *[256]string // only used when unmarshaling; identical to json.stringCache +} + +// decodeBuffer is a buffer split into 4 segments: +// +// - buf[0:prevEnd] // already read portion of the buffer +// - buf[prevStart:prevEnd] // previously read value +// - buf[prevEnd:len(buf)] // unread portion of the buffer +// - buf[len(buf):cap(buf)] // unused portion of the buffer +// +// Invariants: +// +// 0 ≤ prevStart ≤ prevEnd ≤ len(buf) ≤ cap(buf) +type decodeBuffer struct { + peekPos int // non-zero if valid offset into buf for start of next token + peekErr error // implies peekPos is -1 + + buf []byte // may alias rd if it is a bytes.Buffer + prevStart int + prevEnd int + + // baseOffset is added to prevStart and prevEnd to obtain + // the absolute offset relative to the start of io.Reader stream. + baseOffset int64 + + rd io.Reader +} + +// NewDecoder constructs a new streaming decoder reading from r. +// +// If r is a [bytes.Buffer], then the decoder parses directly from the buffer +// without first copying the contents to an intermediate buffer. +// Additional writes to the buffer must not occur while the decoder is in use. +func NewDecoder(r io.Reader, opts ...Options) *Decoder { + d := new(Decoder) + d.Reset(r, opts...) + return d +} + +// Reset resets a decoder such that it is reading afresh from r and +// configured with the provided options. Reset must not be called on an +// a Decoder passed to the [encoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom] method +// or the [encoding/json/v2.UnmarshalFromFunc] function. +func (d *Decoder) Reset(r io.Reader, opts ...Options) { + switch { + case d == nil: + panic("jsontext: invalid nil Decoder") + case r == nil: + panic("jsontext: invalid nil io.Reader") + case d.s.Flags.Get(jsonflags.WithinArshalCall): + panic("jsontext: cannot reset Decoder passed to json.UnmarshalerFrom") + } + // Reuse the buffer if it does not alias a previous [bytes.Buffer]. + b := d.s.buf[:0] + if _, ok := d.s.rd.(*bytes.Buffer); ok { + b = nil + } + d.s.reset(b, r, opts...) +} + +func (d *decoderState) reset(b []byte, r io.Reader, opts ...Options) { + d.state.reset() + d.decodeBuffer = decodeBuffer{buf: b, rd: r} + opts2 := jsonopts.Struct{} // avoid mutating d.Struct in case it is part of opts + opts2.Join(opts...) + d.Struct = opts2 +} + +// Options returns the options used to construct the encoder and +// may additionally contain semantic options passed to a +// [encoding/json/v2.UnmarshalDecode] call. +// +// If operating within +// a [encoding/json/v2.UnmarshalerFrom.UnmarshalJSONFrom] method call or +// a [encoding/json/v2.UnmarshalFromFunc] function call, +// then the returned options are only valid within the call. +func (d *Decoder) Options() Options { + return &d.s.Struct +} + +var errBufferWriteAfterNext = errors.New("invalid bytes.Buffer.Write call after calling bytes.Buffer.Next") + +// fetch reads at least 1 byte from the underlying io.Reader. +// It returns io.ErrUnexpectedEOF if zero bytes were read and io.EOF was seen. +func (d *decoderState) fetch() error { + if d.rd == nil { + return io.ErrUnexpectedEOF + } + + // Inform objectNameStack that we are about to fetch new buffer content. + d.Names.copyQuotedBuffer(d.buf) + + // Specialize bytes.Buffer for better performance. + if bb, ok := d.rd.(*bytes.Buffer); ok { + switch { + case bb.Len() == 0: + return io.ErrUnexpectedEOF + case len(d.buf) == 0: + d.buf = bb.Next(bb.Len()) // "read" all data in the buffer + return nil + default: + // This only occurs if a partially filled bytes.Buffer was provided + // and more data is written to it while Decoder is reading from it. + // This practice will lead to data corruption since future writes + // may overwrite the contents of the current buffer. + // + // The user is trying to use a bytes.Buffer as a pipe, + // but a bytes.Buffer is poor implementation of a pipe, + // the purpose-built io.Pipe should be used instead. + return &ioError{action: "read", err: errBufferWriteAfterNext} + } + } + + // Allocate initial buffer if empty. + if cap(d.buf) == 0 { + d.buf = make([]byte, 0, 64) + } + + // Check whether to grow the buffer. + const maxBufferSize = 4 << 10 + const growthSizeFactor = 2 // higher value is faster + const growthRateFactor = 2 // higher value is slower + // By default, grow if below the maximum buffer size. + grow := cap(d.buf) <= maxBufferSize/growthSizeFactor + // Growing can be expensive, so only grow + // if a sufficient number of bytes have been processed. + grow = grow && int64(cap(d.buf)) < d.previousOffsetEnd()/growthRateFactor + // If prevStart==0, then fetch was called in order to fetch more data + // to finish consuming a large JSON value contiguously. + // Grow if less than 25% of the remaining capacity is available. + // Note that this may cause the input buffer to exceed maxBufferSize. + grow = grow || (d.prevStart == 0 && len(d.buf) >= 3*cap(d.buf)/4) + + if grow { + // Allocate a new buffer and copy the contents of the old buffer over. + // TODO: Provide a hard limit on the maximum internal buffer size? + buf := make([]byte, 0, cap(d.buf)*growthSizeFactor) + d.buf = append(buf, d.buf[d.prevStart:]...) + } else { + // Move unread portion of the data to the front. + n := copy(d.buf[:cap(d.buf)], d.buf[d.prevStart:]) + d.buf = d.buf[:n] + } + d.baseOffset += int64(d.prevStart) + d.prevEnd -= d.prevStart + d.prevStart = 0 + + // Read more data into the internal buffer. + for { + n, err := d.rd.Read(d.buf[len(d.buf):cap(d.buf)]) + switch { + case n > 0: + d.buf = d.buf[:len(d.buf)+n] + return nil // ignore errors if any bytes are read + case err == io.EOF: + return io.ErrUnexpectedEOF + case err != nil: + return &ioError{action: "read", err: err} + default: + continue // Read returned (0, nil) + } + } +} + +const invalidateBufferByte = '#' // invalid starting character for JSON grammar + +// invalidatePreviousRead invalidates buffers returned by Peek and Read calls +// so that the first byte is an invalid character. +// This Hyrum-proofs the API against faulty application code that assumes +// values returned by ReadValue remain valid past subsequent Read calls. +func (d *decodeBuffer) invalidatePreviousRead() { + // Avoid mutating the buffer if d.rd is nil which implies that d.buf + // is provided by the user code and may not expect mutations. + isBytesBuffer := func(r io.Reader) bool { + _, ok := r.(*bytes.Buffer) + return ok + } + if d.rd != nil && !isBytesBuffer(d.rd) && d.prevStart < d.prevEnd && uint(d.prevStart) < uint(len(d.buf)) { + d.buf[d.prevStart] = invalidateBufferByte + d.prevStart = d.prevEnd + } +} + +// needMore reports whether there are no more unread bytes. +func (d *decodeBuffer) needMore(pos int) bool { + // NOTE: The arguments and logic are kept simple to keep this inlinable. + return pos == len(d.buf) +} + +func (d *decodeBuffer) offsetAt(pos int) int64 { return d.baseOffset + int64(pos) } +func (d *decodeBuffer) previousOffsetStart() int64 { return d.baseOffset + int64(d.prevStart) } +func (d *decodeBuffer) previousOffsetEnd() int64 { return d.baseOffset + int64(d.prevEnd) } +func (d *decodeBuffer) previousBuffer() []byte { return d.buf[d.prevStart:d.prevEnd] } +func (d *decodeBuffer) unreadBuffer() []byte { return d.buf[d.prevEnd:len(d.buf)] } + +// PreviousTokenOrValue returns the previously read token or value +// unless it has been invalidated by a call to PeekKind. +// If a token is just a delimiter, then this returns a 1-byte buffer. +// This method is used for error reporting at the semantic layer. +func (d *decodeBuffer) PreviousTokenOrValue() []byte { + b := d.previousBuffer() + // If peek was called, then the previous token or buffer is invalidated. + if d.peekPos > 0 || len(b) > 0 && b[0] == invalidateBufferByte { + return nil + } + // ReadToken does not preserve the buffer for null, bools, or delimiters. + // Manually re-construct that buffer. + if len(b) == 0 { + b = d.buf[:d.prevEnd] // entirety of the previous buffer + for _, tok := range []string{"null", "false", "true", "{", "}", "[", "]"} { + if len(b) >= len(tok) && string(b[len(b)-len(tok):]) == tok { + return b[len(b)-len(tok):] + } + } + } + return b +} + +// PeekKind retrieves the next token kind, but does not advance the read offset. +// +// It returns 0 if an error occurs. Any such error is cached until +// the next read call and it is the caller's responsibility to eventually +// follow up a PeekKind call with a read call. +func (d *Decoder) PeekKind() Kind { + return d.s.PeekKind() +} +func (d *decoderState) PeekKind() Kind { + // Check whether we have a cached peek result. + if d.peekPos > 0 { + return Kind(d.buf[d.peekPos]).normalize() + } + + var err error + d.invalidatePreviousRead() + pos := d.prevEnd + + // Consume leading whitespace. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { + err = io.EOF // EOF possibly if no Tokens present after top-level value + } + d.peekPos, d.peekErr = -1, wrapSyntacticError(d, err, pos, 0) + return invalidKind + } + } + + // Consume colon or comma. + var delim byte + if c := d.buf[pos]; c == ':' || c == ',' { + delim = c + pos += 1 + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + err = wrapSyntacticError(d, err, pos, 0) + d.peekPos, d.peekErr = -1, d.checkDelimBeforeIOError(delim, err) + return invalidKind + } + } + } + next := Kind(d.buf[pos]).normalize() + if d.Tokens.needDelim(next) != delim { + d.peekPos, d.peekErr = -1, d.checkDelim(delim, next) + return invalidKind + } + + // This may set peekPos to zero, which is indistinguishable from + // the uninitialized state. While a small hit to performance, it is correct + // since ReadValue and ReadToken will disregard the cached result and + // recompute the next kind. + d.peekPos, d.peekErr = pos, nil + return next +} + +// checkDelimBeforeIOError checks whether the delim is even valid +// before returning an IO error, which occurs after the delim. +func (d *decoderState) checkDelimBeforeIOError(delim byte, err error) error { + // Since an IO error occurred, we do not know what the next kind is. + // However, knowing the next kind is necessary to validate + // whether the current delim is at least potentially valid. + // Since a JSON string is always valid as the next token, + // conservatively assume that is the next kind for validation. + const next = Kind('"') + if d.Tokens.needDelim(next) != delim { + err = d.checkDelim(delim, next) + } + return err +} + +// CountNextDelimWhitespace counts the number of upcoming bytes of +// delimiter or whitespace characters. +// This method is used for error reporting at the semantic layer. +func (d *decoderState) CountNextDelimWhitespace() int { + d.PeekKind() // populate unreadBuffer + return len(d.unreadBuffer()) - len(bytes.TrimLeft(d.unreadBuffer(), ",: \n\r\t")) +} + +// checkDelim checks whether delim is valid for the given next kind. +func (d *decoderState) checkDelim(delim byte, next Kind) error { + where := "at start of value" + switch d.Tokens.needDelim(next) { + case delim: + return nil + case ':': + where = "after object name (expecting ':')" + case ',': + if d.Tokens.Last.isObject() { + where = "after object value (expecting ',' or '}')" + } else { + where = "after array element (expecting ',' or ']')" + } + } + pos := d.prevEnd // restore position to right after leading whitespace + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + err := jsonwire.NewInvalidCharacterError(d.buf[pos:], where) + return wrapSyntacticError(d, err, pos, 0) +} + +// SkipValue is semantically equivalent to calling [Decoder.ReadValue] and discarding +// the result except that memory is not wasted trying to hold the entire result. +func (d *Decoder) SkipValue() error { + return d.s.SkipValue() +} +func (d *decoderState) SkipValue() error { + switch d.PeekKind() { + case '{', '[': + // For JSON objects and arrays, keep skipping all tokens + // until the depth matches the starting depth. + depth := d.Tokens.Depth() + for { + if _, err := d.ReadToken(); err != nil { + return err + } + if depth >= d.Tokens.Depth() { + return nil + } + } + default: + // Trying to skip a value when the next token is a '}' or ']' + // will result in an error being returned here. + var flags jsonwire.ValueFlags + if _, err := d.ReadValue(&flags); err != nil { + return err + } + return nil + } +} + +// SkipValueRemainder skips the remainder of a value +// after reading a '{' or '[' token. +func (d *decoderState) SkipValueRemainder() error { + if d.Tokens.Depth()-1 > 0 && d.Tokens.Last.Length() == 0 { + for n := d.Tokens.Depth(); d.Tokens.Depth() >= n; { + if _, err := d.ReadToken(); err != nil { + return err + } + } + } + return nil +} + +// SkipUntil skips all tokens until the state machine +// is at or past the specified depth and length. +func (d *decoderState) SkipUntil(depth int, length int64) error { + for d.Tokens.Depth() > depth || (d.Tokens.Depth() == depth && d.Tokens.Last.Length() < length) { + if _, err := d.ReadToken(); err != nil { + return err + } + } + return nil +} + +// ReadToken reads the next [Token], advancing the read offset. +// The returned token is only valid until the next Peek, Read, or Skip call. +// It returns [io.EOF] if there are no more tokens. +func (d *Decoder) ReadToken() (Token, error) { + return d.s.ReadToken() +} +func (d *decoderState) ReadToken() (Token, error) { + // Determine the next kind. + var err error + var next Kind + pos := d.peekPos + if pos != 0 { + // Use cached peek result. + if d.peekErr != nil { + err := d.peekErr + d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error + return Token{}, err + } + next = Kind(d.buf[pos]).normalize() + d.peekPos = 0 // reset cache + } else { + d.invalidatePreviousRead() + pos = d.prevEnd + + // Consume leading whitespace. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { + err = io.EOF // EOF possibly if no Tokens present after top-level value + } + return Token{}, wrapSyntacticError(d, err, pos, 0) + } + } + + // Consume colon or comma. + var delim byte + if c := d.buf[pos]; c == ':' || c == ',' { + delim = c + pos += 1 + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + err = wrapSyntacticError(d, err, pos, 0) + return Token{}, d.checkDelimBeforeIOError(delim, err) + } + } + } + next = Kind(d.buf[pos]).normalize() + if d.Tokens.needDelim(next) != delim { + return Token{}, d.checkDelim(delim, next) + } + } + + // Handle the next token. + var n int + switch next { + case 'n': + if jsonwire.ConsumeNull(d.buf[pos:]) == 0 { + pos, err = d.consumeLiteral(pos, "null") + if err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + } else { + pos += len("null") + } + if err = d.Tokens.appendLiteral(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos-len("null"), +1) // report position at start of literal + } + d.prevStart, d.prevEnd = pos, pos + return Null, nil + + case 'f': + if jsonwire.ConsumeFalse(d.buf[pos:]) == 0 { + pos, err = d.consumeLiteral(pos, "false") + if err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + } else { + pos += len("false") + } + if err = d.Tokens.appendLiteral(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos-len("false"), +1) // report position at start of literal + } + d.prevStart, d.prevEnd = pos, pos + return False, nil + + case 't': + if jsonwire.ConsumeTrue(d.buf[pos:]) == 0 { + pos, err = d.consumeLiteral(pos, "true") + if err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + } else { + pos += len("true") + } + if err = d.Tokens.appendLiteral(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos-len("true"), +1) // report position at start of literal + } + d.prevStart, d.prevEnd = pos, pos + return True, nil + + case '"': + var flags jsonwire.ValueFlags // TODO: Preserve this in Token? + if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { + oldAbsPos := d.baseOffset + int64(pos) + pos, err = d.consumeString(&flags, pos) + newAbsPos := d.baseOffset + int64(pos) + n = int(newAbsPos - oldAbsPos) + if err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + } else { + pos += n + } + if d.Tokens.Last.NeedObjectName() { + if !d.Flags.Get(jsonflags.AllowDuplicateNames) { + if !d.Tokens.Last.isValidNamespace() { + return Token{}, wrapSyntacticError(d, errInvalidNamespace, pos-n, +1) + } + if d.Tokens.Last.isActiveNamespace() && !d.Namespaces.Last().insertQuoted(d.buf[pos-n:pos], flags.IsVerbatim()) { + err = wrapWithObjectName(ErrDuplicateName, d.buf[pos-n:pos]) + return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of string + } + } + d.Names.ReplaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds + } + if err = d.Tokens.appendString(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of string + } + d.prevStart, d.prevEnd = pos-n, pos + return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil + + case '0': + // NOTE: Since JSON numbers are not self-terminating, + // we need to make sure that the next byte is not part of a number. + if n = jsonwire.ConsumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { + oldAbsPos := d.baseOffset + int64(pos) + pos, err = d.consumeNumber(pos) + newAbsPos := d.baseOffset + int64(pos) + n = int(newAbsPos - oldAbsPos) + if err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + } else { + pos += n + } + if err = d.Tokens.appendNumber(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos-n, +1) // report position at start of number + } + d.prevStart, d.prevEnd = pos-n, pos + return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil + + case '{': + if err = d.Tokens.pushObject(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + d.Names.push() + if !d.Flags.Get(jsonflags.AllowDuplicateNames) { + d.Namespaces.push() + } + pos += 1 + d.prevStart, d.prevEnd = pos, pos + return BeginObject, nil + + case '}': + if err = d.Tokens.popObject(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + d.Names.pop() + if !d.Flags.Get(jsonflags.AllowDuplicateNames) { + d.Namespaces.pop() + } + pos += 1 + d.prevStart, d.prevEnd = pos, pos + return EndObject, nil + + case '[': + if err = d.Tokens.pushArray(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + pos += 1 + d.prevStart, d.prevEnd = pos, pos + return BeginArray, nil + + case ']': + if err = d.Tokens.popArray(); err != nil { + return Token{}, wrapSyntacticError(d, err, pos, +1) + } + pos += 1 + d.prevStart, d.prevEnd = pos, pos + return EndArray, nil + + default: + err = jsonwire.NewInvalidCharacterError(d.buf[pos:], "at start of value") + return Token{}, wrapSyntacticError(d, err, pos, +1) + } +} + +// ReadValue returns the next raw JSON value, advancing the read offset. +// The value is stripped of any leading or trailing whitespace and +// contains the exact bytes of the input, which may contain invalid UTF-8 +// if [AllowInvalidUTF8] is specified. +// +// The returned value is only valid until the next Peek, Read, or Skip call and +// may not be mutated while the Decoder remains in use. +// If the decoder is currently at the end token for an object or array, +// then it reports a [SyntacticError] and the internal state remains unchanged. +// It returns [io.EOF] if there are no more values. +func (d *Decoder) ReadValue() (Value, error) { + var flags jsonwire.ValueFlags + return d.s.ReadValue(&flags) +} +func (d *decoderState) ReadValue(flags *jsonwire.ValueFlags) (Value, error) { + // Determine the next kind. + var err error + var next Kind + pos := d.peekPos + if pos != 0 { + // Use cached peek result. + if d.peekErr != nil { + err := d.peekErr + d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error + return nil, err + } + next = Kind(d.buf[pos]).normalize() + d.peekPos = 0 // reset cache + } else { + d.invalidatePreviousRead() + pos = d.prevEnd + + // Consume leading whitespace. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + if err == io.ErrUnexpectedEOF && d.Tokens.Depth() == 1 { + err = io.EOF // EOF possibly if no Tokens present after top-level value + } + return nil, wrapSyntacticError(d, err, pos, 0) + } + } + + // Consume colon or comma. + var delim byte + if c := d.buf[pos]; c == ':' || c == ',' { + delim = c + pos += 1 + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + err = wrapSyntacticError(d, err, pos, 0) + return nil, d.checkDelimBeforeIOError(delim, err) + } + } + } + next = Kind(d.buf[pos]).normalize() + if d.Tokens.needDelim(next) != delim { + return nil, d.checkDelim(delim, next) + } + } + + // Handle the next value. + oldAbsPos := d.baseOffset + int64(pos) + pos, err = d.consumeValue(flags, pos, d.Tokens.Depth()) + newAbsPos := d.baseOffset + int64(pos) + n := int(newAbsPos - oldAbsPos) + if err != nil { + return nil, wrapSyntacticError(d, err, pos, +1) + } + switch next { + case 'n', 't', 'f': + err = d.Tokens.appendLiteral() + case '"': + if d.Tokens.Last.NeedObjectName() { + if !d.Flags.Get(jsonflags.AllowDuplicateNames) { + if !d.Tokens.Last.isValidNamespace() { + err = errInvalidNamespace + break + } + if d.Tokens.Last.isActiveNamespace() && !d.Namespaces.Last().insertQuoted(d.buf[pos-n:pos], flags.IsVerbatim()) { + err = wrapWithObjectName(ErrDuplicateName, d.buf[pos-n:pos]) + break + } + } + d.Names.ReplaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds + } + err = d.Tokens.appendString() + case '0': + err = d.Tokens.appendNumber() + case '{': + if err = d.Tokens.pushObject(); err != nil { + break + } + if err = d.Tokens.popObject(); err != nil { + panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) + } + case '[': + if err = d.Tokens.pushArray(); err != nil { + break + } + if err = d.Tokens.popArray(); err != nil { + panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) + } + } + if err != nil { + return nil, wrapSyntacticError(d, err, pos-n, +1) // report position at start of value + } + d.prevEnd = pos + d.prevStart = pos - n + return d.buf[pos-n : pos : pos], nil +} + +// CheckNextValue checks whether the next value is syntactically valid, +// but does not advance the read offset. +// If last, it verifies that the stream cleanly terminates with [io.EOF]. +func (d *decoderState) CheckNextValue(last bool) error { + d.PeekKind() // populates d.peekPos and d.peekErr + pos, err := d.peekPos, d.peekErr + d.peekPos, d.peekErr = 0, nil + if err != nil { + return err + } + + var flags jsonwire.ValueFlags + if pos, err := d.consumeValue(&flags, pos, d.Tokens.Depth()); err != nil { + return wrapSyntacticError(d, err, pos, +1) + } else if last { + return d.checkEOF(pos) + } + return nil +} + +// CheckEOF verifies that the input has no more data. +func (d *decoderState) CheckEOF() error { + return d.checkEOF(d.prevEnd) +} +func (d *decoderState) checkEOF(pos int) error { + switch pos, err := d.consumeWhitespace(pos); err { + case nil: + err := jsonwire.NewInvalidCharacterError(d.buf[pos:], "after top-level value") + return wrapSyntacticError(d, err, pos, 0) + case io.ErrUnexpectedEOF: + return nil + default: + return err + } +} + +// consumeWhitespace consumes all whitespace starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the last whitespace. +// If it returns nil, there is guaranteed to at least be one unread byte. +// +// The following pattern is common in this implementation: +// +// pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) +// if d.needMore(pos) { +// if pos, err = d.consumeWhitespace(pos); err != nil { +// return ... +// } +// } +// +// It is difficult to simplify this without sacrificing performance since +// consumeWhitespace must be inlined. The body of the if statement is +// executed only in rare situations where we need to fetch more data. +// Since fetching may return an error, we also need to check the error. +func (d *decoderState) consumeWhitespace(pos int) (newPos int, err error) { + for { + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + absPos := d.baseOffset + int64(pos) + err = d.fetch() // will mutate d.buf and invalidate pos + pos = int(absPos - d.baseOffset) + if err != nil { + return pos, err + } + continue + } + return pos, nil + } +} + +// consumeValue consumes a single JSON value starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the value. +func (d *decoderState) consumeValue(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { + for { + var n int + var err error + switch next := Kind(d.buf[pos]).normalize(); next { + case 'n': + if n = jsonwire.ConsumeNull(d.buf[pos:]); n == 0 { + n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "null") + } + case 'f': + if n = jsonwire.ConsumeFalse(d.buf[pos:]); n == 0 { + n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "false") + } + case 't': + if n = jsonwire.ConsumeTrue(d.buf[pos:]); n == 0 { + n, err = jsonwire.ConsumeLiteral(d.buf[pos:], "true") + } + case '"': + if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { + return d.consumeString(flags, pos) + } + case '0': + // NOTE: Since JSON numbers are not self-terminating, + // we need to make sure that the next byte is not part of a number. + if n = jsonwire.ConsumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { + return d.consumeNumber(pos) + } + case '{': + return d.consumeObject(flags, pos, depth) + case '[': + return d.consumeArray(flags, pos, depth) + default: + if (d.Tokens.Last.isObject() && next == ']') || (d.Tokens.Last.isArray() && next == '}') { + return pos, errMismatchDelim + } + return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "at start of value") + } + if err == io.ErrUnexpectedEOF { + absPos := d.baseOffset + int64(pos) + err = d.fetch() // will mutate d.buf and invalidate pos + pos = int(absPos - d.baseOffset) + if err != nil { + return pos + n, err + } + continue + } + return pos + n, err + } +} + +// consumeLiteral consumes a single JSON literal starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the literal. +func (d *decoderState) consumeLiteral(pos int, lit string) (newPos int, err error) { + for { + n, err := jsonwire.ConsumeLiteral(d.buf[pos:], lit) + if err == io.ErrUnexpectedEOF { + absPos := d.baseOffset + int64(pos) + err = d.fetch() // will mutate d.buf and invalidate pos + pos = int(absPos - d.baseOffset) + if err != nil { + return pos + n, err + } + continue + } + return pos + n, err + } +} + +// consumeString consumes a single JSON string starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the string. +func (d *decoderState) consumeString(flags *jsonwire.ValueFlags, pos int) (newPos int, err error) { + var n int + for { + n, err = jsonwire.ConsumeStringResumable(flags, d.buf[pos:], n, !d.Flags.Get(jsonflags.AllowInvalidUTF8)) + if err == io.ErrUnexpectedEOF { + absPos := d.baseOffset + int64(pos) + err = d.fetch() // will mutate d.buf and invalidate pos + pos = int(absPos - d.baseOffset) + if err != nil { + return pos + n, err + } + continue + } + return pos + n, err + } +} + +// consumeNumber consumes a single JSON number starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the number. +func (d *decoderState) consumeNumber(pos int) (newPos int, err error) { + var n int + var state jsonwire.ConsumeNumberState + for { + n, state, err = jsonwire.ConsumeNumberResumable(d.buf[pos:], n, state) + // NOTE: Since JSON numbers are not self-terminating, + // we need to make sure that the next byte is not part of a number. + if err == io.ErrUnexpectedEOF || d.needMore(pos+n) { + mayTerminate := err == nil + absPos := d.baseOffset + int64(pos) + err = d.fetch() // will mutate d.buf and invalidate pos + pos = int(absPos - d.baseOffset) + if err != nil { + if mayTerminate && err == io.ErrUnexpectedEOF { + return pos + n, nil + } + return pos, err + } + continue + } + return pos + n, err + } +} + +// consumeObject consumes a single JSON object starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the object. +func (d *decoderState) consumeObject(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { + var n int + var names *objectNamespace + if !d.Flags.Get(jsonflags.AllowDuplicateNames) { + d.Namespaces.push() + defer d.Namespaces.pop() + names = d.Namespaces.Last() + } + + // Handle before start. + if uint(pos) >= uint(len(d.buf)) || d.buf[pos] != '{' { + panic("BUG: consumeObject must be called with a buffer that starts with '{'") + } else if depth == maxNestingDepth+1 { + return pos, errMaxDepth + } + pos++ + + // Handle after start. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + if d.buf[pos] == '}' { + pos++ + return pos, nil + } + + depth++ + for { + // Handle before name. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + var flags2 jsonwire.ValueFlags + if n = jsonwire.ConsumeSimpleString(d.buf[pos:]); n == 0 { + oldAbsPos := d.baseOffset + int64(pos) + pos, err = d.consumeString(&flags2, pos) + newAbsPos := d.baseOffset + int64(pos) + n = int(newAbsPos - oldAbsPos) + flags.Join(flags2) + if err != nil { + return pos, err + } + } else { + pos += n + } + quotedName := d.buf[pos-n : pos] + if !d.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(quotedName, flags2.IsVerbatim()) { + return pos - n, wrapWithObjectName(ErrDuplicateName, quotedName) + } + + // Handle after name. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, wrapWithObjectName(err, quotedName) + } + } + if d.buf[pos] != ':' { + err := jsonwire.NewInvalidCharacterError(d.buf[pos:], "after object name (expecting ':')") + return pos, wrapWithObjectName(err, quotedName) + } + pos++ + + // Handle before value. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, wrapWithObjectName(err, quotedName) + } + } + pos, err = d.consumeValue(flags, pos, depth) + if err != nil { + return pos, wrapWithObjectName(err, quotedName) + } + + // Handle after value. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + switch d.buf[pos] { + case ',': + pos++ + continue + case '}': + pos++ + return pos, nil + default: + return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "after object value (expecting ',' or '}')") + } + } +} + +// consumeArray consumes a single JSON array starting at d.buf[pos:]. +// It returns the new position in d.buf immediately after the array. +func (d *decoderState) consumeArray(flags *jsonwire.ValueFlags, pos, depth int) (newPos int, err error) { + // Handle before start. + if uint(pos) >= uint(len(d.buf)) || d.buf[pos] != '[' { + panic("BUG: consumeArray must be called with a buffer that starts with '['") + } else if depth == maxNestingDepth+1 { + return pos, errMaxDepth + } + pos++ + + // Handle after start. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + if d.buf[pos] == ']' { + pos++ + return pos, nil + } + + var idx int64 + depth++ + for { + // Handle before value. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + pos, err = d.consumeValue(flags, pos, depth) + if err != nil { + return pos, wrapWithArrayIndex(err, idx) + } + + // Handle after value. + pos += jsonwire.ConsumeWhitespace(d.buf[pos:]) + if d.needMore(pos) { + if pos, err = d.consumeWhitespace(pos); err != nil { + return pos, err + } + } + switch d.buf[pos] { + case ',': + pos++ + idx++ + continue + case ']': + pos++ + return pos, nil + default: + return pos, jsonwire.NewInvalidCharacterError(d.buf[pos:], "after array element (expecting ',' or ']')") + } + } +} + +// InputOffset returns the current input byte offset. It gives the location +// of the next byte immediately after the most recently returned token or value. +// The number of bytes actually read from the underlying [io.Reader] may be more +// than this offset due to internal buffering effects. +func (d *Decoder) InputOffset() int64 { + return d.s.previousOffsetEnd() +} + +// UnreadBuffer returns the data remaining in the unread buffer, +// which may contain zero or more bytes. +// The returned buffer must not be mutated while Decoder continues to be used. +// The buffer contents are valid until the next Peek, Read, or Skip call. +func (d *Decoder) UnreadBuffer() []byte { + return d.s.unreadBuffer() +} + +// StackDepth returns the depth of the state machine for read JSON data. +// Each level on the stack represents a nested JSON object or array. +// It is incremented whenever an [BeginObject] or [BeginArray] token is encountered +// and decremented whenever an [EndObject] or [EndArray] token is encountered. +// The depth is zero-indexed, where zero represents the top-level JSON value. +func (d *Decoder) StackDepth() int { + // NOTE: Keep in sync with Encoder.StackDepth. + return d.s.Tokens.Depth() - 1 +} + +// StackIndex returns information about the specified stack level. +// It must be a number between 0 and [Decoder.StackDepth], inclusive. +// For each level, it reports the kind: +// +// - 0 for a level of zero, +// - '{' for a level representing a JSON object, and +// - '[' for a level representing a JSON array. +// +// It also reports the length of that JSON object or array. +// Each name and value in a JSON object is counted separately, +// so the effective number of members would be half the length. +// A complete JSON object must have an even length. +func (d *Decoder) StackIndex(i int) (Kind, int64) { + // NOTE: Keep in sync with Encoder.StackIndex. + switch s := d.s.Tokens.index(i); { + case i > 0 && s.isObject(): + return '{', s.Length() + case i > 0 && s.isArray(): + return '[', s.Length() + default: + return 0, s.Length() + } +} + +// StackPointer returns a JSON Pointer (RFC 6901) to the most recently read value. +func (d *Decoder) StackPointer() Pointer { + return Pointer(d.s.AppendStackPointer(nil, -1)) +} + +func (d *decoderState) AppendStackPointer(b []byte, where int) []byte { + d.Names.copyQuotedBuffer(d.buf) + return d.state.appendStackPointer(b, where) +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/doc.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/doc.go new file mode 100644 index 000000000..bea3ccd34 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/doc.go @@ -0,0 +1,109 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jsontext implements syntactic processing of JSON +// as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. +// JSON is a simple data interchange format that can represent +// primitive data types such as booleans, strings, and numbers, +// in addition to structured data types such as objects and arrays. +// +// The [Encoder] and [Decoder] types are used to encode or decode +// a stream of JSON tokens or values. +// +// # Tokens and Values +// +// A JSON token refers to the basic structural elements of JSON: +// +// - a JSON literal (i.e., null, true, or false) +// - a JSON string (e.g., "hello, world!") +// - a JSON number (e.g., 123.456) +// - a begin or end delimiter for a JSON object (i.e., '{' or '}') +// - a begin or end delimiter for a JSON array (i.e., '[' or ']') +// +// A JSON token is represented by the [Token] type in Go. Technically, +// there are two additional structural characters (i.e., ':' and ','), +// but there is no [Token] representation for them since their presence +// can be inferred by the structure of the JSON grammar itself. +// For example, there must always be an implicit colon between +// the name and value of a JSON object member. +// +// A JSON value refers to a complete unit of JSON data: +// +// - a JSON literal, string, or number +// - a JSON object (e.g., `{"name":"value"}`) +// - a JSON array (e.g., `[1,2,3,]`) +// +// A JSON value is represented by the [Value] type in Go and is a []byte +// containing the raw textual representation of the value. There is some overlap +// between tokens and values as both contain literals, strings, and numbers. +// However, only a value can represent the entirety of a JSON object or array. +// +// The [Encoder] and [Decoder] types contain methods to read or write the next +// [Token] or [Value] in a sequence. They maintain a state machine to validate +// whether the sequence of JSON tokens and/or values produces a valid JSON. +// [Options] may be passed to the [NewEncoder] or [NewDecoder] constructors +// to configure the syntactic behavior of encoding and decoding. +// +// # Terminology +// +// The terms "encode" and "decode" are used for syntactic functionality +// that is concerned with processing JSON based on its grammar, and +// the terms "marshal" and "unmarshal" are used for semantic functionality +// that determines the meaning of JSON values as Go values and vice-versa. +// This package (i.e., [jsontext]) deals with JSON at a syntactic layer, +// while [encoding/json/v2] deals with JSON at a semantic layer. +// The goal is to provide a clear distinction between functionality that +// is purely concerned with encoding versus that of marshaling. +// For example, one can directly encode a stream of JSON tokens without +// needing to marshal a concrete Go value representing them. +// Similarly, one can decode a stream of JSON tokens without +// needing to unmarshal them into a concrete Go value. +// +// This package uses JSON terminology when discussing JSON, which may differ +// from related concepts in Go or elsewhere in computing literature. +// +// - a JSON "object" refers to an unordered collection of name/value members. +// - a JSON "array" refers to an ordered sequence of elements. +// - a JSON "value" refers to either a literal (i.e., null, false, or true), +// string, number, object, or array. +// +// See RFC 8259 for more information. +// +// # Specifications +// +// Relevant specifications include RFC 4627, RFC 7159, RFC 7493, RFC 8259, +// and RFC 8785. Each RFC is generally a stricter subset of another RFC. +// In increasing order of strictness: +// +// - RFC 4627 and RFC 7159 do not require (but recommend) the use of UTF-8 +// and also do not require (but recommend) that object names be unique. +// - RFC 8259 requires the use of UTF-8, +// but does not require (but recommends) that object names be unique. +// - RFC 7493 requires the use of UTF-8 +// and also requires that object names be unique. +// - RFC 8785 defines a canonical representation. It requires the use of UTF-8 +// and also requires that object names be unique and in a specific ordering. +// It specifies exactly how strings and numbers must be formatted. +// +// The primary difference between RFC 4627 and RFC 7159 is that the former +// restricted top-level values to only JSON objects and arrays, while +// RFC 7159 and subsequent RFCs permit top-level values to additionally be +// JSON nulls, booleans, strings, or numbers. +// +// By default, this package operates on RFC 7493, but can be configured +// to operate according to the other RFC specifications. +// RFC 7493 is a stricter subset of RFC 8259 and fully compliant with it. +// In particular, it makes specific choices about behavior that RFC 8259 +// leaves as undefined in order to ensure greater interoperability. +// +// # Security Considerations +// +// See the "Security Considerations" section in [encoding/json/v2]. +package jsontext + +// requireKeyedLiterals can be embedded in a struct to require keyed literals. +type requireKeyedLiterals struct{} + +// nonComparable can be embedded in a struct to prevent comparability. +type nonComparable [0]func() diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/encode.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/encode.go new file mode 100644 index 000000000..36bf7efdf --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/encode.go @@ -0,0 +1,975 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "bytes" + "io" + "math/bits" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +// Encoder is a streaming encoder from raw JSON tokens and values. +// It is used to write a stream of top-level JSON values, +// each terminated with a newline character. +// +// [Encoder.WriteToken] and [Encoder.WriteValue] calls may be interleaved. +// For example, the following JSON value: +// +// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} +// +// can be composed with the following calls (ignoring errors for brevity): +// +// e.WriteToken(BeginObject) // { +// e.WriteToken(String("name")) // "name" +// e.WriteToken(String("value")) // "value" +// e.WriteValue(Value(`"array"`)) // "array" +// e.WriteToken(BeginArray) // [ +// e.WriteToken(Null) // null +// e.WriteToken(False) // false +// e.WriteValue(Value("true")) // true +// e.WriteToken(Float(3.14159)) // 3.14159 +// e.WriteToken(EndArray) // ] +// e.WriteValue(Value(`"object"`)) // "object" +// e.WriteValue(Value(`{"k":"v"}`)) // {"k":"v"} +// e.WriteToken(EndObject) // } +// +// The above is one of many possible sequence of calls and +// may not represent the most sensible method to call for any given token/value. +// For example, it is probably more common to call [Encoder.WriteToken] with a string +// for object names. +type Encoder struct { + s encoderState +} + +// encoderState is the low-level state of Encoder. +// It has exported fields and method for use by the "json" package. +type encoderState struct { + state + encodeBuffer + jsonopts.Struct + + SeenPointers map[any]struct{} // only used when marshaling; identical to json.seenPointers +} + +// encodeBuffer is a buffer split into 2 segments: +// +// - buf[0:len(buf)] // written (but unflushed) portion of the buffer +// - buf[len(buf):cap(buf)] // unused portion of the buffer +type encodeBuffer struct { + Buf []byte // may alias wr if it is a bytes.Buffer + + // baseOffset is added to len(buf) to obtain the absolute offset + // relative to the start of io.Writer stream. + baseOffset int64 + + wr io.Writer + + // maxValue is the approximate maximum Value size passed to WriteValue. + maxValue int + // availBuffer is the buffer returned by the AvailableBuffer method. + availBuffer []byte // always has zero length + // bufStats is statistics about buffer utilization. + // It is only used with pooled encoders in pools.go. + bufStats bufferStatistics +} + +// NewEncoder constructs a new streaming encoder writing to w +// configured with the provided options. +// It flushes the internal buffer when the buffer is sufficiently full or +// when a top-level value has been written. +// +// If w is a [bytes.Buffer], then the encoder appends directly into the buffer +// without copying the contents from an intermediate buffer. +func NewEncoder(w io.Writer, opts ...Options) *Encoder { + e := new(Encoder) + e.Reset(w, opts...) + return e +} + +// Reset resets an encoder such that it is writing afresh to w and +// configured with the provided options. Reset must not be called on +// a Encoder passed to the [encoding/json/v2.MarshalerTo.MarshalJSONTo] method +// or the [encoding/json/v2.MarshalToFunc] function. +func (e *Encoder) Reset(w io.Writer, opts ...Options) { + switch { + case e == nil: + panic("jsontext: invalid nil Encoder") + case w == nil: + panic("jsontext: invalid nil io.Writer") + case e.s.Flags.Get(jsonflags.WithinArshalCall): + panic("jsontext: cannot reset Encoder passed to json.MarshalerTo") + } + // Reuse the buffer if it does not alias a previous [bytes.Buffer]. + b := e.s.Buf[:0] + if _, ok := e.s.wr.(*bytes.Buffer); ok { + b = nil + } + e.s.reset(b, w, opts...) +} + +func (e *encoderState) reset(b []byte, w io.Writer, opts ...Options) { + e.state.reset() + e.encodeBuffer = encodeBuffer{Buf: b, wr: w, availBuffer: e.availBuffer, bufStats: e.bufStats} + if bb, ok := w.(*bytes.Buffer); ok && bb != nil { + e.Buf = bb.AvailableBuffer() // alias the unused buffer of bb + } + opts2 := jsonopts.Struct{} // avoid mutating e.Struct in case it is part of opts + opts2.Join(opts...) + e.Struct = opts2 + if e.Flags.Get(jsonflags.Multiline) { + if !e.Flags.Has(jsonflags.SpaceAfterColon) { + e.Flags.Set(jsonflags.SpaceAfterColon | 1) + } + if !e.Flags.Has(jsonflags.SpaceAfterComma) { + e.Flags.Set(jsonflags.SpaceAfterComma | 0) + } + if !e.Flags.Has(jsonflags.Indent) { + e.Flags.Set(jsonflags.Indent | 1) + e.Indent = "\t" + } + } +} + +// Options returns the options used to construct the decoder and +// may additionally contain semantic options passed to a +// [encoding/json/v2.MarshalEncode] call. +// +// If operating within +// a [encoding/json/v2.MarshalerTo.MarshalJSONTo] method call or +// a [encoding/json/v2.MarshalToFunc] function call, +// then the returned options are only valid within the call. +func (e *Encoder) Options() Options { + return &e.s.Struct +} + +// NeedFlush determines whether to flush at this point. +func (e *encoderState) NeedFlush() bool { + // NOTE: This function is carefully written to be inlinable. + + // Avoid flushing if e.wr is nil since there is no underlying writer. + // Flush if less than 25% of the capacity remains. + // Flushing at some constant fraction ensures that the buffer stops growing + // so long as the largest Token or Value fits within that unused capacity. + return e.wr != nil && (e.Tokens.Depth() == 1 || len(e.Buf) > 3*cap(e.Buf)/4) +} + +// Flush flushes the buffer to the underlying io.Writer. +// It may append a trailing newline after the top-level value. +func (e *encoderState) Flush() error { + if e.wr == nil || e.avoidFlush() { + return nil + } + + // In streaming mode, always emit a newline after the top-level value. + if e.Tokens.Depth() == 1 && !e.Flags.Get(jsonflags.OmitTopLevelNewline) { + e.Buf = append(e.Buf, '\n') + } + + // Inform objectNameStack that we are about to flush the buffer content. + e.Names.copyQuotedBuffer(e.Buf) + + // Specialize bytes.Buffer for better performance. + if bb, ok := e.wr.(*bytes.Buffer); ok { + // If e.buf already aliases the internal buffer of bb, + // then the Write call simply increments the internal offset, + // otherwise Write operates as expected. + // See https://go.dev/issue/42986. + n, _ := bb.Write(e.Buf) // never fails unless bb is nil + e.baseOffset += int64(n) + + // If the internal buffer of bytes.Buffer is too small, + // append operations elsewhere in the Encoder may grow the buffer. + // This would be semantically correct, but hurts performance. + // As such, ensure 25% of the current length is always available + // to reduce the probability that other appends must allocate. + if avail := bb.Available(); avail < bb.Len()/4 { + bb.Grow(avail + 1) + } + + e.Buf = bb.AvailableBuffer() + return nil + } + + // Flush the internal buffer to the underlying io.Writer. + n, err := e.wr.Write(e.Buf) + e.baseOffset += int64(n) + if err != nil { + // In the event of an error, preserve the unflushed portion. + // Thus, write errors aren't fatal so long as the io.Writer + // maintains consistent state after errors. + if n > 0 { + e.Buf = e.Buf[:copy(e.Buf, e.Buf[n:])] + } + return &ioError{action: "write", err: err} + } + e.Buf = e.Buf[:0] + + // Check whether to grow the buffer. + // Note that cap(e.buf) may already exceed maxBufferSize since + // an append elsewhere already grew it to store a large token. + const maxBufferSize = 4 << 10 + const growthSizeFactor = 2 // higher value is faster + const growthRateFactor = 2 // higher value is slower + // By default, grow if below the maximum buffer size. + grow := cap(e.Buf) <= maxBufferSize/growthSizeFactor + // Growing can be expensive, so only grow + // if a sufficient number of bytes have been processed. + grow = grow && int64(cap(e.Buf)) < e.previousOffsetEnd()/growthRateFactor + if grow { + e.Buf = make([]byte, 0, cap(e.Buf)*growthSizeFactor) + } + + return nil +} +func (d *encodeBuffer) offsetAt(pos int) int64 { return d.baseOffset + int64(pos) } +func (e *encodeBuffer) previousOffsetEnd() int64 { return e.baseOffset + int64(len(e.Buf)) } +func (e *encodeBuffer) unflushedBuffer() []byte { return e.Buf } + +// avoidFlush indicates whether to avoid flushing to ensure there is always +// enough in the buffer to unwrite the last object member if it were empty. +func (e *encoderState) avoidFlush() bool { + switch { + case e.Tokens.Last.Length() == 0: + // Never flush after BeginObject or BeginArray since we don't know yet + // if the object or array will end up being empty. + return true + case e.Tokens.Last.needObjectValue(): + // Never flush before the object value since we don't know yet + // if the object value will end up being empty. + return true + case e.Tokens.Last.NeedObjectName() && len(e.Buf) >= 2: + // Never flush after the object value if it does turn out to be empty. + switch string(e.Buf[len(e.Buf)-2:]) { + case `ll`, `""`, `{}`, `[]`: // last two bytes of every empty value + return true + } + } + return false +} + +// UnwriteEmptyObjectMember unwrites the last object member if it is empty +// and reports whether it performed an unwrite operation. +func (e *encoderState) UnwriteEmptyObjectMember(prevName *string) bool { + if last := e.Tokens.Last; !last.isObject() || !last.NeedObjectName() || last.Length() == 0 { + panic("BUG: must be called on an object after writing a value") + } + + // The flushing logic is modified to never flush a trailing empty value. + // The encoder never writes trailing whitespace eagerly. + b := e.unflushedBuffer() + + // Detect whether the last value was empty. + var n int + if len(b) >= 3 { + switch string(b[len(b)-2:]) { + case "ll": // last two bytes of `null` + n = len(`null`) + case `""`: + // It is possible for a non-empty string to have `""` as a suffix + // if the second to the last quote was escaped. + if b[len(b)-3] == '\\' { + return false // e.g., `"\""` is not empty + } + n = len(`""`) + case `{}`: + n = len(`{}`) + case `[]`: + n = len(`[]`) + } + } + if n == 0 { + return false + } + + // Unwrite the value, whitespace, colon, name, whitespace, and comma. + b = b[:len(b)-n] + b = jsonwire.TrimSuffixWhitespace(b) + b = jsonwire.TrimSuffixByte(b, ':') + b = jsonwire.TrimSuffixString(b) + b = jsonwire.TrimSuffixWhitespace(b) + b = jsonwire.TrimSuffixByte(b, ',') + e.Buf = b // store back truncated unflushed buffer + + // Undo state changes. + e.Tokens.Last.decrement() // for object member value + e.Tokens.Last.decrement() // for object member name + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + if e.Tokens.Last.isActiveNamespace() { + e.Namespaces.Last().removeLast() + } + } + e.Names.clearLast() + if prevName != nil { + e.Names.copyQuotedBuffer(e.Buf) // required by objectNameStack.replaceLastUnquotedName + e.Names.replaceLastUnquotedName(*prevName) + } + return true +} + +// UnwriteOnlyObjectMemberName unwrites the only object member name +// and returns the unquoted name. +func (e *encoderState) UnwriteOnlyObjectMemberName() string { + if last := e.Tokens.Last; !last.isObject() || last.Length() != 1 { + panic("BUG: must be called on an object after writing first name") + } + + // Unwrite the name and whitespace. + b := jsonwire.TrimSuffixString(e.Buf) + isVerbatim := bytes.IndexByte(e.Buf[len(b):], '\\') < 0 + name := string(jsonwire.UnquoteMayCopy(e.Buf[len(b):], isVerbatim)) + e.Buf = jsonwire.TrimSuffixWhitespace(b) + + // Undo state changes. + e.Tokens.Last.decrement() + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + if e.Tokens.Last.isActiveNamespace() { + e.Namespaces.Last().removeLast() + } + } + e.Names.clearLast() + return name +} + +// WriteToken writes the next token and advances the internal write offset. +// +// The provided token kind must be consistent with the JSON grammar. +// For example, it is an error to provide a number when the encoder +// is expecting an object name (which is always a string), or +// to provide an end object delimiter when the encoder is finishing an array. +// If the provided token is invalid, then it reports a [SyntacticError] and +// the internal state remains unchanged. The offset reported +// in [SyntacticError] will be relative to the [Encoder.OutputOffset]. +func (e *Encoder) WriteToken(t Token) error { + return e.s.WriteToken(t) +} +func (e *encoderState) WriteToken(t Token) error { + k := t.Kind() + b := e.Buf // use local variable to avoid mutating e in case of error + + // Append any delimiters or optional whitespace. + b = e.Tokens.MayAppendDelim(b, k) + if e.Flags.Get(jsonflags.AnyWhitespace) { + b = e.appendWhitespace(b, k) + } + pos := len(b) // offset before the token + + // Append the token to the output and to the state machine. + var err error + switch k { + case 'n': + b = append(b, "null"...) + err = e.Tokens.appendLiteral() + case 'f': + b = append(b, "false"...) + err = e.Tokens.appendLiteral() + case 't': + b = append(b, "true"...) + err = e.Tokens.appendLiteral() + case '"': + if b, err = t.appendString(b, &e.Flags); err != nil { + break + } + if e.Tokens.Last.NeedObjectName() { + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + if !e.Tokens.Last.isValidNamespace() { + err = errInvalidNamespace + break + } + if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], false) { + err = wrapWithObjectName(ErrDuplicateName, b[pos:]) + break + } + } + e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds + } + err = e.Tokens.appendString() + case '0': + if b, err = t.appendNumber(b, &e.Flags); err != nil { + break + } + err = e.Tokens.appendNumber() + case '{': + b = append(b, '{') + if err = e.Tokens.pushObject(); err != nil { + break + } + e.Names.push() + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + e.Namespaces.push() + } + case '}': + b = append(b, '}') + if err = e.Tokens.popObject(); err != nil { + break + } + e.Names.pop() + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + e.Namespaces.pop() + } + case '[': + b = append(b, '[') + err = e.Tokens.pushArray() + case ']': + b = append(b, ']') + err = e.Tokens.popArray() + default: + err = errInvalidToken + } + if err != nil { + return wrapSyntacticError(e, err, pos, +1) + } + + // Finish off the buffer and store it back into e. + e.Buf = b + if e.NeedFlush() { + return e.Flush() + } + return nil +} + +// AppendRaw appends either a raw string (without double quotes) or number. +// Specify safeASCII if the string output is guaranteed to be ASCII +// without any characters (including '<', '>', and '&') that need escaping, +// otherwise this will validate whether the string needs escaping. +// The appended bytes for a JSON number must be valid. +// +// This is a specialized implementation of Encoder.WriteValue +// that allows appending directly into the buffer. +// It is only called from marshal logic in the "json" package. +func (e *encoderState) AppendRaw(k Kind, safeASCII bool, appendFn func([]byte) ([]byte, error)) error { + b := e.Buf // use local variable to avoid mutating e in case of error + + // Append any delimiters or optional whitespace. + b = e.Tokens.MayAppendDelim(b, k) + if e.Flags.Get(jsonflags.AnyWhitespace) { + b = e.appendWhitespace(b, k) + } + pos := len(b) // offset before the token + + var err error + switch k { + case '"': + // Append directly into the encoder buffer by assuming that + // most of the time none of the characters need escaping. + b = append(b, '"') + if b, err = appendFn(b); err != nil { + return err + } + b = append(b, '"') + + // Check whether we need to escape the string and if necessary + // copy it to a scratch buffer and then escape it back. + isVerbatim := safeASCII || !jsonwire.NeedEscape(b[pos+len(`"`):len(b)-len(`"`)]) + if !isVerbatim { + var err error + b2 := append(e.availBuffer, b[pos+len(`"`):len(b)-len(`"`)]...) + b, err = jsonwire.AppendQuote(b[:pos], string(b2), &e.Flags) + e.availBuffer = b2[:0] + if err != nil { + return wrapSyntacticError(e, err, pos, +1) + } + } + + // Update the state machine. + if e.Tokens.Last.NeedObjectName() { + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + if !e.Tokens.Last.isValidNamespace() { + return wrapSyntacticError(e, err, pos, +1) + } + if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], isVerbatim) { + err = wrapWithObjectName(ErrDuplicateName, b[pos:]) + return wrapSyntacticError(e, err, pos, +1) + } + } + e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds + } + if err := e.Tokens.appendString(); err != nil { + return wrapSyntacticError(e, err, pos, +1) + } + case '0': + if b, err = appendFn(b); err != nil { + return err + } + if err := e.Tokens.appendNumber(); err != nil { + return wrapSyntacticError(e, err, pos, +1) + } + default: + panic("BUG: invalid kind") + } + + // Finish off the buffer and store it back into e. + e.Buf = b + if e.NeedFlush() { + return e.Flush() + } + return nil +} + +// WriteValue writes the next raw value and advances the internal write offset. +// The Encoder does not simply copy the provided value verbatim, but +// parses it to ensure that it is syntactically valid and reformats it +// according to how the Encoder is configured to format whitespace and strings. +// If [AllowInvalidUTF8] is specified, then any invalid UTF-8 is mangled +// as the Unicode replacement character, U+FFFD. +// +// The provided value kind must be consistent with the JSON grammar +// (see examples on [Encoder.WriteToken]). If the provided value is invalid, +// then it reports a [SyntacticError] and the internal state remains unchanged. +// The offset reported in [SyntacticError] will be relative to the +// [Encoder.OutputOffset] plus the offset into v of any encountered syntax error. +func (e *Encoder) WriteValue(v Value) error { + return e.s.WriteValue(v) +} +func (e *encoderState) WriteValue(v Value) error { + e.maxValue |= len(v) // bitwise OR is a fast approximation of max + + k := v.Kind() + b := e.Buf // use local variable to avoid mutating e in case of error + + // Append any delimiters or optional whitespace. + b = e.Tokens.MayAppendDelim(b, k) + if e.Flags.Get(jsonflags.AnyWhitespace) { + b = e.appendWhitespace(b, k) + } + pos := len(b) // offset before the value + + // Append the value the output. + var n int + n += jsonwire.ConsumeWhitespace(v[n:]) + b, m, err := e.reformatValue(b, v[n:], e.Tokens.Depth()) + if err != nil { + return wrapSyntacticError(e, err, pos+n+m, +1) + } + n += m + n += jsonwire.ConsumeWhitespace(v[n:]) + if len(v) > n { + err = jsonwire.NewInvalidCharacterError(v[n:], "after top-level value") + return wrapSyntacticError(e, err, pos+n, 0) + } + + // Append the kind to the state machine. + switch k { + case 'n', 'f', 't': + err = e.Tokens.appendLiteral() + case '"': + if e.Tokens.Last.NeedObjectName() { + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + if !e.Tokens.Last.isValidNamespace() { + err = errInvalidNamespace + break + } + if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], false) { + err = wrapWithObjectName(ErrDuplicateName, b[pos:]) + break + } + } + e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds + } + err = e.Tokens.appendString() + case '0': + err = e.Tokens.appendNumber() + case '{': + if err = e.Tokens.pushObject(); err != nil { + break + } + if err = e.Tokens.popObject(); err != nil { + panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) + } + if e.Flags.Get(jsonflags.ReorderRawObjects) { + mustReorderObjects(b[pos:]) + } + case '[': + if err = e.Tokens.pushArray(); err != nil { + break + } + if err = e.Tokens.popArray(); err != nil { + panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) + } + if e.Flags.Get(jsonflags.ReorderRawObjects) { + mustReorderObjects(b[pos:]) + } + } + if err != nil { + return wrapSyntacticError(e, err, pos, +1) + } + + // Finish off the buffer and store it back into e. + e.Buf = b + if e.NeedFlush() { + return e.Flush() + } + return nil +} + +// CountNextDelimWhitespace counts the number of bytes of delimiter and +// whitespace bytes assuming the upcoming token is a JSON value. +// This method is used for error reporting at the semantic layer. +func (e *encoderState) CountNextDelimWhitespace() (n int) { + const next = Kind('"') // arbitrary kind as next JSON value + delim := e.Tokens.needDelim(next) + if delim > 0 { + n += len(",") | len(":") + } + if delim == ':' { + if e.Flags.Get(jsonflags.SpaceAfterColon) { + n += len(" ") + } + } else { + if delim == ',' && e.Flags.Get(jsonflags.SpaceAfterComma) { + n += len(" ") + } + if e.Flags.Get(jsonflags.Multiline) { + if m := e.Tokens.NeedIndent(next); m > 0 { + n += len("\n") + len(e.IndentPrefix) + (m-1)*len(e.Indent) + } + } + } + return n +} + +// appendWhitespace appends whitespace that immediately precedes the next token. +func (e *encoderState) appendWhitespace(b []byte, next Kind) []byte { + if delim := e.Tokens.needDelim(next); delim == ':' { + if e.Flags.Get(jsonflags.SpaceAfterColon) { + b = append(b, ' ') + } + } else { + if delim == ',' && e.Flags.Get(jsonflags.SpaceAfterComma) { + b = append(b, ' ') + } + if e.Flags.Get(jsonflags.Multiline) { + b = e.AppendIndent(b, e.Tokens.NeedIndent(next)) + } + } + return b +} + +// AppendIndent appends the appropriate number of indentation characters +// for the current nested level, n. +func (e *encoderState) AppendIndent(b []byte, n int) []byte { + if n == 0 { + return b + } + b = append(b, '\n') + b = append(b, e.IndentPrefix...) + for ; n > 1; n-- { + b = append(b, e.Indent...) + } + return b +} + +// reformatValue parses a JSON value from the start of src and +// appends it to the end of dst, reformatting whitespace and strings as needed. +// It returns the extended dst buffer and the number of consumed input bytes. +func (e *encoderState) reformatValue(dst []byte, src Value, depth int) ([]byte, int, error) { + // TODO: Should this update ValueFlags as input? + if len(src) == 0 { + return dst, 0, io.ErrUnexpectedEOF + } + switch k := Kind(src[0]).normalize(); k { + case 'n': + if jsonwire.ConsumeNull(src) == 0 { + n, err := jsonwire.ConsumeLiteral(src, "null") + return dst, n, err + } + return append(dst, "null"...), len("null"), nil + case 'f': + if jsonwire.ConsumeFalse(src) == 0 { + n, err := jsonwire.ConsumeLiteral(src, "false") + return dst, n, err + } + return append(dst, "false"...), len("false"), nil + case 't': + if jsonwire.ConsumeTrue(src) == 0 { + n, err := jsonwire.ConsumeLiteral(src, "true") + return dst, n, err + } + return append(dst, "true"...), len("true"), nil + case '"': + if n := jsonwire.ConsumeSimpleString(src); n > 0 { + dst = append(dst, src[:n]...) // copy simple strings verbatim + return dst, n, nil + } + return jsonwire.ReformatString(dst, src, &e.Flags) + case '0': + if n := jsonwire.ConsumeSimpleNumber(src); n > 0 && !e.Flags.Get(jsonflags.CanonicalizeNumbers) { + dst = append(dst, src[:n]...) // copy simple numbers verbatim + return dst, n, nil + } + return jsonwire.ReformatNumber(dst, src, &e.Flags) + case '{': + return e.reformatObject(dst, src, depth) + case '[': + return e.reformatArray(dst, src, depth) + default: + return dst, 0, jsonwire.NewInvalidCharacterError(src, "at start of value") + } +} + +// reformatObject parses a JSON object from the start of src and +// appends it to the end of src, reformatting whitespace and strings as needed. +// It returns the extended dst buffer and the number of consumed input bytes. +func (e *encoderState) reformatObject(dst []byte, src Value, depth int) ([]byte, int, error) { + // Append object begin. + if len(src) == 0 || src[0] != '{' { + panic("BUG: reformatObject must be called with a buffer that starts with '{'") + } else if depth == maxNestingDepth+1 { + return dst, 0, errMaxDepth + } + dst = append(dst, '{') + n := len("{") + + // Append (possible) object end. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + if src[n] == '}' { + dst = append(dst, '}') + n += len("}") + return dst, n, nil + } + + var err error + var names *objectNamespace + if !e.Flags.Get(jsonflags.AllowDuplicateNames) { + e.Namespaces.push() + defer e.Namespaces.pop() + names = e.Namespaces.Last() + } + depth++ + for { + // Append optional newline and indentation. + if e.Flags.Get(jsonflags.Multiline) { + dst = e.AppendIndent(dst, depth) + } + + // Append object name. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + m := jsonwire.ConsumeSimpleString(src[n:]) + isVerbatim := m > 0 + if isVerbatim { + dst = append(dst, src[n:n+m]...) + } else { + dst, m, err = jsonwire.ReformatString(dst, src[n:], &e.Flags) + if err != nil { + return dst, n + m, err + } + } + quotedName := src[n : n+m] + if !e.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(quotedName, isVerbatim) { + return dst, n, wrapWithObjectName(ErrDuplicateName, quotedName) + } + n += m + + // Append colon. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, wrapWithObjectName(io.ErrUnexpectedEOF, quotedName) + } + if src[n] != ':' { + err = jsonwire.NewInvalidCharacterError(src[n:], "after object name (expecting ':')") + return dst, n, wrapWithObjectName(err, quotedName) + } + dst = append(dst, ':') + n += len(":") + if e.Flags.Get(jsonflags.SpaceAfterColon) { + dst = append(dst, ' ') + } + + // Append object value. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, wrapWithObjectName(io.ErrUnexpectedEOF, quotedName) + } + dst, m, err = e.reformatValue(dst, src[n:], depth) + if err != nil { + return dst, n + m, wrapWithObjectName(err, quotedName) + } + n += m + + // Append comma or object end. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + switch src[n] { + case ',': + dst = append(dst, ',') + if e.Flags.Get(jsonflags.SpaceAfterComma) { + dst = append(dst, ' ') + } + n += len(",") + continue + case '}': + if e.Flags.Get(jsonflags.Multiline) { + dst = e.AppendIndent(dst, depth-1) + } + dst = append(dst, '}') + n += len("}") + return dst, n, nil + default: + return dst, n, jsonwire.NewInvalidCharacterError(src[n:], "after object value (expecting ',' or '}')") + } + } +} + +// reformatArray parses a JSON array from the start of src and +// appends it to the end of dst, reformatting whitespace and strings as needed. +// It returns the extended dst buffer and the number of consumed input bytes. +func (e *encoderState) reformatArray(dst []byte, src Value, depth int) ([]byte, int, error) { + // Append array begin. + if len(src) == 0 || src[0] != '[' { + panic("BUG: reformatArray must be called with a buffer that starts with '['") + } else if depth == maxNestingDepth+1 { + return dst, 0, errMaxDepth + } + dst = append(dst, '[') + n := len("[") + + // Append (possible) array end. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + if src[n] == ']' { + dst = append(dst, ']') + n += len("]") + return dst, n, nil + } + + var idx int64 + var err error + depth++ + for { + // Append optional newline and indentation. + if e.Flags.Get(jsonflags.Multiline) { + dst = e.AppendIndent(dst, depth) + } + + // Append array value. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + var m int + dst, m, err = e.reformatValue(dst, src[n:], depth) + if err != nil { + return dst, n + m, wrapWithArrayIndex(err, idx) + } + n += m + + // Append comma or array end. + n += jsonwire.ConsumeWhitespace(src[n:]) + if uint(len(src)) <= uint(n) { + return dst, n, io.ErrUnexpectedEOF + } + switch src[n] { + case ',': + dst = append(dst, ',') + if e.Flags.Get(jsonflags.SpaceAfterComma) { + dst = append(dst, ' ') + } + n += len(",") + idx++ + continue + case ']': + if e.Flags.Get(jsonflags.Multiline) { + dst = e.AppendIndent(dst, depth-1) + } + dst = append(dst, ']') + n += len("]") + return dst, n, nil + default: + return dst, n, jsonwire.NewInvalidCharacterError(src[n:], "after array value (expecting ',' or ']')") + } + } +} + +// OutputOffset returns the current output byte offset. It gives the location +// of the next byte immediately after the most recently written token or value. +// The number of bytes actually written to the underlying [io.Writer] may be less +// than this offset due to internal buffering effects. +func (e *Encoder) OutputOffset() int64 { + return e.s.previousOffsetEnd() +} + +// AvailableBuffer returns a zero-length buffer with a possible non-zero capacity. +// This buffer is intended to be used to populate a [Value] +// being passed to an immediately succeeding [Encoder.WriteValue] call. +// +// Example usage: +// +// b := d.AvailableBuffer() +// b = append(b, '"') +// b = appendString(b, v) // append the string formatting of v +// b = append(b, '"') +// ... := d.WriteValue(b) +// +// It is the user's responsibility to ensure that the value is valid JSON. +func (e *Encoder) AvailableBuffer() []byte { + // NOTE: We don't return e.buf[len(e.buf):cap(e.buf)] since WriteValue would + // need to take special care to avoid mangling the data while reformatting. + // WriteValue can't easily identify whether the input Value aliases e.buf + // without using unsafe.Pointer. Thus, we just return a different buffer. + // Should this ever alias e.buf, we need to consider how it operates with + // the specialized performance optimization for bytes.Buffer. + n := 1 << bits.Len(uint(e.s.maxValue|63)) // fast approximation for max length + if cap(e.s.availBuffer) < n { + e.s.availBuffer = make([]byte, 0, n) + } + return e.s.availBuffer +} + +// StackDepth returns the depth of the state machine for written JSON data. +// Each level on the stack represents a nested JSON object or array. +// It is incremented whenever an [BeginObject] or [BeginArray] token is encountered +// and decremented whenever an [EndObject] or [EndArray] token is encountered. +// The depth is zero-indexed, where zero represents the top-level JSON value. +func (e *Encoder) StackDepth() int { + // NOTE: Keep in sync with Decoder.StackDepth. + return e.s.Tokens.Depth() - 1 +} + +// StackIndex returns information about the specified stack level. +// It must be a number between 0 and [Encoder.StackDepth], inclusive. +// For each level, it reports the kind: +// +// - 0 for a level of zero, +// - '{' for a level representing a JSON object, and +// - '[' for a level representing a JSON array. +// +// It also reports the length of that JSON object or array. +// Each name and value in a JSON object is counted separately, +// so the effective number of members would be half the length. +// A complete JSON object must have an even length. +func (e *Encoder) StackIndex(i int) (Kind, int64) { + // NOTE: Keep in sync with Decoder.StackIndex. + switch s := e.s.Tokens.index(i); { + case i > 0 && s.isObject(): + return '{', s.Length() + case i > 0 && s.isArray(): + return '[', s.Length() + default: + return 0, s.Length() + } +} + +// StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value. +func (e *Encoder) StackPointer() Pointer { + return Pointer(e.s.AppendStackPointer(nil, -1)) +} + +func (e *encoderState) AppendStackPointer(b []byte, where int) []byte { + e.Names.copyQuotedBuffer(e.Buf) + return e.state.appendStackPointer(b, where) +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/errors.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/errors.go new file mode 100644 index 000000000..1af86d5b6 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/errors.go @@ -0,0 +1,180 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "bytes" + "io" + "strconv" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +const errorPrefix = "jsontext: " + +type ioError struct { + action string // either "read" or "write" + err error +} + +func (e *ioError) Error() string { + return errorPrefix + e.action + " error: " + e.err.Error() +} +func (e *ioError) Unwrap() error { + return e.err +} + +// SyntacticError is a description of a syntactic error that occurred when +// encoding or decoding JSON according to the grammar. +// +// The contents of this error as produced by this package may change over time. +type SyntacticError struct { + requireKeyedLiterals + nonComparable + + // ByteOffset indicates that an error occurred after this byte offset. + ByteOffset int64 + // JSONPointer indicates that an error occurred within this JSON value + // as indicated using the JSON Pointer notation (see RFC 6901). + JSONPointer Pointer + + // Err is the underlying error. + Err error +} + +// wrapSyntacticError wraps an error and annotates it with a precise location +// using the provided [encoderState] or [decoderState]. +// If err is an [ioError] or [io.EOF], then it is not wrapped. +// +// It takes a relative offset pos that can be resolved into +// an absolute offset using state.offsetAt. +// +// It takes a where that specify how the JSON pointer is derived. +// If the underlying error is a [pointerSuffixError], +// then the suffix is appended to the derived pointer. +func wrapSyntacticError(state interface { + offsetAt(pos int) int64 + AppendStackPointer(b []byte, where int) []byte +}, err error, pos, where int) error { + if _, ok := err.(*ioError); err == io.EOF || ok { + return err + } + offset := state.offsetAt(pos) + ptr := state.AppendStackPointer(nil, where) + if serr, ok := err.(*pointerSuffixError); ok { + ptr = serr.appendPointer(ptr) + err = serr.error + } + if d, ok := state.(*decoderState); ok && err == errMismatchDelim { + where := "at start of value" + if len(d.Tokens.Stack) > 0 && d.Tokens.Last.Length() > 0 { + switch { + case d.Tokens.Last.isArray(): + where = "after array element (expecting ',' or ']')" + ptr = []byte(Pointer(ptr).Parent()) // problem is with parent array + case d.Tokens.Last.isObject(): + where = "after object value (expecting ',' or '}')" + ptr = []byte(Pointer(ptr).Parent()) // problem is with parent object + } + } + err = jsonwire.NewInvalidCharacterError(d.buf[pos:], where) + } + return &SyntacticError{ByteOffset: offset, JSONPointer: Pointer(ptr), Err: err} +} + +func (e *SyntacticError) Error() string { + pointer := e.JSONPointer + offset := e.ByteOffset + b := []byte(errorPrefix) + if e.Err != nil { + b = append(b, e.Err.Error()...) + if e.Err == ErrDuplicateName { + b = strconv.AppendQuote(append(b, ' '), pointer.LastToken()) + pointer = pointer.Parent() + offset = 0 // not useful to print offset for duplicate names + } + } else { + b = append(b, "syntactic error"...) + } + if pointer != "" { + b = strconv.AppendQuote(append(b, " within "...), jsonwire.TruncatePointer(string(pointer), 100)) + } + if offset > 0 { + b = strconv.AppendInt(append(b, " after offset "...), offset, 10) + } + return string(b) +} + +func (e *SyntacticError) Unwrap() error { + return e.Err +} + +// pointerSuffixError represents a JSON pointer suffix to be appended +// to [SyntacticError.JSONPointer]. It is an internal error type +// used within this package and does not appear in the public API. +// +// This type is primarily used to annotate errors in Encoder.WriteValue +// and Decoder.ReadValue with precise positions. +// At the time WriteValue or ReadValue is called, a JSON pointer to the +// upcoming value can be constructed using the Encoder/Decoder state. +// However, tracking pointers within values during normal operation +// would incur a performance penalty in the error-free case. +// +// To provide precise error locations without this overhead, +// the error is wrapped with object names or array indices +// as the call stack is popped when an error occurs. +// Since this happens in reverse order, pointerSuffixError holds +// the pointer in reverse and is only later reversed when appending to +// the pointer prefix. +// +// For example, if the encoder is at "/alpha/bravo/charlie" +// and an error occurs in WriteValue at "/xray/yankee/zulu", then +// the final pointer should be "/alpha/bravo/charlie/xray/yankee/zulu". +// +// As pointerSuffixError is populated during the error return path, +// it first contains "/zulu", then "/zulu/yankee", +// and finally "/zulu/yankee/xray". +// These tokens are reversed and concatenated to "/alpha/bravo/charlie" +// to form the full pointer. +type pointerSuffixError struct { + error + + // reversePointer is a JSON pointer, but with each token in reverse order. + reversePointer []byte +} + +// wrapWithObjectName wraps err with a JSON object name access, +// which must be a valid quoted JSON string. +func wrapWithObjectName(err error, quotedName []byte) error { + serr, _ := err.(*pointerSuffixError) + if serr == nil { + serr = &pointerSuffixError{error: err} + } + name := jsonwire.UnquoteMayCopy(quotedName, false) + serr.reversePointer = appendEscapePointerName(append(serr.reversePointer, '/'), name) + return serr +} + +// wrapWithArrayIndex wraps err with a JSON array index access. +func wrapWithArrayIndex(err error, index int64) error { + serr, _ := err.(*pointerSuffixError) + if serr == nil { + serr = &pointerSuffixError{error: err} + } + serr.reversePointer = strconv.AppendUint(append(serr.reversePointer, '/'), uint64(index), 10) + return serr +} + +// appendPointer appends the path encoded in e to the end of pointer. +func (e *pointerSuffixError) appendPointer(pointer []byte) []byte { + // Copy each token in reversePointer to the end of pointer in reverse order. + // Double reversal means that the appended suffix is now in forward order. + bi, bo := e.reversePointer, pointer + for len(bi) > 0 { + i := bytes.LastIndexByte(bi, '/') + bi, bo = bi[:i], append(bo, bi[i:]...) + } + return bo +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/export.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/export.go new file mode 100644 index 000000000..b30bb99ed --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/export.go @@ -0,0 +1,75 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "io" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" +) + +// Internal is for internal use only. +// This is exempt from the Go compatibility agreement. +var Internal exporter + +type exporter struct{} + +// Export exposes internal functionality from "jsontext" to "json". +// This cannot be dynamically called by other packages since +// they cannot obtain a reference to the internal.AllowInternalUse value. +func (exporter) Export(p *internal.NotForPublicUse) export { + if p != &internal.AllowInternalUse { + panic("unauthorized call to Export") + } + return export{} +} + +// The export type exposes functionality to packages with visibility to +// the internal.AllowInternalUse variable. The "json" package uses this +// to modify low-level state in the Encoder and Decoder types. +// It mutates the state directly instead of calling ReadToken or WriteToken +// since this is more performant. The public APIs need to track state to ensure +// that users are constructing a valid JSON value, but the "json" implementation +// guarantees that it emits valid JSON by the structure of the code itself. +type export struct{} + +// Encoder returns a pointer to the underlying encoderState. +func (export) Encoder(e *Encoder) *encoderState { return &e.s } + +// Decoder returns a pointer to the underlying decoderState. +func (export) Decoder(d *Decoder) *decoderState { return &d.s } + +func (export) GetBufferedEncoder(o ...Options) *Encoder { + return getBufferedEncoder(o...) +} +func (export) PutBufferedEncoder(e *Encoder) { + putBufferedEncoder(e) +} + +func (export) GetStreamingEncoder(w io.Writer, o ...Options) *Encoder { + return getStreamingEncoder(w, o...) +} +func (export) PutStreamingEncoder(e *Encoder) { + putStreamingEncoder(e) +} + +func (export) GetBufferedDecoder(b []byte, o ...Options) *Decoder { + return getBufferedDecoder(b, o...) +} +func (export) PutBufferedDecoder(d *Decoder) { + putBufferedDecoder(d) +} + +func (export) GetStreamingDecoder(r io.Reader, o ...Options) *Decoder { + return getStreamingDecoder(r, o...) +} +func (export) PutStreamingDecoder(d *Decoder) { + putStreamingDecoder(d) +} + +func (export) IsIOError(err error) bool { + _, ok := err.(*ioError) + return ok +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/options.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/options.go new file mode 100644 index 000000000..e973b58d6 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/options.go @@ -0,0 +1,302 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "strings" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +// Options configures [NewEncoder], [Encoder.Reset], [NewDecoder], +// and [Decoder.Reset] with specific features. +// Each function takes in a variadic list of options, where properties +// set in latter options override the value of previously set properties. +// +// There is a single Options type, which is used with both encoding and decoding. +// Some options affect both operations, while others only affect one operation: +// +// - [AllowDuplicateNames] affects encoding and decoding +// - [AllowInvalidUTF8] affects encoding and decoding +// - [EscapeForHTML] affects encoding only +// - [EscapeForJS] affects encoding only +// - [PreserveRawStrings] affects encoding only +// - [CanonicalizeRawInts] affects encoding only +// - [CanonicalizeRawFloats] affects encoding only +// - [ReorderRawObjects] affects encoding only +// - [SpaceAfterColon] affects encoding only +// - [SpaceAfterComma] affects encoding only +// - [Multiline] affects encoding only +// - [WithIndent] affects encoding only +// - [WithIndentPrefix] affects encoding only +// +// Options that do not affect a particular operation are ignored. +// +// The Options type is identical to [encoding/json.Options] and +// [encoding/json/v2.Options]. Options from the other packages may +// be passed to functionality in this package, but are ignored. +// Options from this package may be used with the other packages. +type Options = jsonopts.Options + +// AllowDuplicateNames specifies that JSON objects may contain +// duplicate member names. Disabling the duplicate name check may provide +// performance benefits, but breaks compliance with RFC 7493, section 2.3. +// The input or output will still be compliant with RFC 8259, +// which leaves the handling of duplicate names as unspecified behavior. +// +// This affects either encoding or decoding. +func AllowDuplicateNames(v bool) Options { + if v { + return jsonflags.AllowDuplicateNames | 1 + } else { + return jsonflags.AllowDuplicateNames | 0 + } +} + +// AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, +// which will be mangled as the Unicode replacement character, U+FFFD. +// This causes the encoder or decoder to break compliance with +// RFC 7493, section 2.1, and RFC 8259, section 8.1. +// +// This affects either encoding or decoding. +func AllowInvalidUTF8(v bool) Options { + if v { + return jsonflags.AllowInvalidUTF8 | 1 + } else { + return jsonflags.AllowInvalidUTF8 | 0 + } +} + +// EscapeForHTML specifies that '<', '>', and '&' characters within JSON strings +// should be escaped as a hexadecimal Unicode codepoint (e.g., \u003c) so that +// the output is safe to embed within HTML. +// +// This only affects encoding and is ignored when decoding. +func EscapeForHTML(v bool) Options { + if v { + return jsonflags.EscapeForHTML | 1 + } else { + return jsonflags.EscapeForHTML | 0 + } +} + +// EscapeForJS specifies that U+2028 and U+2029 characters within JSON strings +// should be escaped as a hexadecimal Unicode codepoint (e.g., \u2028) so that +// the output is valid to embed within JavaScript. See RFC 8259, section 12. +// +// This only affects encoding and is ignored when decoding. +func EscapeForJS(v bool) Options { + if v { + return jsonflags.EscapeForJS | 1 + } else { + return jsonflags.EscapeForJS | 0 + } +} + +// PreserveRawStrings specifies that when encoding a raw JSON string in a +// [Token] or [Value], pre-escaped sequences +// in a JSON string are preserved to the output. +// However, raw strings still respect [EscapeForHTML] and [EscapeForJS] +// such that the relevant characters are escaped. +// If [AllowInvalidUTF8] is enabled, bytes of invalid UTF-8 +// are preserved to the output. +// +// This only affects encoding and is ignored when decoding. +func PreserveRawStrings(v bool) Options { + if v { + return jsonflags.PreserveRawStrings | 1 + } else { + return jsonflags.PreserveRawStrings | 0 + } +} + +// CanonicalizeRawInts specifies that when encoding a raw JSON +// integer number (i.e., a number without a fraction and exponent) in a +// [Token] or [Value], the number is canonicalized +// according to RFC 8785, section 3.2.2.3. As a special case, +// the number -0 is canonicalized as 0. +// +// JSON numbers are treated as IEEE 754 double precision numbers. +// Any numbers with precision beyond what is representable by that form +// will lose their precision when canonicalized. For example, +// integer values beyond ±2⁵³ will lose their precision. +// For example, 1234567890123456789 is formatted as 1234567890123456800. +// +// This only affects encoding and is ignored when decoding. +func CanonicalizeRawInts(v bool) Options { + if v { + return jsonflags.CanonicalizeRawInts | 1 + } else { + return jsonflags.CanonicalizeRawInts | 0 + } +} + +// CanonicalizeRawFloats specifies that when encoding a raw JSON +// floating-point number (i.e., a number with a fraction or exponent) in a +// [Token] or [Value], the number is canonicalized +// according to RFC 8785, section 3.2.2.3. As a special case, +// the number -0 is canonicalized as 0. +// +// JSON numbers are treated as IEEE 754 double precision numbers. +// It is safe to canonicalize a serialized single precision number and +// parse it back as a single precision number and expect the same value. +// If a number exceeds ±1.7976931348623157e+308, which is the maximum +// finite number, then it saturated at that value and formatted as such. +// +// This only affects encoding and is ignored when decoding. +func CanonicalizeRawFloats(v bool) Options { + if v { + return jsonflags.CanonicalizeRawFloats | 1 + } else { + return jsonflags.CanonicalizeRawFloats | 0 + } +} + +// ReorderRawObjects specifies that when encoding a raw JSON object in a +// [Value], the object members are reordered according to +// RFC 8785, section 3.2.3. +// +// This only affects encoding and is ignored when decoding. +func ReorderRawObjects(v bool) Options { + if v { + return jsonflags.ReorderRawObjects | 1 + } else { + return jsonflags.ReorderRawObjects | 0 + } +} + +// SpaceAfterColon specifies that the JSON output should emit a space character +// after each colon separator following a JSON object name. +// If false, then no space character appears after the colon separator. +// +// This only affects encoding and is ignored when decoding. +func SpaceAfterColon(v bool) Options { + if v { + return jsonflags.SpaceAfterColon | 1 + } else { + return jsonflags.SpaceAfterColon | 0 + } +} + +// SpaceAfterComma specifies that the JSON output should emit a space character +// after each comma separator following a JSON object value or array element. +// If false, then no space character appears after the comma separator. +// +// This only affects encoding and is ignored when decoding. +func SpaceAfterComma(v bool) Options { + if v { + return jsonflags.SpaceAfterComma | 1 + } else { + return jsonflags.SpaceAfterComma | 0 + } +} + +// Multiline specifies that the JSON output should expand to multiple lines, +// where every JSON object member or JSON array element appears on +// a new, indented line according to the nesting depth. +// +// If [SpaceAfterColon] is not specified, then the default is true. +// If [SpaceAfterComma] is not specified, then the default is false. +// If [WithIndent] is not specified, then the default is "\t". +// +// If set to false, then the output is a single-line, +// where the only whitespace emitted is determined by the current +// values of [SpaceAfterColon] and [SpaceAfterComma]. +// +// This only affects encoding and is ignored when decoding. +func Multiline(v bool) Options { + if v { + return jsonflags.Multiline | 1 + } else { + return jsonflags.Multiline | 0 + } +} + +// WithIndent specifies that the encoder should emit multiline output +// where each element in a JSON object or array begins on a new, indented line +// beginning with the indent prefix (see [WithIndentPrefix]) +// followed by one or more copies of indent according to the nesting depth. +// The indent must only be composed of space or tab characters. +// +// If the intent to emit indented output without a preference for +// the particular indent string, then use [Multiline] instead. +// +// This only affects encoding and is ignored when decoding. +// Use of this option implies [Multiline] being set to true. +func WithIndent(indent string) Options { + // Fast-path: Return a constant for common indents, which avoids allocating. + // These are derived from analyzing the Go module proxy on 2023-07-01. + switch indent { + case "\t": + return jsonopts.Indent("\t") // ~14k usages + case " ": + return jsonopts.Indent(" ") // ~18k usages + case " ": + return jsonopts.Indent(" ") // ~1.7k usages + case " ": + return jsonopts.Indent(" ") // ~52k usages + case " ": + return jsonopts.Indent(" ") // ~12k usages + case "": + return jsonopts.Indent("") // ~1.5k usages + } + + // Otherwise, allocate for this unique value. + if s := strings.Trim(indent, " \t"); len(s) > 0 { + panic("json: invalid character " + jsonwire.QuoteRune(s) + " in indent") + } + return jsonopts.Indent(indent) +} + +// WithIndentPrefix specifies that the encoder should emit multiline output +// where each element in a JSON object or array begins on a new, indented line +// beginning with the indent prefix followed by one or more copies of indent +// (see [WithIndent]) according to the nesting depth. +// The prefix must only be composed of space or tab characters. +// +// This only affects encoding and is ignored when decoding. +// Use of this option implies [Multiline] being set to true. +func WithIndentPrefix(prefix string) Options { + if s := strings.Trim(prefix, " \t"); len(s) > 0 { + panic("json: invalid character " + jsonwire.QuoteRune(s) + " in indent prefix") + } + return jsonopts.IndentPrefix(prefix) +} + +/* +// TODO(https://go.dev/issue/56733): Implement WithByteLimit and WithDepthLimit. +// Remember to also update the "Security Considerations" section. + +// WithByteLimit sets a limit on the number of bytes of input or output bytes +// that may be consumed or produced for each top-level JSON value. +// If a [Decoder] or [Encoder] method call would need to consume/produce +// more than a total of n bytes to make progress on the top-level JSON value, +// then the call will report an error. +// Whitespace before and within the top-level value are counted against the limit. +// Whitespace after a top-level value are counted against the limit +// for the next top-level value. +// +// A non-positive limit is equivalent to no limit at all. +// If unspecified, the default limit is no limit at all. +// This affects either encoding or decoding. +func WithByteLimit(n int64) Options { + return jsonopts.ByteLimit(max(n, 0)) +} + +// WithDepthLimit sets a limit on the maximum depth of JSON nesting +// that may be consumed or produced for each top-level JSON value. +// If a [Decoder] or [Encoder] method call would need to consume or produce +// a depth greater than n to make progress on the top-level JSON value, +// then the call will report an error. +// +// A non-positive limit is equivalent to no limit at all. +// If unspecified, the default limit is 10000. +// This affects either encoding or decoding. +func WithDepthLimit(n int) Options { + return jsonopts.DepthLimit(max(n, 0)) +} +*/ diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/pools.go similarity index 64% rename from constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go rename to constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/pools.go index 60e93270f..63941baac 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/pools.go @@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package json +package jsontext import ( "bytes" "io" "math/bits" - "sort" "sync" ) @@ -40,16 +39,16 @@ type bufferStatistics struct { prevLen int // length of previous buffer } -func getBufferedEncoder(o EncodeOptions) *Encoder { +func getBufferedEncoder(opts ...Options) *Encoder { e := bufferedEncoderPool.Get().(*Encoder) - if e.buf == nil { + if e.s.Buf == nil { // Round up to nearest 2ⁿ to make best use of malloc size classes. // See runtime/sizeclasses.go on Go1.15. // Logical OR with 63 to ensure 64 as the minimum buffer size. - n := 1 << bits.Len(uint(e.bufStats.prevLen|63)) - e.buf = make([]byte, 0, n) + n := 1 << bits.Len(uint(e.s.bufStats.prevLen|63)) + e.s.Buf = make([]byte, 0, n) } - e.reset(e.buf[:0], nil, o) + e.s.reset(e.s.Buf[:0], nil, opts...) return e } func putBufferedEncoder(e *Encoder) { @@ -68,37 +67,37 @@ func putBufferedEncoder(e *Encoder) { // // See https://go.dev/issue/27735. switch { - case cap(e.buf) <= 4<<10: // always recycle buffers smaller than 4KiB - e.bufStats.strikes = 0 - case cap(e.buf)/4 <= len(e.buf): // at least 25% utilization - e.bufStats.strikes = 0 - case e.bufStats.strikes < 4: // at most 4 strikes - e.bufStats.strikes++ + case cap(e.s.Buf) <= 4<<10: // always recycle buffers smaller than 4KiB + e.s.bufStats.strikes = 0 + case cap(e.s.Buf)/4 <= len(e.s.Buf): // at least 25% utilization + e.s.bufStats.strikes = 0 + case e.s.bufStats.strikes < 4: // at most 4 strikes + e.s.bufStats.strikes++ default: // discard the buffer; too large and too often under-utilized - e.bufStats.strikes = 0 - e.bufStats.prevLen = len(e.buf) // heuristic for size to allocate next time - e.buf = nil + e.s.bufStats.strikes = 0 + e.s.bufStats.prevLen = len(e.s.Buf) // heuristic for size to allocate next time + e.s.Buf = nil } bufferedEncoderPool.Put(e) } -func getStreamingEncoder(w io.Writer, o EncodeOptions) *Encoder { +func getStreamingEncoder(w io.Writer, opts ...Options) *Encoder { if _, ok := w.(*bytes.Buffer); ok { e := bytesBufferEncoderPool.Get().(*Encoder) - e.reset(nil, w, o) // buffer taken from bytes.Buffer + e.s.reset(nil, w, opts...) // buffer taken from bytes.Buffer return e } else { e := streamingEncoderPool.Get().(*Encoder) - e.reset(e.buf[:0], w, o) // preserve existing buffer + e.s.reset(e.s.Buf[:0], w, opts...) // preserve existing buffer return e } } func putStreamingEncoder(e *Encoder) { - if _, ok := e.wr.(*bytes.Buffer); ok { + if _, ok := e.s.wr.(*bytes.Buffer); ok { bytesBufferEncoderPool.Put(e) } else { - if cap(e.buf) > 64<<10 { - e.buf = nil // avoid pinning arbitrarily large amounts of memory + if cap(e.s.Buf) > 64<<10 { + e.s.Buf = nil // avoid pinning arbitrarily large amounts of memory } streamingEncoderPool.Put(e) } @@ -119,64 +118,33 @@ var ( bytesBufferDecoderPool = bufferedDecoderPool ) -func getBufferedDecoder(b []byte, o DecodeOptions) *Decoder { +func getBufferedDecoder(b []byte, opts ...Options) *Decoder { d := bufferedDecoderPool.Get().(*Decoder) - d.reset(b, nil, o) + d.s.reset(b, nil, opts...) return d } func putBufferedDecoder(d *Decoder) { bufferedDecoderPool.Put(d) } -func getStreamingDecoder(r io.Reader, o DecodeOptions) *Decoder { +func getStreamingDecoder(r io.Reader, opts ...Options) *Decoder { if _, ok := r.(*bytes.Buffer); ok { d := bytesBufferDecoderPool.Get().(*Decoder) - d.reset(nil, r, o) // buffer taken from bytes.Buffer + d.s.reset(nil, r, opts...) // buffer taken from bytes.Buffer return d } else { d := streamingDecoderPool.Get().(*Decoder) - d.reset(d.buf[:0], r, o) // preserve existing buffer + d.s.reset(d.s.buf[:0], r, opts...) // preserve existing buffer return d } } func putStreamingDecoder(d *Decoder) { - if _, ok := d.rd.(*bytes.Buffer); ok { + if _, ok := d.s.rd.(*bytes.Buffer); ok { bytesBufferDecoderPool.Put(d) } else { - if cap(d.buf) > 64<<10 { - d.buf = nil // avoid pinning arbitrarily large amounts of memory + if cap(d.s.buf) > 64<<10 { + d.s.buf = nil // avoid pinning arbitrarily large amounts of memory } streamingDecoderPool.Put(d) } } - -var stringsPools = &sync.Pool{New: func() any { return new(stringSlice) }} - -type stringSlice []string - -// getStrings returns a non-nil pointer to a slice with length n. -func getStrings(n int) *stringSlice { - s := stringsPools.Get().(*stringSlice) - if cap(*s) < n { - *s = make([]string, n) - } - *s = (*s)[:n] - return s -} - -func putStrings(s *stringSlice) { - if cap(*s) > 1<<10 { - *s = nil // avoid pinning arbitrarily large amounts of memory - } - stringsPools.Put(s) -} - -// Sort sorts the string slice according to RFC 8785, section 3.2.3. -func (ss *stringSlice) Sort() { - // TODO(https://go.dev/issue/47619): Use slices.SortFunc instead. - sort.Sort(ss) -} - -func (ss *stringSlice) Len() int { return len(*ss) } -func (ss *stringSlice) Less(i, j int) bool { return lessUTF16((*ss)[i], (*ss)[j]) } -func (ss *stringSlice) Swap(i, j int) { (*ss)[i], (*ss)[j] = (*ss)[j], (*ss)[i] } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/quote.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/quote.go new file mode 100644 index 000000000..77897b43f --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/quote.go @@ -0,0 +1,39 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +// AppendQuote appends a double-quoted JSON string literal representing src +// to dst and returns the extended buffer. +// It uses the minimal string representation per RFC 8785, section 3.2.2.2. +// Invalid UTF-8 bytes are replaced with the Unicode replacement character +// and an error is returned at the end indicating the presence of invalid UTF-8. +// The dst must not overlap with the src. +func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error) { + dst, err := jsonwire.AppendQuote(dst, src, &jsonflags.Flags{}) + if err != nil { + err = &SyntacticError{Err: err} + } + return dst, err +} + +// AppendUnquote appends the decoded interpretation of src as a +// double-quoted JSON string literal to dst and returns the extended buffer. +// The input src must be a JSON string without any surrounding whitespace. +// Invalid UTF-8 bytes are replaced with the Unicode replacement character +// and an error is returned at the end indicating the presence of invalid UTF-8. +// Any trailing bytes after the JSON string literal results in an error. +// The dst must not overlap with the src. +func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error) { + dst, err := jsonwire.AppendUnquote(dst, src) + if err != nil { + err = &SyntacticError{Err: err} + } + return dst, err +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/state.go similarity index 63% rename from constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go rename to constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/state.go index ee14c753f..fdbfd5d3d 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/state.go @@ -2,81 +2,214 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package json +package jsontext import ( + "errors" + "iter" "math" "strconv" + "strings" + "unicode/utf8" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" ) +// ErrDuplicateName indicates that a JSON token could not be +// encoded or decoded because it results in a duplicate JSON object name. +// This error is directly wrapped within a [SyntacticError] when produced. +// +// The name of a duplicate JSON object member can be extracted as: +// +// err := ... +// var serr jsontext.SyntacticError +// if errors.As(err, &serr) && serr.Err == jsontext.ErrDuplicateName { +// ptr := serr.JSONPointer // JSON pointer to duplicate name +// name := ptr.LastToken() // duplicate name itself +// ... +// } +// +// This error is only returned if [AllowDuplicateNames] is false. +var ErrDuplicateName = errors.New("duplicate object member name") + +// ErrNonStringName indicates that a JSON token could not be +// encoded or decoded because it is not a string, +// as required for JSON object names according to RFC 8259, section 4. +// This error is directly wrapped within a [SyntacticError] when produced. +var ErrNonStringName = errors.New("object member name must be a string") + var ( - errMissingName = &SyntacticError{str: "missing string for object name"} - errMissingColon = &SyntacticError{str: "missing character ':' after object name"} - errMissingValue = &SyntacticError{str: "missing value after object name"} - errMissingComma = &SyntacticError{str: "missing character ',' after object or array value"} - errMismatchDelim = &SyntacticError{str: "mismatching structural token for object or array"} + errMissingValue = errors.New("missing value after object name") + errMismatchDelim = errors.New("mismatching structural token for object or array") + errMaxDepth = errors.New("exceeded max depth") + + errInvalidNamespace = errors.New("object namespace is in an invalid state") ) -const errInvalidNamespace = jsonError("object namespace is in an invalid state") +// Per RFC 8259, section 9, implementations may enforce a maximum depth. +// Such a limit is necessary to prevent stack overflows. +const maxNestingDepth = 10000 type state struct { - // tokens validates whether the next token kind is valid. - tokens stateMachine + // Tokens validates whether the next token kind is valid. + Tokens stateMachine - // names is a stack of object names. - // Not used if AllowDuplicateNames is true. - names objectNameStack + // Names is a stack of object names. + Names objectNameStack - // namespaces is a stack of object namespaces. + // Namespaces is a stack of object namespaces. // For performance reasons, Encoder or Decoder may not update this // if Marshal or Unmarshal is able to track names in a more efficient way. // See makeMapArshaler and makeStructArshaler. // Not used if AllowDuplicateNames is true. - namespaces objectNamespaceStack + Namespaces objectNamespaceStack +} + +// needObjectValue reports whether the next token should be an object value. +// This method is used by [wrapSyntacticError]. +func (s *state) needObjectValue() bool { + return s.Tokens.Last.needObjectValue() } func (s *state) reset() { - s.tokens.reset() - s.names.reset() - s.namespaces.reset() + s.Tokens.reset() + s.Names.reset() + s.Namespaces.reset() +} + +// Pointer is a JSON Pointer (RFC 6901) that references a particular JSON value +// relative to the root of the top-level JSON value. +// +// A Pointer is a slash-separated list of tokens, where each token is +// either a JSON object name or an index to a JSON array element +// encoded as a base-10 integer value. +// It is impossible to distinguish between an array index and an object name +// (that happens to be an base-10 encoded integer) without also knowing +// the structure of the top-level JSON value that the pointer refers to. +// +// There is exactly one representation of a pointer to a particular value, +// so comparability of Pointer values is equivalent to checking whether +// they both point to the exact same value. +type Pointer string + +// IsValid reports whether p is a valid JSON Pointer according to RFC 6901. +// Note that the concatenation of two valid pointers produces a valid pointer. +func (p Pointer) IsValid() bool { + for i, r := range p { + switch { + case r == '~' && (i+1 == len(p) || (p[i+1] != '0' && p[i+1] != '1')): + return false // invalid escape + case r == '\ufffd' && !strings.HasPrefix(string(p[i:]), "\ufffd"): + return false // invalid UTF-8 + } + } + return len(p) == 0 || p[0] == '/' +} + +// Contains reports whether the JSON value that p points to +// is equal to or contains the JSON value that pc points to. +func (p Pointer) Contains(pc Pointer) bool { + // Invariant: len(p) <= len(pc) if p.Contains(pc) + suffix, ok := strings.CutPrefix(string(pc), string(p)) + return ok && (suffix == "" || suffix[0] == '/') +} + +// Parent strips off the last token and returns the remaining pointer. +// The parent of an empty p is an empty string. +func (p Pointer) Parent() Pointer { + return p[:max(strings.LastIndexByte(string(p), '/'), 0)] +} + +// LastToken returns the last token in the pointer. +// The last token of an empty p is an empty string. +func (p Pointer) LastToken() string { + last := p[max(strings.LastIndexByte(string(p), '/'), 0):] + return unescapePointerToken(strings.TrimPrefix(string(last), "/")) +} + +// AppendToken appends a token to the end of p and returns the full pointer. +func (p Pointer) AppendToken(tok string) Pointer { + return Pointer(appendEscapePointerName([]byte(p+"/"), tok)) +} + +// TODO: Add Pointer.AppendTokens, +// but should this take in a ...string or an iter.Seq[string]? + +// Tokens returns an iterator over the reference tokens in the JSON pointer, +// starting from the first token until the last token (unless stopped early). +func (p Pointer) Tokens() iter.Seq[string] { + return func(yield func(string) bool) { + for len(p) > 0 { + p = Pointer(strings.TrimPrefix(string(p), "/")) + i := min(uint(strings.IndexByte(string(p), '/')), uint(len(p))) + if !yield(unescapePointerToken(string(p)[:i])) { + return + } + p = p[i:] + } + } +} + +func unescapePointerToken(token string) string { + if strings.Contains(token, "~") { + // Per RFC 6901, section 3, unescape '~' and '/' characters. + token = strings.ReplaceAll(token, "~1", "/") + token = strings.ReplaceAll(token, "~0", "~") + } + return token } // appendStackPointer appends a JSON Pointer (RFC 6901) to the current value. -// The returned pointer is only accurate if s.names is populated, -// otherwise it uses the numeric index as the object member name. +// +// - If where is -1, then it points to the previously processed token. +// +// - If where is 0, then it points to the parent JSON object or array, +// or an object member if in-between an object member key and value. +// This is useful when the position is ambiguous whether +// we are interested in the previous or next token, or +// when we are uncertain whether the next token +// continues or terminates the current object or array. +// +// - If where is +1, then it points to the next expected value, +// assuming that it continues the current JSON object or array. +// As a special case, if the next token is a JSON object name, +// then it points to the parent JSON object. // // Invariant: Must call s.names.copyQuotedBuffer beforehand. -func (s state) appendStackPointer(b []byte) []byte { +func (s state) appendStackPointer(b []byte, where int) []byte { var objectDepth int - for i := 1; i < s.tokens.depth(); i++ { - e := s.tokens.index(i) - if e.length() == 0 { - break // empty object or array + for i := 1; i < s.Tokens.Depth(); i++ { + e := s.Tokens.index(i) + arrayDelta := -1 // by default point to previous array element + if isLast := i == s.Tokens.Depth()-1; isLast { + switch { + case where < 0 && e.Length() == 0 || where == 0 && !e.needObjectValue() || where > 0 && e.NeedObjectName(): + return b + case where > 0 && e.isArray(): + arrayDelta = 0 // point to next array element + } } - b = append(b, '/') switch { case e.isObject(): - if objectDepth < s.names.length() { - for _, c := range s.names.getUnquoted(objectDepth) { - // Per RFC 6901, section 3, escape '~' and '/' characters. - switch c { - case '~': - b = append(b, "~0"...) - case '/': - b = append(b, "~1"...) - default: - b = append(b, c) - } - } - } else { - // Since the names stack is unpopulated, the name is unknown. - // As a best-effort replacement, use the numeric member index. - // While inaccurate, it produces a syntactically valid pointer. - b = strconv.AppendUint(b, uint64((e.length()-1)/2), 10) - } + b = appendEscapePointerName(append(b, '/'), s.Names.getUnquoted(objectDepth)) objectDepth++ case e.isArray(): - b = strconv.AppendUint(b, uint64(e.length()-1), 10) + b = strconv.AppendUint(append(b, '/'), uint64(e.Length()+int64(arrayDelta)), 10) + } + } + return b +} + +func appendEscapePointerName[Bytes ~[]byte | ~string](b []byte, name Bytes) []byte { + for _, r := range string(name) { + // Per RFC 6901, section 3, escape '~' and '/' characters. + switch r { + case '~': + b = append(b, "~0"...) + case '/': + b = append(b, "~1"...) + default: + b = utf8.AppendRune(b, r) } } return b @@ -92,54 +225,54 @@ func (s state) appendStackPointer(b []byte) []byte { // The top-level virtual JSON array is special in that it doesn't require commas // between each JSON value. // -// For performance, most methods are carefully written to be inlineable. +// For performance, most methods are carefully written to be inlinable. // The zero value is a valid state machine ready for use. type stateMachine struct { - stack []stateEntry - last stateEntry + Stack []stateEntry + Last stateEntry } // reset resets the state machine. // The machine always starts with a minimum depth of 1. func (m *stateMachine) reset() { - m.stack = m.stack[:0] - if cap(m.stack) > 1<<10 { - m.stack = nil + m.Stack = m.Stack[:0] + if cap(m.Stack) > 1<<10 { + m.Stack = nil } - m.last = stateTypeArray + m.Last = stateTypeArray } -// depth is the current nested depth of JSON objects and arrays. +// Depth is the current nested depth of JSON objects and arrays. // It is one-indexed (i.e., top-level values have a depth of 1). -func (m stateMachine) depth() int { - return len(m.stack) + 1 +func (m stateMachine) Depth() int { + return len(m.Stack) + 1 } // index returns a reference to the ith entry. // It is only valid until the next push method call. func (m *stateMachine) index(i int) *stateEntry { - if i == len(m.stack) { - return &m.last + if i == len(m.Stack) { + return &m.Last } - return &m.stack[i] + return &m.Stack[i] } -// depthLength reports the current nested depth and +// DepthLength reports the current nested depth and // the length of the last JSON object or array. -func (m stateMachine) depthLength() (int, int) { - return m.depth(), m.last.length() +func (m stateMachine) DepthLength() (int, int64) { + return m.Depth(), m.Last.Length() } // appendLiteral appends a JSON literal as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendLiteral() error { switch { - case m.last.needObjectName(): - return errMissingName - case !m.last.isValidNamespace(): + case m.Last.NeedObjectName(): + return ErrNonStringName + case !m.Last.isValidNamespace(): return errInvalidNamespace default: - m.last.increment() + m.Last.Increment() return nil } } @@ -148,10 +281,10 @@ func (m *stateMachine) appendLiteral() error { // If an error is returned, the state is not mutated. func (m *stateMachine) appendString() error { switch { - case !m.last.isValidNamespace(): + case !m.Last.isValidNamespace(): return errInvalidNamespace default: - m.last.increment() + m.Last.Increment() return nil } } @@ -162,18 +295,20 @@ func (m *stateMachine) appendNumber() error { return m.appendLiteral() } -// pushObject appends a JSON start object token as next in the sequence. +// pushObject appends a JSON begin object token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushObject() error { switch { - case m.last.needObjectName(): - return errMissingName - case !m.last.isValidNamespace(): + case m.Last.NeedObjectName(): + return ErrNonStringName + case !m.Last.isValidNamespace(): return errInvalidNamespace + case len(m.Stack) == maxNestingDepth: + return errMaxDepth default: - m.last.increment() - m.stack = append(m.stack, m.last) - m.last = stateTypeObject + m.Last.Increment() + m.Stack = append(m.Stack, m.Last) + m.Last = stateTypeObject return nil } } @@ -182,31 +317,33 @@ func (m *stateMachine) pushObject() error { // If an error is returned, the state is not mutated. func (m *stateMachine) popObject() error { switch { - case !m.last.isObject(): + case !m.Last.isObject(): return errMismatchDelim - case m.last.needObjectValue(): + case m.Last.needObjectValue(): return errMissingValue - case !m.last.isValidNamespace(): + case !m.Last.isValidNamespace(): return errInvalidNamespace default: - m.last = m.stack[len(m.stack)-1] - m.stack = m.stack[:len(m.stack)-1] + m.Last = m.Stack[len(m.Stack)-1] + m.Stack = m.Stack[:len(m.Stack)-1] return nil } } -// pushArray appends a JSON start array token as next in the sequence. +// pushArray appends a JSON begin array token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushArray() error { switch { - case m.last.needObjectName(): - return errMissingName - case !m.last.isValidNamespace(): + case m.Last.NeedObjectName(): + return ErrNonStringName + case !m.Last.isValidNamespace(): return errInvalidNamespace + case len(m.Stack) == maxNestingDepth: + return errMaxDepth default: - m.last.increment() - m.stack = append(m.stack, m.last) - m.last = stateTypeArray + m.Last.Increment() + m.Stack = append(m.Stack, m.Last) + m.Last = stateTypeArray return nil } } @@ -215,43 +352,43 @@ func (m *stateMachine) pushArray() error { // If an error is returned, the state is not mutated. func (m *stateMachine) popArray() error { switch { - case !m.last.isArray() || len(m.stack) == 0: // forbid popping top-level virtual JSON array + case !m.Last.isArray() || len(m.Stack) == 0: // forbid popping top-level virtual JSON array return errMismatchDelim - case !m.last.isValidNamespace(): + case !m.Last.isValidNamespace(): return errInvalidNamespace default: - m.last = m.stack[len(m.stack)-1] - m.stack = m.stack[:len(m.stack)-1] + m.Last = m.Stack[len(m.Stack)-1] + m.Stack = m.Stack[:len(m.Stack)-1] return nil } } -// needIndent reports whether indent whitespace should be injected. +// NeedIndent reports whether indent whitespace should be injected. // A zero value means that no whitespace should be injected. // A positive value means '\n', indentPrefix, and (n-1) copies of indentBody // should be appended to the output immediately before the next token. -func (m stateMachine) needIndent(next Kind) (n int) { +func (m stateMachine) NeedIndent(next Kind) (n int) { willEnd := next == '}' || next == ']' switch { - case m.depth() == 1: + case m.Depth() == 1: return 0 // top-level values are never indented - case m.last.length() == 0 && willEnd: + case m.Last.Length() == 0 && willEnd: return 0 // an empty object or array is never indented - case m.last.length() == 0 || m.last.needImplicitComma(next): - return m.depth() + case m.Last.Length() == 0 || m.Last.needImplicitComma(next): + return m.Depth() case willEnd: - return m.depth() - 1 + return m.Depth() - 1 default: return 0 } } -// mayAppendDelim appends a colon or comma that may precede the next token. -func (m stateMachine) mayAppendDelim(b []byte, next Kind) []byte { +// MayAppendDelim appends a colon or comma that may precede the next token. +func (m stateMachine) MayAppendDelim(b []byte, next Kind) []byte { switch { - case m.last.needImplicitColon(): + case m.Last.needImplicitColon(): return append(b, ':') - case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values + case m.Last.needImplicitComma(next) && len(m.Stack) != 0: // comma not needed for top-level values return append(b, ',') default: return b @@ -263,39 +400,24 @@ func (m stateMachine) mayAppendDelim(b []byte, next Kind) []byte { // A zero value means no delimiter should be emitted. func (m stateMachine) needDelim(next Kind) (delim byte) { switch { - case m.last.needImplicitColon(): + case m.Last.needImplicitColon(): return ':' - case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values + case m.Last.needImplicitComma(next) && len(m.Stack) != 0: // comma not needed for top-level values return ',' default: return 0 } } -// checkDelim reports whether the specified delimiter should be there given -// the kind of the next token that appears immediately afterwards. -func (m stateMachine) checkDelim(delim byte, next Kind) error { - switch needDelim := m.needDelim(next); { - case needDelim == delim: - return nil - case needDelim == ':': - return errMissingColon - case needDelim == ',': - return errMissingComma - default: - return newInvalidCharacterError([]byte{delim}, "before next token") - } -} - -// invalidateDisabledNamespaces marks all disabled namespaces as invalid. +// InvalidateDisabledNamespaces marks all disabled namespaces as invalid. // // For efficiency, Marshal and Unmarshal may disable namespaces since there are // more efficient ways to track duplicate names. However, if an error occurs, // the namespaces in Encoder or Decoder will be left in an inconsistent state. // Mark the namespaces as invalid so that future method calls on // Encoder or Decoder will return an error. -func (m *stateMachine) invalidateDisabledNamespaces() { - for i := 0; i < m.depth(); i++ { +func (m *stateMachine) InvalidateDisabledNamespaces() { + for i := range m.Depth() { e := m.index(i) if !e.isActiveNamespace() { e.invalidateNamespace() @@ -329,10 +451,10 @@ const ( stateCountEven stateEntry = 0x0000_0000_0000_0000 ) -// length reports the number of elements in the JSON object or array. +// Length reports the number of elements in the JSON object or array. // Each name and value in an object entry is treated as a separate element. -func (e stateEntry) length() int { - return int(e & stateCountMask) +func (e stateEntry) Length() int64 { + return int64(e & stateCountMask) } // isObject reports whether this is a JSON object. @@ -345,9 +467,9 @@ func (e stateEntry) isArray() bool { return e&stateTypeMask == stateTypeArray } -// needObjectName reports whether the next token must be a JSON string, +// NeedObjectName reports whether the next token must be a JSON string, // which is necessary for JSON object names. -func (e stateEntry) needObjectName() bool { +func (e stateEntry) NeedObjectName() bool { return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountEven } @@ -367,13 +489,13 @@ func (e stateEntry) needObjectValue() bool { // which always occurs after a value in a JSON object or array // before the next value (or name). func (e stateEntry) needImplicitComma(next Kind) bool { - return !e.needObjectValue() && e.length() > 0 && next != '}' && next != ']' + return !e.needObjectValue() && e.Length() > 0 && next != '}' && next != ']' } -// increment increments the number of elements for the current object or array. +// Increment increments the number of elements for the current object or array. // This assumes that overflow won't practically be an issue since // 1< 0 { startOffset = ns.offsets[i-1] } - if n := consumeSimpleString(quotedName); n > 0 { + if n := jsonwire.ConsumeSimpleString(quotedName); n > 0 { ns.unquotedNames = append(ns.unquotedNames[:startOffset], quotedName[len(`"`):n-len(`"`)]...) } else { - ns.unquotedNames, _ = unescapeString(ns.unquotedNames[:startOffset], quotedName) + ns.unquotedNames, _ = jsonwire.AppendUnquote(ns.unquotedNames[:startOffset], quotedName) } ns.offsets[i] = len(ns.unquotedNames) } @@ -565,14 +687,14 @@ func (nss *objectNamespaceStack) reset() { func (nss *objectNamespaceStack) push() { if cap(*nss) > len(*nss) { *nss = (*nss)[:len(*nss)+1] - nss.last().reset() + nss.Last().reset() } else { *nss = append(*nss, objectNamespace{}) } } -// last returns a pointer to the last JSON object namespace. -func (nss objectNamespaceStack) last() *objectNamespace { +// Last returns a pointer to the last JSON object namespace. +func (nss objectNamespaceStack) Last() *objectNamespace { return &nss[len(nss)-1] } @@ -641,13 +763,13 @@ func (ns *objectNamespace) insertQuoted(name []byte, isVerbatim bool) bool { } return ns.insert(name, !isVerbatim) } -func (ns *objectNamespace) insertUnquoted(name []byte) bool { +func (ns *objectNamespace) InsertUnquoted(name []byte) bool { return ns.insert(name, false) } func (ns *objectNamespace) insert(name []byte, quoted bool) bool { var allNames []byte if quoted { - allNames, _ = unescapeString(ns.allUnquotedNames, name) + allNames, _ = jsonwire.AppendUnquote(ns.allUnquotedNames, name) } else { allNames = append(ns.allUnquotedNames, name...) } @@ -702,46 +824,3 @@ func (ns *objectNamespace) removeLast() { ns.allUnquotedNames = ns.allUnquotedNames[:ns.endOffsets[ns.length()-1]] } } - -type uintSet64 uint64 - -func (s uintSet64) has(i uint) bool { return s&(1< 0 } -func (s *uintSet64) set(i uint) { *s |= 1 << i } - -// uintSet is a set of unsigned integers. -// It is optimized for most integers being close to zero. -type uintSet struct { - lo uintSet64 - hi []uintSet64 -} - -// has reports whether i is in the set. -func (s *uintSet) has(i uint) bool { - if i < 64 { - return s.lo.has(i) - } else { - i -= 64 - iHi, iLo := int(i/64), i%64 - return iHi < len(s.hi) && s.hi[iHi].has(iLo) - } -} - -// insert inserts i into the set and reports whether it was the first insertion. -func (s *uintSet) insert(i uint) bool { - // TODO: Make this inlineable at least for the lower 64-bit case. - if i < 64 { - has := s.lo.has(i) - s.lo.set(i) - return !has - } else { - i -= 64 - iHi, iLo := int(i/64), i%64 - if iHi >= len(s.hi) { - s.hi = append(s.hi, make([]uintSet64, iHi+1-len(s.hi))...) - s.hi = s.hi[:cap(s.hi)] - } - has := s.hi[iHi].has(iLo) - s.hi[iHi].set(iLo) - return !has - } -} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/token.go similarity index 87% rename from constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go rename to constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/token.go index 9acba7dad..ea8c30eb5 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/token.go @@ -2,11 +2,16 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package json +package jsontext import ( + "bytes" + "errors" "math" "strconv" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" ) // NOTE: Token is analogous to v1 json.Token. @@ -17,17 +22,19 @@ const ( maxUint64 = math.MaxUint64 minUint64 = 0 // for consistency and readability purposes - invalidTokenPanic = "invalid json.Token; it has been voided by a subsequent json.Decoder call" + invalidTokenPanic = "invalid jsontext.Token; it has been voided by a subsequent json.Decoder call" ) +var errInvalidToken = errors.New("invalid jsontext.Token") + // Token represents a lexical JSON token, which may be one of the following: // - a JSON literal (i.e., null, true, or false) // - a JSON string (e.g., "hello, world!") // - a JSON number (e.g., 123.456) -// - a start or end delimiter for a JSON object (i.e., { or } ) -// - a start or end delimiter for a JSON array (i.e., [ or ] ) +// - a begin or end delimiter for a JSON object (i.e., { or } ) +// - a begin or end delimiter for a JSON array (i.e., [ or ] ) // -// A Token cannot represent entire array or object values, while a RawValue can. +// A Token cannot represent entire array or object values, while a [Value] can. // There is no Token to represent commas and colons since // these structural tokens can be inferred from the surrounding context. type Token struct { @@ -87,10 +94,10 @@ var ( False Token = rawToken("false") True Token = rawToken("true") - ObjectStart Token = rawToken("{") - ObjectEnd Token = rawToken("}") - ArrayStart Token = rawToken("[") - ArrayEnd Token = rawToken("]") + BeginObject Token = rawToken("{") + EndObject Token = rawToken("}") + BeginArray Token = rawToken("[") + EndArray Token = rawToken("]") zeroString Token = rawToken(`""`) zeroNumber Token = rawToken(`0`) @@ -156,7 +163,7 @@ func Uint(n uint64) Token { } // Clone makes a copy of the Token such that its value remains valid -// even after a subsequent Decoder.Read call. +// even after a subsequent [Decoder.Read] call. func (t Token) Clone() Token { // TODO: Allow caller to avoid any allocations? if raw := t.raw; raw != nil { @@ -169,22 +176,21 @@ func (t Token) Clone() Token { return False case True.raw: return True - case ObjectStart.raw: - return ObjectStart - case ObjectEnd.raw: - return ObjectEnd - case ArrayStart.raw: - return ArrayStart - case ArrayEnd.raw: - return ArrayEnd + case BeginObject.raw: + return BeginObject + case EndObject.raw: + return EndObject + case BeginArray.raw: + return BeginArray + case EndArray.raw: + return EndArray } } if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } - // TODO(https://go.dev/issue/45038): Use bytes.Clone. - buf := append([]byte(nil), raw.previousBuffer()...) + buf := bytes.Clone(raw.previousBuffer()) return Token{raw: &decodeBuffer{buf: buf, prevStart: 0, prevEnd: len(buf)}} } return t @@ -205,20 +211,20 @@ func (t Token) Bool() bool { // appendString appends a JSON string to dst and returns it. // It panics if t is not a JSON string. -func (t Token) appendString(dst []byte, validateUTF8, preserveRaw bool, escapeRune func(rune) bool) ([]byte, error) { +func (t Token) appendString(dst []byte, flags *jsonflags.Flags) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw string value. buf := raw.previousBuffer() if Kind(buf[0]) == '"' { - if escapeRune == nil && consumeSimpleString(buf) == len(buf) { + if jsonwire.ConsumeSimpleString(buf) == len(buf) { return append(dst, buf...), nil } - dst, _, err := reformatString(dst, buf, validateUTF8, preserveRaw, escapeRune) + dst, _, err := jsonwire.ReformatString(dst, buf, flags) return dst, err } } else if len(t.str) != 0 && t.num == 0 { // Handle exact string value. - return appendString(dst, t.str, validateUTF8, escapeRune) + return jsonwire.AppendQuote(dst, t.str, flags) } panic("invalid JSON token kind: " + t.Kind().String()) @@ -244,9 +250,9 @@ func (t Token) string() (string, []byte) { } buf := raw.previousBuffer() if buf[0] == '"' { - // TODO: Preserve valueFlags in Token? - isVerbatim := consumeSimpleString(buf) == len(buf) - return "", unescapeStringMayCopy(buf, isVerbatim) + // TODO: Preserve ValueFlags in Token? + isVerbatim := jsonwire.ConsumeSimpleString(buf) == len(buf) + return "", jsonwire.UnquoteMayCopy(buf, isVerbatim) } // Handle tokens that are not JSON strings for fmt.Stringer. return "", buf @@ -258,34 +264,31 @@ func (t Token) string() (string, []byte) { if t.num > 0 { switch t.str[0] { case 'f': - return string(appendNumber(nil, math.Float64frombits(t.num), 64)), nil + return string(jsonwire.AppendFloat(nil, math.Float64frombits(t.num), 64)), nil case 'i': return strconv.FormatInt(int64(t.num), 10), nil case 'u': return strconv.FormatUint(uint64(t.num), 10), nil } } - return "", nil + return "", nil } // appendNumber appends a JSON number to dst and returns it. // It panics if t is not a JSON number. -func (t Token) appendNumber(dst []byte, canonicalize bool) ([]byte, error) { +func (t Token) appendNumber(dst []byte, flags *jsonflags.Flags) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw number value. buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { - if !canonicalize { - return append(dst, buf...), nil - } - dst, _, err := reformatNumber(dst, buf, canonicalize) + dst, _, err := jsonwire.ReformatNumber(dst, buf, flags) return dst, err } } else if t.num != 0 { // Handle exact number value. switch t.str[0] { case 'f': - return appendNumber(dst, math.Float64frombits(t.num), 64), nil + return jsonwire.AppendFloat(dst, math.Float64frombits(t.num), 64), nil case 'i': return strconv.AppendInt(dst, int64(t.num), 10), nil case 'u': @@ -308,7 +311,7 @@ func (t Token) Float() float64 { } buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { - fv, _ := parseFloat(buf, 64) + fv, _ := jsonwire.ParseFloat(buf, 64) return fv } } else if t.num != 0 { @@ -354,7 +357,7 @@ func (t Token) Int() int64 { if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } - if numAbs, ok := parseDecUint(buf); ok { + if numAbs, ok := jsonwire.ParseUint(buf); ok { if neg { if numAbs > -minInt64 { return minInt64 @@ -415,7 +418,7 @@ func (t Token) Uint() uint64 { if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } - if num, ok := parseDecUint(buf); ok { + if num, ok := jsonwire.ParseUint(buf); ok { if neg { return minUint64 } @@ -476,9 +479,9 @@ func (t Token) Kind() Kind { // - 't': true // - '"': string // - '0': number -// - '{': object start +// - '{': object begin // - '}': object end -// - '[': array start +// - '[': array begin // - ']': array end // // An invalid kind is usually represented using 0, @@ -509,7 +512,7 @@ func (k Kind) String() string { case ']': return "]" default: - return "" + return "" } } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/value.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/value.go new file mode 100644 index 000000000..3ea05d3a0 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext/value.go @@ -0,0 +1,393 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsontext + +import ( + "bytes" + "errors" + "io" + "slices" + "sync" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire" +) + +// NOTE: Value is analogous to v1 json.RawMessage. + +// AppendFormat formats the JSON value in src and appends it to dst +// according to the specified options. +// See [Value.Format] for more details about the formatting behavior. +// +// The dst and src may overlap. +// If an error is reported, then the entirety of src is appended to dst. +func AppendFormat(dst, src []byte, opts ...Options) ([]byte, error) { + e := getBufferedEncoder(opts...) + defer putBufferedEncoder(e) + e.s.Flags.Set(jsonflags.OmitTopLevelNewline | 1) + if err := e.s.WriteValue(src); err != nil { + return append(dst, src...), err + } + return append(dst, e.s.Buf...), nil +} + +// Value represents a single raw JSON value, which may be one of the following: +// - a JSON literal (i.e., null, true, or false) +// - a JSON string (e.g., "hello, world!") +// - a JSON number (e.g., 123.456) +// - an entire JSON object (e.g., {"fizz":"buzz"} ) +// - an entire JSON array (e.g., [1,2,3] ) +// +// Value can represent entire array or object values, while [Token] cannot. +// Value may contain leading and/or trailing whitespace. +type Value []byte + +// Clone returns a copy of v. +func (v Value) Clone() Value { + return bytes.Clone(v) +} + +// String returns the string formatting of v. +func (v Value) String() string { + if v == nil { + return "null" + } + return string(v) +} + +// IsValid reports whether the raw JSON value is syntactically valid +// according to the specified options. +// +// By default (if no options are specified), it validates according to RFC 7493. +// It verifies whether the input is properly encoded as UTF-8, +// that escape sequences within strings decode to valid Unicode codepoints, and +// that all names in each object are unique. +// It does not verify whether numbers are representable within the limits +// of any common numeric type (e.g., float64, int64, or uint64). +// +// Relevant options include: +// - [AllowDuplicateNames] +// - [AllowInvalidUTF8] +// +// All other options are ignored. +func (v Value) IsValid(opts ...Options) bool { + // TODO: Document support for [WithByteLimit] and [WithDepthLimit]. + d := getBufferedDecoder(v, opts...) + defer putBufferedDecoder(d) + _, errVal := d.ReadValue() + _, errEOF := d.ReadToken() + return errVal == nil && errEOF == io.EOF +} + +// Format formats the raw JSON value in place. +// +// By default (if no options are specified), it validates according to RFC 7493 +// and produces the minimal JSON representation, where +// all whitespace is elided and JSON strings use the shortest encoding. +// +// Relevant options include: +// - [AllowDuplicateNames] +// - [AllowInvalidUTF8] +// - [EscapeForHTML] +// - [EscapeForJS] +// - [PreserveRawStrings] +// - [CanonicalizeRawInts] +// - [CanonicalizeRawFloats] +// - [ReorderRawObjects] +// - [SpaceAfterColon] +// - [SpaceAfterComma] +// - [Multiline] +// - [WithIndent] +// - [WithIndentPrefix] +// +// All other options are ignored. +// +// It is guaranteed to succeed if the value is valid according to the same options. +// If the value is already formatted, then the buffer is not mutated. +func (v *Value) Format(opts ...Options) error { + // TODO: Document support for [WithByteLimit] and [WithDepthLimit]. + return v.format(opts, nil) +} + +// format accepts two []Options to avoid the allocation appending them together. +// It is equivalent to v.Format(append(opts1, opts2...)...). +func (v *Value) format(opts1, opts2 []Options) error { + e := getBufferedEncoder(opts1...) + defer putBufferedEncoder(e) + e.s.Join(opts2...) + e.s.Flags.Set(jsonflags.OmitTopLevelNewline | 1) + if err := e.s.WriteValue(*v); err != nil { + return err + } + if !bytes.Equal(*v, e.s.Buf) { + *v = append((*v)[:0], e.s.Buf...) + } + return nil +} + +// Compact removes all whitespace from the raw JSON value. +// +// It does not reformat JSON strings or numbers to use any other representation. +// To maximize the set of JSON values that can be formatted, +// this permits values with duplicate names and invalid UTF-8. +// +// Compact is equivalent to calling [Value.Format] with the following options: +// - [AllowDuplicateNames](true) +// - [AllowInvalidUTF8](true) +// - [PreserveRawStrings](true) +// +// Any options specified by the caller are applied after the initial set +// and may deliberately override prior options. +func (v *Value) Compact(opts ...Options) error { + return v.format([]Options{ + AllowDuplicateNames(true), + AllowInvalidUTF8(true), + PreserveRawStrings(true), + }, opts) +} + +// Indent reformats the whitespace in the raw JSON value so that each element +// in a JSON object or array begins on a indented line according to the nesting. +// +// It does not reformat JSON strings or numbers to use any other representation. +// To maximize the set of JSON values that can be formatted, +// this permits values with duplicate names and invalid UTF-8. +// +// Indent is equivalent to calling [Value.Format] with the following options: +// - [AllowDuplicateNames](true) +// - [AllowInvalidUTF8](true) +// - [PreserveRawStrings](true) +// - [Multiline](true) +// +// Any options specified by the caller are applied after the initial set +// and may deliberately override prior options. +func (v *Value) Indent(opts ...Options) error { + return v.format([]Options{ + AllowDuplicateNames(true), + AllowInvalidUTF8(true), + PreserveRawStrings(true), + Multiline(true), + }, opts) +} + +// Canonicalize canonicalizes the raw JSON value according to the +// JSON Canonicalization Scheme (JCS) as defined by RFC 8785 +// where it produces a stable representation of a JSON value. +// +// JSON strings are formatted to use their minimal representation, +// JSON numbers are formatted as double precision numbers according +// to some stable serialization algorithm. +// JSON object members are sorted in ascending order by name. +// All whitespace is removed. +// +// The output stability is dependent on the stability of the application data +// (see RFC 8785, Appendix E). It cannot produce stable output from +// fundamentally unstable input. For example, if the JSON value +// contains ephemeral data (e.g., a frequently changing timestamp), +// then the value is still unstable regardless of whether this is called. +// +// Canonicalize is equivalent to calling [Value.Format] with the following options: +// - [CanonicalizeRawInts](true) +// - [CanonicalizeRawFloats](true) +// - [ReorderRawObjects](true) +// +// Any options specified by the caller are applied after the initial set +// and may deliberately override prior options. +// +// Note that JCS treats all JSON numbers as IEEE 754 double precision numbers. +// Any numbers with precision beyond what is representable by that form +// will lose their precision when canonicalized. For example, integer values +// beyond ±2⁵³ will lose their precision. To preserve the original representation +// of JSON integers, additionally set [CanonicalizeRawInts] to false: +// +// v.Canonicalize(jsontext.CanonicalizeRawInts(false)) +func (v *Value) Canonicalize(opts ...Options) error { + return v.format([]Options{ + CanonicalizeRawInts(true), + CanonicalizeRawFloats(true), + ReorderRawObjects(true), + }, opts) +} + +// MarshalJSON returns v as the JSON encoding of v. +// It returns the stored value as the raw JSON output without any validation. +// If v is nil, then this returns a JSON null. +func (v Value) MarshalJSON() ([]byte, error) { + // NOTE: This matches the behavior of v1 json.RawMessage.MarshalJSON. + if v == nil { + return []byte("null"), nil + } + return v, nil +} + +// UnmarshalJSON sets v as the JSON encoding of b. +// It stores a copy of the provided raw JSON input without any validation. +func (v *Value) UnmarshalJSON(b []byte) error { + // NOTE: This matches the behavior of v1 json.RawMessage.UnmarshalJSON. + if v == nil { + return errors.New("jsontext.Value: UnmarshalJSON on nil pointer") + } + *v = append((*v)[:0], b...) + return nil +} + +// Kind returns the starting token kind. +// For a valid value, this will never include '}' or ']'. +func (v Value) Kind() Kind { + if v := v[jsonwire.ConsumeWhitespace(v):]; len(v) > 0 { + return Kind(v[0]).normalize() + } + return invalidKind +} + +const commaAndWhitespace = ", \n\r\t" + +type objectMember struct { + // name is the unquoted name. + name []byte // e.g., "name" + // buffer is the entirety of the raw JSON object member + // starting from right after the previous member (or opening '{') + // until right after the member value. + buffer []byte // e.g., `, \n\r\t"name": "value"` +} + +func (x objectMember) Compare(y objectMember) int { + if c := jsonwire.CompareUTF16(x.name, y.name); c != 0 { + return c + } + // With [AllowDuplicateNames] or [AllowInvalidUTF8], + // names could be identical, so also sort using the member value. + return jsonwire.CompareUTF16( + bytes.TrimLeft(x.buffer, commaAndWhitespace), + bytes.TrimLeft(y.buffer, commaAndWhitespace)) +} + +var objectMemberPool = sync.Pool{New: func() any { return new([]objectMember) }} + +func getObjectMembers() *[]objectMember { + ns := objectMemberPool.Get().(*[]objectMember) + *ns = (*ns)[:0] + return ns +} +func putObjectMembers(ns *[]objectMember) { + if cap(*ns) < 1<<10 { + clear(*ns) // avoid pinning name and buffer + objectMemberPool.Put(ns) + } +} + +// mustReorderObjects reorders in-place all object members in a JSON value, +// which must be valid otherwise it panics. +func mustReorderObjects(b []byte) { + // Obtain a buffered encoder just to use its internal buffer as + // a scratch buffer for reordering object members. + e2 := getBufferedEncoder() + defer putBufferedEncoder(e2) + + // Disable unnecessary checks to syntactically parse the JSON value. + d := getBufferedDecoder(b) + defer putBufferedDecoder(d) + d.s.Flags.Set(jsonflags.AllowDuplicateNames | jsonflags.AllowInvalidUTF8 | 1) + mustReorderObjectsFromDecoder(d, &e2.s.Buf) // per RFC 8785, section 3.2.3 +} + +// mustReorderObjectsFromDecoder recursively reorders all object members in place +// according to the ordering specified in RFC 8785, section 3.2.3. +// +// Pre-conditions: +// - The value is valid (i.e., no decoder errors should ever occur). +// - Initial call is provided a Decoder reading from the start of v. +// +// Post-conditions: +// - Exactly one JSON value is read from the Decoder. +// - All fully-parsed JSON objects are reordered by directly moving +// the members in the value buffer. +// +// The runtime is approximately O(n·log(n)) + O(m·log(m)), +// where n is len(v) and m is the total number of object members. +func mustReorderObjectsFromDecoder(d *Decoder, scratch *[]byte) { + switch tok, err := d.ReadToken(); tok.Kind() { + case '{': + // Iterate and collect the name and offsets for every object member. + members := getObjectMembers() + defer putObjectMembers(members) + var prevMember objectMember + isSorted := true + + beforeBody := d.InputOffset() // offset after '{' + for d.PeekKind() != '}' { + beforeName := d.InputOffset() + var flags jsonwire.ValueFlags + name, _ := d.s.ReadValue(&flags) + name = jsonwire.UnquoteMayCopy(name, flags.IsVerbatim()) + mustReorderObjectsFromDecoder(d, scratch) + afterValue := d.InputOffset() + + currMember := objectMember{name, d.s.buf[beforeName:afterValue]} + if isSorted && len(*members) > 0 { + isSorted = objectMember.Compare(prevMember, currMember) < 0 + } + *members = append(*members, currMember) + prevMember = currMember + } + afterBody := d.InputOffset() // offset before '}' + d.ReadToken() + + // Sort the members; return early if it's already sorted. + if isSorted { + return + } + firstBufferBeforeSorting := (*members)[0].buffer + slices.SortFunc(*members, objectMember.Compare) + firstBufferAfterSorting := (*members)[0].buffer + + // Append the reordered members to a new buffer, + // then copy the reordered members back over the original members. + // Avoid swapping in place since each member may be a different size + // where moving a member over a smaller member may corrupt the data + // for subsequent members before they have been moved. + // + // The following invariant must hold: + // sum([m.after-m.before for m in members]) == afterBody-beforeBody + commaAndWhitespacePrefix := func(b []byte) []byte { + return b[:len(b)-len(bytes.TrimLeft(b, commaAndWhitespace))] + } + sorted := (*scratch)[:0] + for i, member := range *members { + switch { + case i == 0 && &member.buffer[0] != &firstBufferBeforeSorting[0]: + // First member after sorting is not the first member before sorting, + // so use the prefix of the first member before sorting. + sorted = append(sorted, commaAndWhitespacePrefix(firstBufferBeforeSorting)...) + sorted = append(sorted, bytes.TrimLeft(member.buffer, commaAndWhitespace)...) + case i != 0 && &member.buffer[0] == &firstBufferBeforeSorting[0]: + // Later member after sorting is the first member before sorting, + // so use the prefix of the first member after sorting. + sorted = append(sorted, commaAndWhitespacePrefix(firstBufferAfterSorting)...) + sorted = append(sorted, bytes.TrimLeft(member.buffer, commaAndWhitespace)...) + default: + sorted = append(sorted, member.buffer...) + } + } + if int(afterBody-beforeBody) != len(sorted) { + panic("BUG: length invariant violated") + } + copy(d.s.buf[beforeBody:afterBody], sorted) + + // Update scratch buffer to the largest amount ever used. + if len(sorted) > len(*scratch) { + *scratch = sorted + } + case '[': + for d.PeekKind() != ']' { + mustReorderObjectsFromDecoder(d, scratch) + } + d.ReadToken() + default: + if err != nil { + panic("BUG: " + err.Error()) + } + } +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/migrate.sh b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/migrate.sh new file mode 100644 index 000000000..9c34f26eb --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/migrate.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +GOROOT=${1:-../go} +JSONROOT="." + +cp $JSONROOT/alias_gen.go $JSONROOT/alias_gen.go.bak +rm -r $JSONROOT/*.go $JSONROOT/internal $JSONROOT/jsontext $JSONROOT/v1 +mv $JSONROOT/alias_gen.go.bak $JSONROOT/alias_gen.go +cp -r $GOROOT/src/encoding/json/v2/*.go $JSONROOT/ +cp -r $GOROOT/src/encoding/json/internal/ $JSONROOT/internal/ +cp -r $GOROOT/src/encoding/json/jsontext/ $JSONROOT/jsontext/ +mkdir $JSONROOT/v1 +for X in $GOROOT/src/encoding/json/v2_*.go; do + cp $X $JSONROOT/v1/$(basename $X | sed "s/v2_//") +done +cd $JSONROOT +for X in $(git ls-files --cached --others --exclude-standard | grep ".*[.]go$"); do + if [ ! -e "$X" ]; then + continue + fi + sed -i 's/go:build goexperiment.jsonv2$/go:build !goexperiment.jsonv2 || !go1.25/' $X + sed -i 's|"encoding/json/v2"|"github.com/go-json-experiment/json"|' $X + sed -i 's|"encoding/json/internal"|"github.com/go-json-experiment/json/internal"|' $X + sed -i 's|"encoding/json/internal/jsonflags"|"github.com/go-json-experiment/json/internal/jsonflags"|' $X + sed -i 's|"encoding/json/internal/jsonopts"|"github.com/go-json-experiment/json/internal/jsonopts"|' $X + sed -i 's|"encoding/json/internal/jsontest"|"github.com/go-json-experiment/json/internal/jsontest"|' $X + sed -i 's|"encoding/json/internal/jsonwire"|"github.com/go-json-experiment/json/internal/jsonwire"|' $X + sed -i 's|"encoding/json/jsontext"|"github.com/go-json-experiment/json/jsontext"|' $X + sed -i 's|"encoding/json"|"github.com/go-json-experiment/json/v1"|' $X + sed -i 's|"internal/zstd"|"github.com/go-json-experiment/json/internal/zstd"|' $X + goimports -w $X +done +sed -i 's/v2[.]struct/json.struct/' $JSONROOT/errors_test.go +sed -i 's|jsonv1 "github.com/go-json-experiment/json/v1"|jsonv1 "encoding/json"|' $JSONROOT/bench_test.go + +# TODO(go1.25): Remove test that relies on "synctest" that is not available yet. +sed -i '/Issue #73733/,+17d' $JSONROOT/v1/encode_test.go +goimports -w $JSONROOT/v1/encode_test.go + +# Remove documentation that only makes sense within the stdlib. +sed -i '/This package .* is experimental/,+4d' $JSONROOT/doc.go +sed -i '/This package .* is experimental/,+4d' $JSONROOT/jsontext/doc.go + +git checkout internal/zstd # we still need local copy of zstd for testing + +go run alias_gen.go "encoding/json" $JSONROOT/v1 +go run alias_gen.go "encoding/json/v2" $JSONROOT +go run alias_gen.go "encoding/json/jsontext" $JSONROOT/jsontext diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/options.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/options.go new file mode 100644 index 000000000..2f4744980 --- /dev/null +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/options.go @@ -0,0 +1,287 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "fmt" + + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts" +) + +// Options configure [Marshal], [MarshalWrite], [MarshalEncode], +// [Unmarshal], [UnmarshalRead], and [UnmarshalDecode] with specific features. +// Each function takes in a variadic list of options, where properties +// set in later options override the value of previously set properties. +// +// The Options type is identical to [encoding/json.Options] and +// [encoding/json/jsontext.Options]. Options from the other packages can +// be used interchangeably with functionality in this package. +// +// Options represent either a singular option or a set of options. +// It can be functionally thought of as a Go map of option properties +// (even though the underlying implementation avoids Go maps for performance). +// +// The constructors (e.g., [Deterministic]) return a singular option value: +// +// opt := Deterministic(true) +// +// which is analogous to creating a single entry map: +// +// opt := Options{"Deterministic": true} +// +// [JoinOptions] composes multiple options values to together: +// +// out := JoinOptions(opts...) +// +// which is analogous to making a new map and copying the options over: +// +// out := make(Options) +// for _, m := range opts { +// for k, v := range m { +// out[k] = v +// } +// } +// +// [GetOption] looks up the value of options parameter: +// +// v, ok := GetOption(opts, Deterministic) +// +// which is analogous to a Go map lookup: +// +// v, ok := Options["Deterministic"] +// +// There is a single Options type, which is used with both marshal and unmarshal. +// Some options affect both operations, while others only affect one operation: +// +// - [StringifyNumbers] affects marshaling and unmarshaling +// - [Deterministic] affects marshaling only +// - [FormatNilSliceAsNull] affects marshaling only +// - [FormatNilMapAsNull] affects marshaling only +// - [OmitZeroStructFields] affects marshaling only +// - [MatchCaseInsensitiveNames] affects marshaling and unmarshaling +// - [DiscardUnknownMembers] affects marshaling only +// - [RejectUnknownMembers] affects unmarshaling only +// - [WithMarshalers] affects marshaling only +// - [WithUnmarshalers] affects unmarshaling only +// +// Options that do not affect a particular operation are ignored. +type Options = jsonopts.Options + +// JoinOptions coalesces the provided list of options into a single Options. +// Properties set in later options override the value of previously set properties. +func JoinOptions(srcs ...Options) Options { + var dst jsonopts.Struct + dst.Join(srcs...) + return &dst +} + +// GetOption returns the value stored in opts with the provided setter, +// reporting whether the value is present. +// +// Example usage: +// +// v, ok := json.GetOption(opts, json.Deterministic) +// +// Options are most commonly introspected to alter the JSON representation of +// [MarshalerTo.MarshalJSONTo] and [UnmarshalerFrom.UnmarshalJSONFrom] methods, and +// [MarshalToFunc] and [UnmarshalFromFunc] functions. +// In such cases, the presence bit should generally be ignored. +func GetOption[T any](opts Options, setter func(T) Options) (T, bool) { + return jsonopts.GetOption(opts, setter) +} + +// DefaultOptionsV2 is the full set of all options that define v2 semantics. +// It is equivalent to all options under [Options], [encoding/json.Options], +// and [encoding/json/jsontext.Options] being set to false or the zero value, +// except for the options related to whitespace formatting. +func DefaultOptionsV2() Options { + return &jsonopts.DefaultOptionsV2 +} + +// StringifyNumbers specifies that numeric Go types should be marshaled +// as a JSON string containing the equivalent JSON number value. +// When unmarshaling, numeric Go types are parsed from a JSON string +// containing the JSON number without any surrounding whitespace. +// +// According to RFC 8259, section 6, a JSON implementation may choose to +// limit the representation of a JSON number to an IEEE 754 binary64 value. +// This may cause decoders to lose precision for int64 and uint64 types. +// Quoting JSON numbers as a JSON string preserves the exact precision. +// +// This affects either marshaling or unmarshaling. +func StringifyNumbers(v bool) Options { + if v { + return jsonflags.StringifyNumbers | 1 + } else { + return jsonflags.StringifyNumbers | 0 + } +} + +// Deterministic specifies that the same input value will be serialized +// as the exact same output bytes. Different processes of +// the same program will serialize equal values to the same bytes, +// but different versions of the same program are not guaranteed +// to produce the exact same sequence of bytes. +// +// This only affects marshaling and is ignored when unmarshaling. +func Deterministic(v bool) Options { + if v { + return jsonflags.Deterministic | 1 + } else { + return jsonflags.Deterministic | 0 + } +} + +// FormatNilSliceAsNull specifies that a nil Go slice should marshal as a +// JSON null instead of the default representation as an empty JSON array +// (or an empty JSON string in the case of ~[]byte). +// Slice fields explicitly marked with `format:emitempty` still marshal +// as an empty JSON array. +// +// This only affects marshaling and is ignored when unmarshaling. +func FormatNilSliceAsNull(v bool) Options { + if v { + return jsonflags.FormatNilSliceAsNull | 1 + } else { + return jsonflags.FormatNilSliceAsNull | 0 + } +} + +// FormatNilMapAsNull specifies that a nil Go map should marshal as a +// JSON null instead of the default representation as an empty JSON object. +// Map fields explicitly marked with `format:emitempty` still marshal +// as an empty JSON object. +// +// This only affects marshaling and is ignored when unmarshaling. +func FormatNilMapAsNull(v bool) Options { + if v { + return jsonflags.FormatNilMapAsNull | 1 + } else { + return jsonflags.FormatNilMapAsNull | 0 + } +} + +// OmitZeroStructFields specifies that a Go struct should marshal in such a way +// that all struct fields that are zero are omitted from the marshaled output +// if the value is zero as determined by the "IsZero() bool" method if present, +// otherwise based on whether the field is the zero Go value. +// This is semantically equivalent to specifying the `omitzero` tag option +// on every field in a Go struct. +// +// This only affects marshaling and is ignored when unmarshaling. +func OmitZeroStructFields(v bool) Options { + if v { + return jsonflags.OmitZeroStructFields | 1 + } else { + return jsonflags.OmitZeroStructFields | 0 + } +} + +// MatchCaseInsensitiveNames specifies that JSON object members are matched +// against Go struct fields using a case-insensitive match of the name. +// Go struct fields explicitly marked with `case:strict` or `case:ignore` +// always use case-sensitive (or case-insensitive) name matching, +// regardless of the value of this option. +// +// This affects either marshaling or unmarshaling. +// For marshaling, this option may alter the detection of duplicate names +// (assuming [jsontext.AllowDuplicateNames] is false) from inlined fields +// if it matches one of the declared fields in the Go struct. +func MatchCaseInsensitiveNames(v bool) Options { + if v { + return jsonflags.MatchCaseInsensitiveNames | 1 + } else { + return jsonflags.MatchCaseInsensitiveNames | 0 + } +} + +// DiscardUnknownMembers specifies that marshaling should ignore any +// JSON object members stored in Go struct fields dedicated to storing +// unknown JSON object members. +// +// This only affects marshaling and is ignored when unmarshaling. +func DiscardUnknownMembers(v bool) Options { + if v { + return jsonflags.DiscardUnknownMembers | 1 + } else { + return jsonflags.DiscardUnknownMembers | 0 + } +} + +// RejectUnknownMembers specifies that unknown members should be rejected +// when unmarshaling a JSON object, regardless of whether there is a field +// to store unknown members. +// +// This only affects unmarshaling and is ignored when marshaling. +func RejectUnknownMembers(v bool) Options { + if v { + return jsonflags.RejectUnknownMembers | 1 + } else { + return jsonflags.RejectUnknownMembers | 0 + } +} + +// WithMarshalers specifies a list of type-specific marshalers to use, +// which can be used to override the default marshal behavior for values +// of particular types. +// +// This only affects marshaling and is ignored when unmarshaling. +func WithMarshalers(v *Marshalers) Options { + return (*marshalersOption)(v) +} + +// WithUnmarshalers specifies a list of type-specific unmarshalers to use, +// which can be used to override the default unmarshal behavior for values +// of particular types. +// +// This only affects unmarshaling and is ignored when marshaling. +func WithUnmarshalers(v *Unmarshalers) Options { + return (*unmarshalersOption)(v) +} + +// These option types are declared here instead of "jsonopts" +// to avoid a dependency on "reflect" from "jsonopts". +type ( + marshalersOption Marshalers + unmarshalersOption Unmarshalers +) + +func (*marshalersOption) JSONOptions(internal.NotForPublicUse) {} +func (*unmarshalersOption) JSONOptions(internal.NotForPublicUse) {} + +// Inject support into "jsonopts" to handle these types. +func init() { + jsonopts.GetUnknownOption = func(src jsonopts.Struct, zero jsonopts.Options) (any, bool) { + switch zero.(type) { + case *marshalersOption: + if !src.Flags.Has(jsonflags.Marshalers) { + return (*Marshalers)(nil), false + } + return src.Marshalers.(*Marshalers), true + case *unmarshalersOption: + if !src.Flags.Has(jsonflags.Unmarshalers) { + return (*Unmarshalers)(nil), false + } + return src.Unmarshalers.(*Unmarshalers), true + default: + panic(fmt.Sprintf("unknown option %T", zero)) + } + } + jsonopts.JoinUnknownOption = func(dst jsonopts.Struct, src jsonopts.Options) jsonopts.Struct { + switch src := src.(type) { + case *marshalersOption: + dst.Flags.Set(jsonflags.Marshalers | 1) + dst.Marshalers = (*Marshalers)(src) + case *unmarshalersOption: + dst.Flags.Set(jsonflags.Unmarshalers | 1) + dst.Unmarshalers = (*Unmarshalers)(src) + default: + panic(fmt.Sprintf("unknown option %T", src)) + } + return dst + } +} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go b/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go deleted file mode 100644 index e0bd1b31d..000000000 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package json - -import ( - "bytes" - "errors" - "io" - "sort" - "sync" - "unicode/utf16" - "unicode/utf8" -) - -// NOTE: RawValue is analogous to v1 json.RawMessage. - -// RawValue represents a single raw JSON value, which may be one of the following: -// - a JSON literal (i.e., null, true, or false) -// - a JSON string (e.g., "hello, world!") -// - a JSON number (e.g., 123.456) -// - an entire JSON object (e.g., {"fizz":"buzz"} ) -// - an entire JSON array (e.g., [1,2,3] ) -// -// RawValue can represent entire array or object values, while Token cannot. -// RawValue may contain leading and/or trailing whitespace. -type RawValue []byte - -// Clone returns a copy of v. -func (v RawValue) Clone() RawValue { - if v == nil { - return nil - } - return append(RawValue{}, v...) -} - -// String returns the string formatting of v. -func (v RawValue) String() string { - if v == nil { - return "null" - } - return string(v) -} - -// IsValid reports whether the raw JSON value is syntactically valid -// according to RFC 7493. -// -// It verifies whether the input is properly encoded as UTF-8, -// that escape sequences within strings decode to valid Unicode codepoints, and -// that all names in each object are unique. -// It does not verify whether numbers are representable within the limits -// of any common numeric type (e.g., float64, int64, or uint64). -func (v RawValue) IsValid() bool { - d := getBufferedDecoder(v, DecodeOptions{}) - defer putBufferedDecoder(d) - _, errVal := d.ReadValue() - _, errEOF := d.ReadToken() - return errVal == nil && errEOF == io.EOF -} - -// Compact removes all whitespace from the raw JSON value. -// -// It does not reformat JSON strings to use any other representation. -// It is guaranteed to succeed if the input is valid. -// If the value is already compacted, then the buffer is not mutated. -func (v *RawValue) Compact() error { - return v.reformat(false, false, "", "") -} - -// Indent reformats the whitespace in the raw JSON value so that each element -// in a JSON object or array begins on a new, indented line beginning with -// prefix followed by one or more copies of indent according to the nesting. -// The value does not begin with the prefix nor any indention, -// to make it easier to embed inside other formatted JSON data. -// -// It does not reformat JSON strings to use any other representation. -// It is guaranteed to succeed if the input is valid. -// If the value is already indented properly, then the buffer is not mutated. -func (v *RawValue) Indent(prefix, indent string) error { - return v.reformat(false, true, prefix, indent) -} - -// Canonicalize canonicalizes the raw JSON value according to the -// JSON Canonicalization Scheme (JCS) as defined by RFC 8785 -// where it produces a stable representation of a JSON value. -// -// The output stability is dependent on the stability of the application data -// (see RFC 8785, Appendix E). It cannot produce stable output from -// fundamentally unstable input. For example, if the JSON value -// contains ephemeral data (e.g., a frequently changing timestamp), -// then the value is still unstable regardless of whether this is called. -// -// Note that JCS treats all JSON numbers as IEEE 754 double precision numbers. -// Any numbers with precision beyond what is representable by that form -// will lose their precision when canonicalized. For example, integer values -// beyond ±2⁵³ will lose their precision. It is recommended that -// int64 and uint64 data types be represented as a JSON string. -// -// It is guaranteed to succeed if the input is valid. -// If the value is already canonicalized, then the buffer is not mutated. -func (v *RawValue) Canonicalize() error { - return v.reformat(true, false, "", "") -} - -// TODO: Instead of implementing the v1 Marshaler/Unmarshaler, -// consider implementing the v2 versions instead. - -// MarshalJSON returns v as the JSON encoding of v. -// It returns the stored value as the raw JSON output without any validation. -// If v is nil, then this returns a JSON null. -func (v RawValue) MarshalJSON() ([]byte, error) { - // NOTE: This matches the behavior of v1 json.RawMessage.MarshalJSON. - if v == nil { - return []byte("null"), nil - } - return v, nil -} - -// UnmarshalJSON sets v as the JSON encoding of b. -// It stores a copy of the provided raw JSON input without any validation. -func (v *RawValue) UnmarshalJSON(b []byte) error { - // NOTE: This matches the behavior of v1 json.RawMessage.UnmarshalJSON. - if v == nil { - return errors.New("json.RawValue: UnmarshalJSON on nil pointer") - } - *v = append((*v)[:0], b...) - return nil -} - -// Kind returns the starting token kind. -// For a valid value, this will never include '}' or ']'. -func (v RawValue) Kind() Kind { - if v := v[consumeWhitespace(v):]; len(v) > 0 { - return Kind(v[0]).normalize() - } - return invalidKind -} - -func (v *RawValue) reformat(canonical, multiline bool, prefix, indent string) error { - var eo EncodeOptions - if canonical { - eo.AllowInvalidUTF8 = false // per RFC 8785, section 3.2.4 - eo.AllowDuplicateNames = false // per RFC 8785, section 3.1 - eo.canonicalizeNumbers = true // per RFC 8785, section 3.2.2.3 - eo.EscapeRune = nil // per RFC 8785, section 3.2.2.2 - eo.multiline = false // per RFC 8785, section 3.2.1 - } else { - if s := trimLeftSpaceTab(prefix); len(s) > 0 { - panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") - } - if s := trimLeftSpaceTab(indent); len(s) > 0 { - panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") - } - eo.AllowInvalidUTF8 = true - eo.AllowDuplicateNames = true - eo.preserveRawStrings = true - eo.multiline = multiline // in case indent is empty - eo.IndentPrefix = prefix - eo.Indent = indent - } - eo.omitTopLevelNewline = true - - // Write the entire value to reformat all tokens and whitespace. - e := getBufferedEncoder(eo) - defer putBufferedEncoder(e) - if err := e.WriteValue(*v); err != nil { - return err - } - - // For canonical output, we may need to reorder object members. - if canonical { - // Obtain a buffered encoder just to use its internal buffer as - // a scratch buffer in reorderObjects for reordering object members. - e2 := getBufferedEncoder(EncodeOptions{}) - defer putBufferedEncoder(e2) - - // Disable redundant checks performed earlier during encoding. - d := getBufferedDecoder(e.buf, DecodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true}) - defer putBufferedDecoder(d) - reorderObjects(d, &e2.buf) // per RFC 8785, section 3.2.3 - } - - // Store the result back into the value if different. - if !bytes.Equal(*v, e.buf) { - *v = append((*v)[:0], e.buf...) - } - return nil -} - -func trimLeftSpaceTab(s string) string { - for i, r := range s { - switch r { - case ' ', '\t': - default: - return s[i:] - } - } - return "" -} - -type memberName struct { - // name is the unescaped name. - name []byte - // before and after are byte offsets into Decoder.buf that represents - // the entire name/value pair. It may contain leading commas. - before, after int64 -} - -var memberNamePool = sync.Pool{New: func() any { return new(memberNames) }} - -func getMemberNames() *memberNames { - ns := memberNamePool.Get().(*memberNames) - *ns = (*ns)[:0] - return ns -} -func putMemberNames(ns *memberNames) { - if cap(*ns) < 1<<10 { - for i := range *ns { - (*ns)[i] = memberName{} // avoid pinning name - } - memberNamePool.Put(ns) - } -} - -type memberNames []memberName - -func (m *memberNames) Len() int { return len(*m) } -func (m *memberNames) Less(i, j int) bool { return lessUTF16((*m)[i].name, (*m)[j].name) } -func (m *memberNames) Swap(i, j int) { (*m)[i], (*m)[j] = (*m)[j], (*m)[i] } - -// reorderObjects recursively reorders all object members in place -// according to the ordering specified in RFC 8785, section 3.2.3. -// -// Pre-conditions: -// - The value is valid (i.e., no decoder errors should ever occur). -// - The value is compact (i.e., no whitespace is present). -// - Initial call is provided a Decoder reading from the start of v. -// -// Post-conditions: -// - Exactly one JSON value is read from the Decoder. -// - All fully-parsed JSON objects are reordered by directly moving -// the members in the value buffer. -// -// The runtime is approximately O(n·log(n)) + O(m·log(m)), -// where n is len(v) and m is the total number of object members. -func reorderObjects(d *Decoder, scratch *[]byte) { - switch tok, _ := d.ReadToken(); tok.Kind() { - case '{': - // Iterate and collect the name and offsets for every object member. - members := getMemberNames() - defer putMemberNames(members) - var prevName []byte - isSorted := true - - beforeBody := d.InputOffset() // offset after '{' - for d.PeekKind() != '}' { - beforeName := d.InputOffset() - var flags valueFlags - name, _ := d.readValue(&flags) - name = unescapeStringMayCopy(name, flags.isVerbatim()) - reorderObjects(d, scratch) - afterValue := d.InputOffset() - - if isSorted && len(*members) > 0 { - isSorted = lessUTF16(prevName, []byte(name)) - } - *members = append(*members, memberName{name, beforeName, afterValue}) - prevName = name - } - afterBody := d.InputOffset() // offset before '}' - d.ReadToken() - - // Sort the members; return early if it's already sorted. - if isSorted { - return - } - // TODO(https://go.dev/issue/47619): Use slices.Sort. - sort.Sort(members) - - // Append the reordered members to a new buffer, - // then copy the reordered members back over the original members. - // Avoid swapping in place since each member may be a different size - // where moving a member over a smaller member may corrupt the data - // for subsequent members before they have been moved. - // - // The following invariant must hold: - // sum([m.after-m.before for m in members]) == afterBody-beforeBody - sorted := (*scratch)[:0] - for i, member := range *members { - if d.buf[member.before] == ',' { - member.before++ // trim leading comma - } - sorted = append(sorted, d.buf[member.before:member.after]...) - if i < len(*members)-1 { - sorted = append(sorted, ',') // append trailing comma - } - } - if int(afterBody-beforeBody) != len(sorted) { - panic("BUG: length invariant violated") - } - copy(d.buf[beforeBody:afterBody], sorted) - - // Update scratch buffer to the largest amount ever used. - if len(sorted) > len(*scratch) { - *scratch = sorted - } - case '[': - for d.PeekKind() != ']' { - reorderObjects(d, scratch) - } - d.ReadToken() - } -} - -// lessUTF16 reports whether x is lexicographically less than y according -// to the UTF-16 codepoints of the UTF-8 encoded input strings. -// This implements the ordering specified in RFC 8785, section 3.2.3. -// The inputs must be valid UTF-8, otherwise this may panic. -func lessUTF16[Bytes []byte | string](x, y Bytes) bool { - // NOTE: This is an optimized, allocation-free implementation - // of lessUTF16Simple in fuzz_test.go. FuzzLessUTF16 verifies that the - // two implementations agree on the result of comparing any two strings. - - isUTF16Self := func(r rune) bool { - return ('\u0000' <= r && r <= '\uD7FF') || ('\uE000' <= r && r <= '\uFFFF') - } - - var invalidUTF8 bool - x0, y0 := x, y - for { - if len(x) == 0 || len(y) == 0 { - if len(x) == len(y) && invalidUTF8 { - return string(x0) < string(y0) - } - return len(x) < len(y) - } - - // ASCII fast-path. - if x[0] < utf8.RuneSelf || y[0] < utf8.RuneSelf { - if x[0] != y[0] { - return x[0] < y[0] - } - x, y = x[1:], y[1:] - continue - } - - // Decode next pair of runes as UTF-8. - // TODO(https://go.dev/issue/56948): Use a generic implementation - // of utf8.DecodeRune, or rely on a compiler optimization to statically - // hide the cost of a type switch (https://go.dev/issue/57072). - var rx, ry rune - var nx, ny int - switch any(x).(type) { - case string: - rx, nx = utf8.DecodeRuneInString(string(x)) - ry, ny = utf8.DecodeRuneInString(string(y)) - case []byte: - rx, nx = utf8.DecodeRune([]byte(x)) - ry, ny = utf8.DecodeRune([]byte(y)) - } - - selfx := isUTF16Self(rx) - selfy := isUTF16Self(ry) - switch { - // The x rune is a single UTF-16 codepoint, while - // the y rune is a surrogate pair of UTF-16 codepoints. - case selfx && !selfy: - ry, _ = utf16.EncodeRune(ry) - // The y rune is a single UTF-16 codepoint, while - // the x rune is a surrogate pair of UTF-16 codepoints. - case selfy && !selfx: - rx, _ = utf16.EncodeRune(rx) - } - if rx != ry { - return rx < ry - } - invalidUTF8 = invalidUTF8 || (rx == utf8.RuneError && nx == 1) || (ry == utf8.RuneError && ny == 1) - x, y = x[nx:], y[ny:] - } -} diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go b/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go index 81280aae6..06bcf0c37 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go @@ -140,18 +140,20 @@ func (c *convert) makeOpenAPIRef(specSchema *spec.Schema) schema.TypeRef { // to deduplicate) mapRelationship, err := getMapElementRelationship(specSchema.Extensions) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } if len(mapRelationship) > 0 { return schema.TypeRef{ NamedType: &n, ElementRelationship: &mapRelationship, + Nullable: specSchema.Nullable, } } return schema.TypeRef{ NamedType: &n, + Nullable: specSchema.Nullable, } } @@ -164,7 +166,8 @@ func (c *convert) makeOpenAPIRef(specSchema *spec.Schema) schema.TypeRef { c.pop(c2) return schema.TypeRef{ - Inlined: inlined, + Inlined: inlined, + Nullable: specSchema.Nullable, } } @@ -212,7 +215,7 @@ func (c *convert) parseObject(s *spec.Schema) *schema.Map { relationship, err := getMapElementRelationship(s.Extensions) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } return &schema.Map{ @@ -225,7 +228,7 @@ func (c *convert) parseObject(s *spec.Schema) *schema.Map { func (c *convert) parseList(s *spec.Schema) *schema.List { relationship, mapKeys, err := getListElementRelationship(s.Extensions) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } elementType := func() schema.TypeRef { if s.Items != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go b/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go index e40f6056e..6a8b9f44a 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go @@ -72,7 +72,7 @@ func (c *convert) makeRef(model proto.Schema, preserveUnknownFields bool) schema mapRelationship, err := getMapElementRelationship(model.GetExtensions()) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } // empty string means unset. @@ -114,7 +114,7 @@ func (c *convert) VisitKind(k *proto.Kind) { unions, err := makeUnions(k.GetExtensions()) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) return } // TODO: We should check that the fields and discriminator @@ -129,14 +129,14 @@ func (c *convert) VisitKind(k *proto.Kind) { a.Map.ElementRelationship, err = getMapElementRelationship(k.GetExtensions()) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } } func (c *convert) VisitArray(a *proto.Array) { relationship, mapKeys, err := getListElementRelationship(a.GetExtensions()) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } atom := c.top() @@ -150,7 +150,7 @@ func (c *convert) VisitArray(a *proto.Array) { func (c *convert) VisitMap(m *proto.Map) { relationship, err := getMapElementRelationship(m.GetExtensions()) if err != nil { - c.reportError(err.Error()) + c.reportError("%v", err) } a := c.top() diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go index 1f62c6e77..1b3dfff1d 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -46,14 +47,14 @@ func (e *Encoding) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (e *Encoding) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (e *Encoding) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { EncodingProps encodingPropsOmitZero `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.EncodingProps = encodingPropsOmitZero(e.EncodingProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (e *Encoding) UnmarshalJSON(data []byte) error { @@ -69,12 +70,12 @@ func (e *Encoding) UnmarshalJSON(data []byte) error { return nil } -func (e *Encoding) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (e *Encoding) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` EncodingProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/example.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/example.go index 8834a92e6..3edb10492 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/example.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/example.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -53,16 +54,16 @@ func (e *Example) MarshalJSON() ([]byte, error) { } return swag.ConcatJSON(b1, b2, b3), nil } -func (e *Example) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (e *Example) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` ExampleProps `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Ref = e.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(e.Extensions) x.ExampleProps = e.ExampleProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (e *Example) UnmarshalJSON(data []byte) error { @@ -81,12 +82,12 @@ func (e *Example) UnmarshalJSON(data []byte) error { return nil } -func (e *Example) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (e *Example) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ExampleProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&e.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go index f0515496e..7a83c53c0 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -53,14 +54,14 @@ func (e *ExternalDocumentation) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (e *ExternalDocumentation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (e *ExternalDocumentation) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { ExternalDocumentationProps `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.ExternalDocumentationProps = e.ExternalDocumentationProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (e *ExternalDocumentation) UnmarshalJSON(data []byte) error { @@ -76,12 +77,12 @@ func (e *ExternalDocumentation) UnmarshalJSON(data []byte) error { return nil } -func (e *ExternalDocumentation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (e *ExternalDocumentation) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ExternalDocumentationProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } e.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/header.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/header.go index 9ea30628c..475817f66 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/header.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/header.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -54,16 +55,16 @@ func (h *Header) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (h *Header) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (h *Header) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` HeaderProps headerPropsOmitZero `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Ref = h.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(h.Extensions) x.HeaderProps = headerPropsOmitZero(h.HeaderProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (h *Header) UnmarshalJSON(data []byte) error { @@ -83,12 +84,12 @@ func (h *Header) UnmarshalJSON(data []byte) error { return nil } -func (h *Header) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (h *Header) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` HeaderProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&h.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go index 47eef1edb..c9062b238 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -49,14 +50,14 @@ func (m *MediaType) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (e *MediaType) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (e *MediaType) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { MediaTypeProps mediaTypePropsOmitZero `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.MediaTypeProps = mediaTypePropsOmitZero(e.MediaTypeProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (m *MediaType) UnmarshalJSON(data []byte) error { @@ -72,12 +73,12 @@ func (m *MediaType) UnmarshalJSON(data []byte) error { return nil } -func (m *MediaType) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (m *MediaType) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` MediaTypeProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } m.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go index f1e102547..8219b29d0 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -49,14 +50,14 @@ func (o *Operation) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (o *Operation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (o *Operation) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` OperationProps operationPropsOmitZero `json:",inline"` } x.Extensions = internal.SanitizeExtensions(o.Extensions) x.OperationProps = operationPropsOmitZero(o.OperationProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON hydrates this items instance with the data from JSON @@ -70,12 +71,12 @@ func (o *Operation) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &o.VendorExtensible) } -func (o *Operation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (o *Operation) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` OperationProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } o.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go index ada7edb63..a5e7d46c4 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -54,16 +55,16 @@ func (p *Parameter) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (p *Parameter) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p *Parameter) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` ParameterProps parameterPropsOmitZero `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.ParameterProps = parameterPropsOmitZero(p.ParameterProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (p *Parameter) UnmarshalJSON(data []byte) error { @@ -84,12 +85,12 @@ func (p *Parameter) UnmarshalJSON(data []byte) error { return nil } -func (p *Parameter) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *Parameter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ParameterProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&p.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/path.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/path.go index 16fbbb4dd..cb04cf0f9 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/path.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/path.go @@ -24,6 +24,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -57,7 +58,7 @@ func (p *Paths) MarshalJSON() ([]byte, error) { return concated, nil } -func (p *Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p *Paths) MarshalJSONTo(enc *jsontext.Encoder) error { m := make(map[string]any, len(p.Extensions)+len(p.Paths)) for k, v := range p.Extensions { if internal.IsExtensionKey(k) { @@ -69,7 +70,7 @@ func (p *Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) m[k] = v } } - return opts.MarshalNext(enc, m) + return jsonv2.MarshalEncode(enc, m) } // UnmarshalJSON hydrates this items instance with the data from JSON @@ -106,7 +107,7 @@ func (p *Paths) UnmarshalJSON(data []byte) error { return nil } -func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *Paths) UnmarshalJSONFrom(dec *jsontext.Decoder) error { tok, err := dec.ReadToken() if err != nil { return err @@ -129,7 +130,7 @@ func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Deco switch k := tok.String(); { case internal.IsExtensionKey(k): var ext any - if err := opts.UnmarshalNext(dec, &ext); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &ext); err != nil { return err } @@ -139,7 +140,7 @@ func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Deco p.Extensions[k] = ext case len(k) > 0 && k[0] == '/': pi := Path{} - if err := opts.UnmarshalNext(dec, &pi); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &pi); err != nil { return err } @@ -188,16 +189,16 @@ func (p *Path) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (p *Path) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p *Path) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Ref string `json:"$ref,omitempty"` - spec.Extensions + Ref string `json:"$ref,omitempty"` + Extensions spec.Extensions `json:",inline"` PathProps } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.PathProps = p.PathProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (p *Path) UnmarshalJSON(data []byte) error { @@ -216,13 +217,13 @@ func (p *Path) UnmarshalJSON(data []byte) error { return nil } -func (p *Path) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *Path) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` PathProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&p.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go index 6f8607e40..b39c0d4fe 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -54,16 +55,16 @@ func (r *RequestBody) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (r *RequestBody) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r *RequestBody) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` RequestBodyProps requestBodyPropsOmitZero `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.RequestBodyProps = requestBodyPropsOmitZero(r.RequestBodyProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (r *RequestBody) UnmarshalJSON(data []byte) error { @@ -98,12 +99,12 @@ type requestBodyPropsOmitZero struct { Required bool `json:"required,omitzero"` } -func (r *RequestBody) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (r *RequestBody) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` RequestBodyProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&r.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/response.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/response.go index 73e241fdc..72ad9882d 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/response.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/response.go @@ -24,6 +24,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -51,11 +52,11 @@ func (r *Responses) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r Responses) MarshalJSONTo(enc *jsontext.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { - ArbitraryKeys - Default *Response `json:"default,omitzero"` + ArbitraryKeys ArbitraryKeys `json:",inline"` + Default *Response `json:"default,omitzero"` } x.ArbitraryKeys = make(map[string]any, len(r.Extensions)+len(r.StatusCodeResponses)) for k, v := range r.Extensions { @@ -67,7 +68,7 @@ func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encod x.ArbitraryKeys[strconv.Itoa(k)] = v } x.Default = r.Default - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (r *Responses) UnmarshalJSON(data []byte) error { @@ -136,7 +137,7 @@ func (r *ResponsesProps) UnmarshalJSON(data []byte) error { return nil } -func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) (err error) { +func (r *Responses) UnmarshalJSONFrom(dec *jsontext.Decoder) (err error) { tok, err := dec.ReadToken() if err != nil { return err @@ -157,7 +158,7 @@ func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2. switch k := tok.String(); { case internal.IsExtensionKey(k): var ext any - if err := opts.UnmarshalNext(dec, &ext); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &ext); err != nil { return err } @@ -167,14 +168,14 @@ func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2. r.Extensions[k] = ext case k == "default": resp := Response{} - if err := opts.UnmarshalNext(dec, &resp); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &resp); err != nil { return err } r.ResponsesProps.Default = &resp default: if nk, err := strconv.Atoi(k); err == nil { resp := Response{} - if err := opts.UnmarshalNext(dec, &resp); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &resp); err != nil { return err } @@ -219,16 +220,16 @@ func (r *Response) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (r Response) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r Response) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Ref string `json:"$ref,omitempty"` - spec.Extensions + Ref string `json:"$ref,omitempty"` + Extensions spec.Extensions `json:",inline"` ResponseProps `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.ResponseProps = r.ResponseProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (r *Response) UnmarshalJSON(data []byte) error { @@ -247,12 +248,12 @@ func (r *Response) UnmarshalJSON(data []byte) error { return nil } -func (r *Response) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (r *Response) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ResponseProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&r.Ref.Ref, x.Extensions); err != nil { @@ -302,16 +303,16 @@ func (r *Link) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (r *Link) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r *Link) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Ref string `json:"$ref,omitempty"` - spec.Extensions - LinkProps `json:",inline"` + Ref string `json:"$ref,omitempty"` + Extensions spec.Extensions `json:",inline"` + LinkProps `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.LinkProps = r.LinkProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (r *Link) UnmarshalJSON(data []byte) error { @@ -331,12 +332,12 @@ func (r *Link) UnmarshalJSON(data []byte) error { return nil } -func (l *Link) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (l *Link) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` LinkProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&l.Ref.Ref, x.Extensions); err != nil { diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go index dd1e98ed8..9bc180eaf 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -52,16 +53,16 @@ func (s *SecurityScheme) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (s *SecurityScheme) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s *SecurityScheme) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` SecuritySchemeProps `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Ref = s.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SecuritySchemeProps = s.SecuritySchemeProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON hydrates this items instance with the data from JSON diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/server.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/server.go index 654a42c06..3037fbce4 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/server.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/server.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -55,14 +56,14 @@ func (s *Server) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (s *Server) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s *Server) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { ServerProps `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.ServerProps = s.ServerProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (s *Server) UnmarshalJSON(data []byte) error { @@ -79,12 +80,12 @@ func (s *Server) UnmarshalJSON(data []byte) error { return nil } -func (s *Server) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *Server) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ServerProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) @@ -123,14 +124,14 @@ func (s *ServerVariable) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (s *ServerVariable) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s *ServerVariable) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { ServerVariableProps `json:",inline"` - spec.Extensions + Extensions spec.Extensions `json:",inline"` } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.ServerVariableProps = s.ServerVariableProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } func (s *ServerVariable) UnmarshalJSON(data []byte) error { @@ -146,12 +147,12 @@ func (s *ServerVariable) UnmarshalJSON(data []byte) error { return nil } -func (s *ServerVariable) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *ServerVariable) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - spec.Extensions + Extensions spec.Extensions `json:",inline"` ServerVariableProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go index 5db819c7f..91b1ae333 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go @@ -21,6 +21,7 @@ import ( "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -60,7 +61,7 @@ func (o *OpenAPI) MarshalJSON() ([]byte, error) { return json.Marshal(&p) } -func (o *OpenAPI) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (o *OpenAPI) MarshalJSONTo(enc *jsontext.Encoder) error { type OpenAPIOmitZero struct { Version string `json:"openapi"` Info *spec.Info `json:"info"` @@ -71,5 +72,5 @@ func (o *OpenAPI) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encode ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"` } x := (*OpenAPIOmitZero)(o) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go index 05310c46b..5aa66ae25 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) const ( @@ -65,18 +66,18 @@ func (h Header) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3, b4), nil } -func (h Header) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (h Header) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` - Extensions + Extensions Extensions `json:",inline"` HeaderProps } x.CommonValidations = commonValidationsOmitZero(h.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(h.SimpleSchema) x.Extensions = internal.SanitizeExtensions(h.Extensions) x.HeaderProps = h.HeaderProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON unmarshals this header from JSON @@ -97,15 +98,15 @@ func (h *Header) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &h.HeaderProps) } -func (h *Header) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (h *Header) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { CommonValidations SimpleSchema - Extensions + Extensions Extensions `json:",inline"` HeaderProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go index d667b705b..8d002a1c5 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go @@ -21,6 +21,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // Extensions vendor specific extensions @@ -183,14 +184,14 @@ func (i Info) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (i Info) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (i Info) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` InfoProps } x.Extensions = i.Extensions x.InfoProps = i.InfoProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON marshal this from JSON @@ -205,12 +206,12 @@ func (i *Info) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &i.VendorExtensible) } -func (i *Info) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (i *Info) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` InfoProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } i.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go index 4132467d2..6fbb19a46 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) const ( @@ -122,13 +123,13 @@ func (i *Items) UnmarshalJSON(data []byte) error { return nil } -func (i *Items) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (i *Items) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { CommonValidations SimpleSchema - Extensions + Extensions Extensions `json:",inline"` } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := i.Refable.Ref.fromMap(x.Extensions); err != nil { @@ -165,16 +166,16 @@ func (i Items) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b4, b3, b1, b2), nil } -func (i Items) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (i Items) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` Ref string `json:"$ref,omitempty"` - Extensions + Extensions Extensions `json:",inline"` } x.CommonValidations = commonValidationsOmitZero(i.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(i.SimpleSchema) x.Ref = i.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(i.Extensions) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go index 63eed3460..99b620f94 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // OperationProps describes an operation @@ -104,13 +105,13 @@ func (o *Operation) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &o.VendorExtensible) } -func (o *Operation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (o *Operation) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type OperationPropsNoMethods OperationProps // strip MarshalJSON method var x struct { - Extensions + Extensions Extensions `json:",inline"` OperationPropsNoMethods } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } o.Extensions = internal.SanitizeExtensions(x.Extensions) @@ -135,12 +136,12 @@ func (o Operation) MarshalJSON() ([]byte, error) { return concated, nil } -func (o Operation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (o Operation) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` OperationProps operationPropsOmitZero `json:",inline"` } x.Extensions = internal.SanitizeExtensions(o.Extensions) x.OperationProps = operationPropsOmitZero(o.OperationProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go index 53d1e0aa9..f2e61a721 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // ParamProps describes the specific attributes of an operation parameter @@ -107,14 +108,14 @@ func (p *Parameter) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &p.ParamProps) } -func (p *Parameter) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *Parameter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { CommonValidations SimpleSchema - Extensions + Extensions Extensions `json:",inline"` ParamProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := p.Refable.Ref.fromMap(x.Extensions); err != nil { @@ -155,18 +156,18 @@ func (p Parameter) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b3, b1, b2, b4, b5), nil } -func (p Parameter) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p Parameter) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` ParamProps paramPropsOmitZero `json:",inline"` Ref string `json:"$ref,omitempty"` - Extensions + Extensions Extensions `json:",inline"` } x.CommonValidations = commonValidationsOmitZero(p.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(p.SimpleSchema) x.Extensions = internal.SanitizeExtensions(p.Extensions) x.ParamProps = paramPropsOmitZero(p.ParamProps) x.Ref = p.Refable.Ref.String() - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go index 1d1588cb9..f2a0d9542 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // PathItemProps the path item specific properties @@ -61,13 +62,13 @@ func (p *PathItem) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &p.PathItemProps) } -func (p *PathItem) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *PathItem) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` PathItemProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } if err := p.Refable.Ref.fromMap(x.Extensions); err != nil { @@ -100,14 +101,14 @@ func (p PathItem) MarshalJSON() ([]byte, error) { return concated, nil } -func (p PathItem) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p PathItem) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Ref string `json:"$ref,omitempty"` - Extensions + Ref string `json:"$ref,omitempty"` + Extensions Extensions `json:",inline"` PathItemProps } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.PathItemProps = p.PathItemProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go index 18f6a9f42..23b72ccce 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go @@ -22,6 +22,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // Paths holds the relative paths to the individual endpoints. @@ -70,7 +71,7 @@ func (p *Paths) UnmarshalJSON(data []byte) error { return nil } -func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (p *Paths) UnmarshalJSONFrom(dec *jsontext.Decoder) error { tok, err := dec.ReadToken() if err != nil { return err @@ -94,7 +95,7 @@ func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Deco switch k := tok.String(); { case internal.IsExtensionKey(k): ext = nil - if err := opts.UnmarshalNext(dec, &ext); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &ext); err != nil { return err } @@ -104,7 +105,7 @@ func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Deco p.Extensions[k] = ext case len(k) > 0 && k[0] == '/': pi = PathItem{} - if err := opts.UnmarshalNext(dec, &pi); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &pi); err != nil { return err } @@ -148,7 +149,7 @@ func (p Paths) MarshalJSON() ([]byte, error) { return concated, nil } -func (p Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (p Paths) MarshalJSONTo(enc *jsontext.Encoder) error { m := make(map[string]any, len(p.Extensions)+len(p.Paths)) for k, v := range p.Extensions { if internal.IsExtensionKey(k) { @@ -160,5 +161,5 @@ func (p Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) m[k] = v } } - return opts.MarshalNext(enc, m) + return jsonv2.MarshalEncode(enc, m) } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go index 3ff1fe132..585a93acc 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // ResponseProps properties specific to a response @@ -67,13 +68,13 @@ func (r *Response) UnmarshalJSON(data []byte) error { return nil } -func (r *Response) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (r *Response) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { ResponseProps - Extensions + Extensions Extensions `json:",inline"` } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } @@ -106,16 +107,16 @@ func (r Response) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3), nil } -func (r Response) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r Response) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Ref string `json:"$ref,omitempty"` - Extensions + Ref string `json:"$ref,omitempty"` + Extensions Extensions `json:",inline"` ResponseProps responsePropsOmitZero `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.ResponseProps = responsePropsOmitZero(r.ResponseProps) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // NewResponse creates a new response instance diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go index d9ad760a4..a1a3d0fd5 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go @@ -23,6 +23,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // Responses is a container for the expected responses of an operation. @@ -78,11 +79,11 @@ func (r Responses) MarshalJSON() ([]byte, error) { return concated, nil } -func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (r Responses) MarshalJSONTo(enc *jsontext.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { - ArbitraryKeys - Default *Response `json:"default,omitempty"` + ArbitraryKeys ArbitraryKeys `json:",inline"` + Default *Response `json:"default,omitempty"` } x.ArbitraryKeys = make(map[string]any, len(r.Extensions)+len(r.StatusCodeResponses)) for k, v := range r.Extensions { @@ -94,7 +95,7 @@ func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encod x.ArbitraryKeys[strconv.Itoa(k)] = v } x.Default = r.Default - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // ResponsesProps describes all responses for an operation. @@ -150,7 +151,7 @@ func (r *ResponsesProps) UnmarshalJSON(data []byte) error { return nil } -func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) (err error) { +func (r *Responses) UnmarshalJSONFrom(dec *jsontext.Decoder) (err error) { tok, err := dec.ReadToken() if err != nil { return err @@ -172,7 +173,7 @@ func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2. switch k := tok.String(); { case internal.IsExtensionKey(k): ext = nil - if err := opts.UnmarshalNext(dec, &ext); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &ext); err != nil { return err } @@ -182,7 +183,7 @@ func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2. r.Extensions[k] = ext case k == "default": resp = Response{} - if err := opts.UnmarshalNext(dec, &resp); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &resp); err != nil { return err } @@ -191,7 +192,7 @@ func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2. default: if nk, err := strconv.Atoi(k); err == nil { resp = Response{} - if err := opts.UnmarshalNext(dec, &resp); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &resp); err != nil { return err } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go index dfbb2e05c..6c0c6fc14 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go @@ -23,6 +23,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // BooleanProperty creates a boolean property @@ -517,10 +518,10 @@ func (s Schema) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil } -func (s Schema) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s Schema) MarshalJSONTo(enc *jsontext.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { - ArbitraryKeys + ArbitraryKeys ArbitraryKeys `json:",inline"` SchemaProps schemaPropsOmitZero `json:",inline"` SwaggerSchemaProps swaggerSchemaPropsOmitZero `json:",inline"` Schema string `json:"$schema,omitempty"` @@ -539,7 +540,7 @@ func (s Schema) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) x.SwaggerSchemaProps = swaggerSchemaPropsOmitZero(s.SwaggerSchemaProps) x.Ref = s.Ref.String() x.Schema = string(s.Schema) - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON marshal this from JSON @@ -595,13 +596,13 @@ func (s *Schema) UnmarshalJSON(data []byte) error { return nil } -func (s *Schema) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *Schema) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` SchemaProps SwaggerSchemaProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go index e2b7da14c..7c7b6bdd8 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section @@ -60,14 +61,14 @@ func (s SecurityScheme) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (s SecurityScheme) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s SecurityScheme) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` SecuritySchemeProps } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SecuritySchemeProps = s.SecuritySchemeProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON marshal this from JSON @@ -78,12 +79,12 @@ func (s *SecurityScheme) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &s.VendorExtensible) } -func (s *SecurityScheme) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *SecurityScheme) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` SecuritySchemeProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go index c8f3beaa3..533b7cc83 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go @@ -21,6 +21,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // Swagger this is the root document object for the API specification. @@ -50,14 +51,14 @@ func (s Swagger) MarshalJSON() ([]byte, error) { } // MarshalJSON marshals this swagger structure to json -func (s Swagger) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s Swagger) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` SwaggerProps } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SwaggerProps = s.SwaggerProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON unmarshals a swagger spec from json @@ -76,16 +77,16 @@ func (s *Swagger) UnmarshalJSON(data []byte) error { return nil } -func (s *Swagger) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *Swagger) UnmarshalJSONFrom(dec *jsontext.Decoder) error { // Note: If you're willing to make breaking changes, it is possible to // optimize this and other usages of this pattern: // https://github.com/kubernetes/kube-openapi/pull/319#discussion_r983165948 var x struct { - Extensions + Extensions Extensions `json:",inline"` SwaggerProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) @@ -146,15 +147,15 @@ func (s SchemaOrBool) MarshalJSON() ([]byte, error) { } // MarshalJSON convert this object to JSON -func (s SchemaOrBool) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s SchemaOrBool) MarshalJSONTo(enc *jsontext.Encoder) error { if s.Schema != nil { - return opts.MarshalNext(enc, s.Schema) + return jsonv2.MarshalEncode(enc, s.Schema) } if s.Schema == nil && !s.Allows { - return enc.WriteToken(jsonv2.False) + return enc.WriteToken(jsontext.False) } - return enc.WriteToken(jsonv2.True) + return enc.WriteToken(jsontext.True) } // UnmarshalJSON converts this bool or schema object from a JSON structure @@ -178,17 +179,17 @@ func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { return nil } -func (s *SchemaOrBool) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *SchemaOrBool) UnmarshalJSONFrom(dec *jsontext.Decoder) error { switch k := dec.PeekKind(); k { case '{': - err := opts.UnmarshalNext(dec, &s.Schema) + err := jsonv2.UnmarshalDecode(dec, &s.Schema) if err != nil { return err } s.Allows = true return nil case 't', 'f': - err := opts.UnmarshalNext(dec, &s.Allows) + err := jsonv2.UnmarshalDecode(dec, &s.Allows) if err != nil { return err } @@ -219,14 +220,14 @@ func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { } // MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrStringArray) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s SchemaOrStringArray) MarshalJSONTo(enc *jsontext.Encoder) error { if len(s.Property) > 0 { - return opts.MarshalNext(enc, s.Property) + return jsonv2.MarshalEncode(enc, s.Property) } if s.Schema != nil { - return opts.MarshalNext(enc, s.Schema) + return jsonv2.MarshalEncode(enc, s.Schema) } - return enc.WriteToken(jsonv2.Null) + return enc.WriteToken(jsontext.Null) } // UnmarshalJSON converts this schema object or array from a JSON structure @@ -256,12 +257,12 @@ func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { return nil } -func (s *SchemaOrStringArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *SchemaOrStringArray) UnmarshalJSONFrom(dec *jsontext.Decoder) error { switch dec.PeekKind() { case '{': - return opts.UnmarshalNext(dec, &s.Schema) + return jsonv2.UnmarshalDecode(dec, &s.Schema) case '[': - return opts.UnmarshalNext(dec, &s.Property) + return jsonv2.UnmarshalDecode(dec, &s.Property) default: _, err := dec.ReadValue() return err @@ -332,14 +333,14 @@ func (s *StringOrArray) UnmarshalJSON(data []byte) error { } } -func (s *StringOrArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *StringOrArray) UnmarshalJSONFrom(dec *jsontext.Decoder) error { switch k := dec.PeekKind(); k { case '[': *s = StringOrArray{} - return opts.UnmarshalNext(dec, (*[]string)(s)) + return jsonv2.UnmarshalDecode(dec, (*[]string)(s)) case '"': *s = StringOrArray{""} - return opts.UnmarshalNext(dec, &(*s)[0]) + return jsonv2.UnmarshalDecode(dec, &(*s)[0]) case 'n': // Throw out null token _, _ = dec.ReadToken() @@ -392,11 +393,11 @@ func (s SchemaOrArray) MarshalJSON() ([]byte, error) { } // MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrArray) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (s SchemaOrArray) MarshalJSONTo(enc *jsontext.Encoder) error { if s.Schemas != nil { - return opts.MarshalNext(enc, s.Schemas) + return jsonv2.MarshalEncode(enc, s.Schemas) } - return opts.MarshalNext(enc, s.Schema) + return jsonv2.MarshalEncode(enc, s.Schema) } // UnmarshalJSON converts this schema object or array from a JSON structure @@ -426,12 +427,12 @@ func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { return nil } -func (s *SchemaOrArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (s *SchemaOrArray) UnmarshalJSONFrom(dec *jsontext.Decoder) error { switch dec.PeekKind() { case '{': - return opts.UnmarshalNext(dec, &s.Schema) + return jsonv2.UnmarshalDecode(dec, &s.Schema) case '[': - return opts.UnmarshalNext(dec, &s.Schemas) + return jsonv2.UnmarshalDecode(dec, &s.Schemas) default: _, err := dec.ReadValue() return err diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go index d105d52ca..89c3d0d82 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go @@ -20,6 +20,7 @@ import ( "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" + "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext" ) // TagProps describe a tag entry in the top level tags section of a swagger spec @@ -55,14 +56,14 @@ func (t Tag) MarshalJSON() ([]byte, error) { return swag.ConcatJSON(b1, b2), nil } -func (t Tag) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { +func (t Tag) MarshalJSONTo(enc *jsontext.Encoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` TagProps } x.Extensions = internal.SanitizeExtensions(t.Extensions) x.TagProps = t.TagProps - return opts.MarshalNext(enc, x) + return jsonv2.MarshalEncode(enc, x) } // UnmarshalJSON marshal this from JSON @@ -77,12 +78,12 @@ func (t *Tag) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &t.VendorExtensible) } -func (t *Tag) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { +func (t *Tag) UnmarshalJSONFrom(dec *jsontext.Decoder) error { var x struct { - Extensions + Extensions Extensions `json:",inline"` TagProps } - if err := opts.UnmarshalNext(dec, &x); err != nil { + if err := jsonv2.UnmarshalDecode(dec, &x); err != nil { return err } t.Extensions = internal.SanitizeExtensions(x.Extensions) diff --git a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/validate/result.go b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/validate/result.go index b3868b19d..870faf29a 100644 --- a/constraint/vendor/k8s.io/kube-openapi/pkg/validation/validate/result.go +++ b/constraint/vendor/k8s.io/kube-openapi/pkg/validation/validate/result.go @@ -135,13 +135,13 @@ 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, fmt.Errorf("%s", 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, fmt.Errorf("%s", strings.TrimPrefix(e.Error(), "IMPORTANT!"))) } } strippedResult := new(Result) diff --git a/constraint/vendor/k8s.io/utils/ptr/OWNERS b/constraint/vendor/k8s.io/utils/ptr/OWNERS index 0d6392752..55da8262a 100644 --- a/constraint/vendor/k8s.io/utils/ptr/OWNERS +++ b/constraint/vendor/k8s.io/utils/ptr/OWNERS @@ -2,9 +2,11 @@ approvers: - apelisse +- skitt - stewart-yu - thockin reviewers: - apelisse +- skitt - stewart-yu - thockin diff --git a/constraint/vendor/k8s.io/utils/ptr/ptr.go b/constraint/vendor/k8s.io/utils/ptr/ptr.go index 659ed3b9e..ea847fd36 100644 --- a/constraint/vendor/k8s.io/utils/ptr/ptr.go +++ b/constraint/vendor/k8s.io/utils/ptr/ptr.go @@ -51,7 +51,7 @@ func To[T any](v T) *T { return &v } -// Deref dereferences ptr and returns the value it points to if no nil, or else +// Deref dereferences ptr and returns the value it points to if not nil, or else // returns def. func Deref[T any](ptr *T, def T) T { if ptr != nil { diff --git a/constraint/vendor/modules.txt b/constraint/vendor/modules.txt index 83ddb5052..7bd8fbc4e 100644 --- a/constraint/vendor/modules.txt +++ b/constraint/vendor/modules.txt @@ -40,7 +40,7 @@ github.com/felixge/httpsnoop ## explicit; go 1.23 github.com/fsnotify/fsnotify github.com/fsnotify/fsnotify/internal -# github.com/fxamacker/cbor/v2 v2.9.0 +# github.com/fxamacker/cbor/v2 v2.9.1 ## explicit; go 1.20 github.com/fxamacker/cbor/v2 # github.com/go-logr/logr v1.4.4 @@ -50,16 +50,53 @@ github.com/go-logr/logr/funcr # github.com/go-logr/stdr v1.2.2 ## explicit; go 1.16 github.com/go-logr/stdr -# github.com/go-openapi/jsonpointer v0.21.0 -## explicit; go 1.20 +# github.com/go-openapi/jsonpointer v1.0.0 +## explicit; go 1.25.0 github.com/go-openapi/jsonpointer -# github.com/go-openapi/jsonreference v0.20.2 -## explicit; go 1.13 +github.com/go-openapi/jsonpointer/jsonname +# github.com/go-openapi/jsonreference v1.0.0 +## explicit; go 1.25.0 github.com/go-openapi/jsonreference github.com/go-openapi/jsonreference/internal -# github.com/go-openapi/swag v0.23.0 -## explicit; go 1.20 +# github.com/go-openapi/swag v0.27.1 +## explicit; go 1.25.0 github.com/go-openapi/swag +# github.com/go-openapi/swag/cmdutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/cmdutils +# github.com/go-openapi/swag/conv v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/conv +# github.com/go-openapi/swag/fileutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/fileutils +# github.com/go-openapi/swag/jsonutils v0.27.1 +## explicit; go 1.25.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.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/loading +# github.com/go-openapi/swag/mangling v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/mangling +# github.com/go-openapi/swag/netutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/netutils +# github.com/go-openapi/swag/pools v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/pools +# github.com/go-openapi/swag/stringutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/stringutils +# github.com/go-openapi/swag/typeutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/typeutils +# github.com/go-openapi/swag/yamlutils v0.27.1 +## explicit; go 1.25.0 +github.com/go-openapi/swag/yamlutils # github.com/gobwas/glob v0.2.3 ## explicit github.com/gobwas/glob @@ -86,7 +123,7 @@ github.com/goccy/go-json/internal/runtime github.com/golang/glog github.com/golang/glog/internal/logsink github.com/golang/glog/internal/stackdump -# github.com/google/cel-go v0.29.0 +# github.com/google/cel-go v0.29.2 ## explicit; go 1.23.0 github.com/google/cel-go/cel github.com/google/cel-go/checker @@ -137,9 +174,6 @@ github.com/grpc-ecosystem/grpc-gateway/v2/utilities # 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 @@ -195,11 +229,6 @@ github.com/lestrrat-go/jwx/v3/transform # github.com/lestrrat-go/option/v2 v2.0.0 ## explicit; go 1.23 github.com/lestrrat-go/option/v2 -# github.com/mailru/easyjson v0.7.7 -## explicit; go 1.12 -github.com/mailru/easyjson/buffer -github.com/mailru/easyjson/jlexer -github.com/mailru/easyjson/jwriter # github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd ## explicit github.com/modern-go/concurrent @@ -392,7 +421,6 @@ go.opentelemetry.io/otel/internal/baggage go.opentelemetry.io/otel/internal/errorhandler go.opentelemetry.io/otel/internal/global go.opentelemetry.io/otel/propagation -go.opentelemetry.io/otel/semconv/v1.17.0 go.opentelemetry.io/otel/semconv/v1.37.0 go.opentelemetry.io/otel/semconv/v1.41.0 go.opentelemetry.io/otel/semconv/v1.41.0/httpconv @@ -450,8 +478,8 @@ go.yaml.in/yaml/v3 # golang.org/x/crypto v0.54.0 ## explicit; go 1.25.0 golang.org/x/crypto/pbkdf2 -# golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 -## explicit; go 1.24.0 +# golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f +## explicit; go 1.25.0 golang.org/x/exp/slices # golang.org/x/net v0.57.0 ## explicit; go 1.25.0 @@ -644,17 +672,13 @@ 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.36.4 +# k8s.io/api v0.37.0 ## explicit; go 1.26.0 k8s.io/api/admission/v1 k8s.io/api/admissionregistration/v1 k8s.io/api/admissionregistration/v1alpha1 k8s.io/api/admissionregistration/v1beta1 k8s.io/api/apidiscovery/v2 -k8s.io/api/apidiscovery/v2beta1 k8s.io/api/apiserverinternal/v1alpha1 k8s.io/api/apps/v1 k8s.io/api/apps/v1beta1 @@ -684,6 +708,7 @@ k8s.io/api/flowcontrol/v1 k8s.io/api/flowcontrol/v1beta1 k8s.io/api/flowcontrol/v1beta2 k8s.io/api/flowcontrol/v1beta3 +k8s.io/api/lifecycle/v1alpha1 k8s.io/api/networking/v1 k8s.io/api/networking/v1beta1 k8s.io/api/node/v1 @@ -699,13 +724,14 @@ k8s.io/api/resource/v1alpha3 k8s.io/api/resource/v1beta1 k8s.io/api/resource/v1beta2 k8s.io/api/scheduling/v1 -k8s.io/api/scheduling/v1alpha2 +k8s.io/api/scheduling/v1alpha3 k8s.io/api/scheduling/v1beta1 k8s.io/api/storage/v1 k8s.io/api/storage/v1alpha1 k8s.io/api/storage/v1beta1 +k8s.io/api/storagemigration/v1 k8s.io/api/storagemigration/v1beta1 -# k8s.io/apiextensions-apiserver v0.36.4 +# k8s.io/apiextensions-apiserver v0.37.0 ## explicit; go 1.26.0 k8s.io/apiextensions-apiserver/pkg/apihelpers k8s.io/apiextensions-apiserver/pkg/apis/apiextensions @@ -721,12 +747,13 @@ k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning k8s.io/apiextensions-apiserver/pkg/apiserver/validation k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/apiextensions/v1beta1 +k8s.io/apiextensions-apiserver/pkg/client/applyconfiguration/internal k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1 k8s.io/apiextensions-apiserver/pkg/features -# k8s.io/apimachinery v0.36.4 +# k8s.io/apimachinery v0.37.0 ## explicit; go 1.26.0 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors @@ -786,7 +813,7 @@ k8s.io/apimachinery/pkg/version k8s.io/apimachinery/pkg/watch k8s.io/apimachinery/third_party/forked/golang/json k8s.io/apimachinery/third_party/forked/golang/reflect -# k8s.io/apiserver v0.36.4 +# k8s.io/apiserver v0.37.0 ## explicit; go 1.26.0 k8s.io/apiserver/pkg/apis/apiserver k8s.io/apiserver/pkg/apis/apiserver/install @@ -815,7 +842,7 @@ k8s.io/apiserver/pkg/util/feature k8s.io/apiserver/pkg/util/webhook k8s.io/apiserver/pkg/util/x509metrics k8s.io/apiserver/pkg/warning -# k8s.io/client-go v0.36.4 +# k8s.io/client-go v0.37.0 ## explicit; go 1.26.0 k8s.io/client-go/applyconfigurations/admissionregistration/v1 k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1 @@ -845,6 +872,7 @@ k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1 k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2 k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3 k8s.io/client-go/applyconfigurations/internal +k8s.io/client-go/applyconfigurations/lifecycle/v1alpha1 k8s.io/client-go/applyconfigurations/meta/v1 k8s.io/client-go/applyconfigurations/networking/v1 k8s.io/client-go/applyconfigurations/networking/v1beta1 @@ -861,11 +889,12 @@ k8s.io/client-go/applyconfigurations/resource/v1alpha3 k8s.io/client-go/applyconfigurations/resource/v1beta1 k8s.io/client-go/applyconfigurations/resource/v1beta2 k8s.io/client-go/applyconfigurations/scheduling/v1 -k8s.io/client-go/applyconfigurations/scheduling/v1alpha2 +k8s.io/client-go/applyconfigurations/scheduling/v1alpha3 k8s.io/client-go/applyconfigurations/scheduling/v1beta1 k8s.io/client-go/applyconfigurations/storage/v1 k8s.io/client-go/applyconfigurations/storage/v1alpha1 k8s.io/client-go/applyconfigurations/storage/v1beta1 +k8s.io/client-go/applyconfigurations/storagemigration/v1 k8s.io/client-go/applyconfigurations/storagemigration/v1beta1 k8s.io/client-go/discovery k8s.io/client-go/dynamic @@ -912,6 +941,8 @@ k8s.io/client-go/informers/flowcontrol/v1beta1 k8s.io/client-go/informers/flowcontrol/v1beta2 k8s.io/client-go/informers/flowcontrol/v1beta3 k8s.io/client-go/informers/internalinterfaces +k8s.io/client-go/informers/lifecycle +k8s.io/client-go/informers/lifecycle/v1alpha1 k8s.io/client-go/informers/networking k8s.io/client-go/informers/networking/v1 k8s.io/client-go/informers/networking/v1beta1 @@ -933,13 +964,14 @@ k8s.io/client-go/informers/resource/v1beta1 k8s.io/client-go/informers/resource/v1beta2 k8s.io/client-go/informers/scheduling k8s.io/client-go/informers/scheduling/v1 -k8s.io/client-go/informers/scheduling/v1alpha2 +k8s.io/client-go/informers/scheduling/v1alpha3 k8s.io/client-go/informers/scheduling/v1beta1 k8s.io/client-go/informers/storage k8s.io/client-go/informers/storage/v1 k8s.io/client-go/informers/storage/v1alpha1 k8s.io/client-go/informers/storage/v1beta1 k8s.io/client-go/informers/storagemigration +k8s.io/client-go/informers/storagemigration/v1 k8s.io/client-go/informers/storagemigration/v1beta1 k8s.io/client-go/kubernetes k8s.io/client-go/kubernetes/scheme @@ -975,6 +1007,7 @@ k8s.io/client-go/kubernetes/typed/flowcontrol/v1 k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1 k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2 k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3 +k8s.io/client-go/kubernetes/typed/lifecycle/v1alpha1 k8s.io/client-go/kubernetes/typed/networking/v1 k8s.io/client-go/kubernetes/typed/networking/v1beta1 k8s.io/client-go/kubernetes/typed/node/v1 @@ -990,11 +1023,12 @@ k8s.io/client-go/kubernetes/typed/resource/v1alpha3 k8s.io/client-go/kubernetes/typed/resource/v1beta1 k8s.io/client-go/kubernetes/typed/resource/v1beta2 k8s.io/client-go/kubernetes/typed/scheduling/v1 -k8s.io/client-go/kubernetes/typed/scheduling/v1alpha2 +k8s.io/client-go/kubernetes/typed/scheduling/v1alpha3 k8s.io/client-go/kubernetes/typed/scheduling/v1beta1 k8s.io/client-go/kubernetes/typed/storage/v1 k8s.io/client-go/kubernetes/typed/storage/v1alpha1 k8s.io/client-go/kubernetes/typed/storage/v1beta1 +k8s.io/client-go/kubernetes/typed/storagemigration/v1 k8s.io/client-go/kubernetes/typed/storagemigration/v1beta1 k8s.io/client-go/listers k8s.io/client-go/listers/admissionregistration/v1 @@ -1024,6 +1058,7 @@ k8s.io/client-go/listers/flowcontrol/v1 k8s.io/client-go/listers/flowcontrol/v1beta1 k8s.io/client-go/listers/flowcontrol/v1beta2 k8s.io/client-go/listers/flowcontrol/v1beta3 +k8s.io/client-go/listers/lifecycle/v1alpha1 k8s.io/client-go/listers/networking/v1 k8s.io/client-go/listers/networking/v1beta1 k8s.io/client-go/listers/node/v1 @@ -1039,11 +1074,12 @@ k8s.io/client-go/listers/resource/v1alpha3 k8s.io/client-go/listers/resource/v1beta1 k8s.io/client-go/listers/resource/v1beta2 k8s.io/client-go/listers/scheduling/v1 -k8s.io/client-go/listers/scheduling/v1alpha2 +k8s.io/client-go/listers/scheduling/v1alpha3 k8s.io/client-go/listers/scheduling/v1beta1 k8s.io/client-go/listers/storage/v1 k8s.io/client-go/listers/storage/v1alpha1 k8s.io/client-go/listers/storage/v1beta1 +k8s.io/client-go/listers/storagemigration/v1 k8s.io/client-go/listers/storagemigration/v1beta1 k8s.io/client-go/metadata k8s.io/client-go/openapi @@ -1080,7 +1116,7 @@ k8s.io/client-go/util/keyutil k8s.io/client-go/util/retry k8s.io/client-go/util/watchlist k8s.io/client-go/util/workqueue -# k8s.io/component-base v0.36.4 +# k8s.io/component-base v0.37.0 ## explicit; go 1.26.0 k8s.io/component-base/cli/flag k8s.io/component-base/compatibility @@ -1107,13 +1143,18 @@ k8s.io/klog/v2/internal/severity k8s.io/klog/v2/internal/sloghandler k8s.io/klog/v2/internal/verbosity k8s.io/klog/v2/textlogger -# k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a -## explicit; go 1.23.0 +# k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad +## explicit; go 1.25.0 k8s.io/kube-openapi/pkg/cached k8s.io/kube-openapi/pkg/common k8s.io/kube-openapi/pkg/handler3 k8s.io/kube-openapi/pkg/internal k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json +k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal +k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags +k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts +k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire +k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext k8s.io/kube-openapi/pkg/internal/third_party/govalidator k8s.io/kube-openapi/pkg/schemaconv k8s.io/kube-openapi/pkg/spec3 @@ -1124,7 +1165,7 @@ k8s.io/kube-openapi/pkg/validation/spec k8s.io/kube-openapi/pkg/validation/strfmt k8s.io/kube-openapi/pkg/validation/strfmt/bson k8s.io/kube-openapi/pkg/validation/validate -# k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 +# k8s.io/utils v0.0.0-20260626114624-be93311217bd ## explicit; go 1.23 k8s.io/utils/buffer k8s.io/utils/clock @@ -1136,19 +1177,22 @@ k8s.io/utils/net k8s.io/utils/path k8s.io/utils/ptr k8s.io/utils/trace -# sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 -## explicit; go 1.21 +# sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 +## explicit; go 1.24.0 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/controller-runtime v0.24.1 +# sigs.k8s.io/controller-runtime v0.25.0 ## explicit; go 1.26.0 +sigs.k8s.io/controller-runtime/pkg/cache/cacheapi sigs.k8s.io/controller-runtime/pkg/certwatcher sigs.k8s.io/controller-runtime/pkg/certwatcher/metrics sigs.k8s.io/controller-runtime/pkg/client sigs.k8s.io/controller-runtime/pkg/client/apiutil sigs.k8s.io/controller-runtime/pkg/client/config +sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler +sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier sigs.k8s.io/controller-runtime/pkg/conversion sigs.k8s.io/controller-runtime/pkg/envtest sigs.k8s.io/controller-runtime/pkg/internal/flock @@ -1169,7 +1213,7 @@ sigs.k8s.io/json/internal/golang/encoding/json ## explicit; go 1.18 sigs.k8s.io/randfill sigs.k8s.io/randfill/bytesource -# sigs.k8s.io/structured-merge-diff/v6 v6.3.3 +# sigs.k8s.io/structured-merge-diff/v6 v6.4.2 ## explicit; go 1.23 sigs.k8s.io/structured-merge-diff/v6/fieldpath sigs.k8s.io/structured-merge-diff/v6/merge diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go new file mode 100644 index 000000000..9f3aa62ee --- /dev/null +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cacheapi/cacheapi.go @@ -0,0 +1,153 @@ +/* +Copyright 2026 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 cacheapi + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + toolscache "k8s.io/client-go/tools/cache" +) + +// InformerGetOptions defines the behavior of how informers are retrieved. +type InformerGetOptions struct { + // BlockUntilSynced controls if the informer retrieval will block until the informer is synced. Defaults to `true`. + BlockUntilSynced *bool +} + +// InformerGetOption defines an option that alters the behavior of how informers are retrieved. +type InformerGetOption func(*InformerGetOptions) + +// BlockUntilSynced determines whether a get request for an informer should block +// until the informer's cache has synced. +func BlockUntilSynced(shouldBlock bool) InformerGetOption { + return func(opts *InformerGetOptions) { + opts.BlockUntilSynced = &shouldBlock + } +} + +// Object is a Kubernetes object, allows functions to work indistinctly with +// any resource that implements both Object interfaces. +// +// Semantically, these are objects which are both serializable (runtime.Object) +// and identifiable (metav1.Object) -- think any object which you could write +// as YAML or JSON, and then `kubectl create`. +// +// Code-wise, this means that any object which embeds both ObjectMeta (which +// provides metav1.Object) and TypeMeta (which provides half of runtime.Object) +// and has a `DeepCopyObject` implementation (the other half of runtime.Object) +// will implement this by default. +// +// For example, nearly all the built-in types are Objects, as well as all +// KubeBuilder-generated CRDs (unless you do something real funky to them). +// +// By and large, most things that implement runtime.Object also implement +// Object -- it's very rare to have *just* a runtime.Object implementation (the +// cases tend to be funky built-in types like Webhook payloads that don't have +// a `metadata` field). +// +// Notice that XYZList types are distinct: they implement ObjectList instead. +type Object interface { + metav1.Object + runtime.Object +} + +// IndexerFunc knows how to take an object and turn it into a series +// of non-namespaced keys. Namespaced objects are automatically given +// namespaced and non-spaced variants, so keys do not need to include namespace. +type IndexerFunc func(Object) []string + +// FieldIndexer knows how to index over a particular "field" such that it +// can later be used by a field selector. +type FieldIndexer interface { + // IndexField adds an index with the given field name on the given object type + // by using the given function to extract the value for that field. If you want + // compatibility with the Kubernetes API server, only return one key, and only use + // fields that the API server supports. Otherwise, you can return multiple keys, + // and "equality" in the field selector means that at least one key matches the value. + // The FieldIndexer will automatically take care of indexing over namespace + // and supporting efficient all-namespace queries. + IndexField(ctx context.Context, obj Object, field string, extractValue IndexerFunc) error +} + +// Informers knows how to create or fetch informers for different +// group-version-kinds, and add indices to those informers. It's safe to call +// GetInformer from multiple threads. +type Informers interface { + // GetInformer fetches or constructs an informer for the given object that corresponds to a single + // API kind and resource. + GetInformer(ctx context.Context, obj Object, opts ...InformerGetOption) (Informer, error) + + // GetInformerForKind is similar to GetInformer, except that it takes a group-version-kind, instead + // of the underlying object. + GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind, opts ...InformerGetOption) (Informer, error) + + // RemoveInformer removes an informer entry and stops it if it was running. + RemoveInformer(ctx context.Context, obj Object) error + + // Start runs all the informers known to this cache until the context is closed. + // It blocks. + Start(ctx context.Context) error + + // WaitForCacheSync waits for all the caches to sync. Returns false if it could not sync a cache. + WaitForCacheSync(ctx context.Context) bool + + // FieldIndexer adds indices to the managed informers. + FieldIndexer +} + +// Informer allows you to interact with the underlying informer. +type Informer interface { + // AddEventHandler adds an event handler to the shared informer using the shared informer's resync + // period. Events to a single handler are delivered sequentially, but there is no coordination + // between different handlers. + // It returns a registration handle for the handler that can be used to remove + // the handler again and an error if the handler cannot be added. + AddEventHandler(handler toolscache.ResourceEventHandler) (toolscache.ResourceEventHandlerRegistration, error) + + // AddEventHandlerWithResyncPeriod adds an event handler to the shared informer using the + // specified resync period. Events to a single handler are delivered sequentially, but there is + // no coordination between different handlers. + // It returns a registration handle for the handler that can be used to remove + // the handler again and an error if the handler cannot be added. + AddEventHandlerWithResyncPeriod(handler toolscache.ResourceEventHandler, resyncPeriod time.Duration) (toolscache.ResourceEventHandlerRegistration, error) + + // AddEventHandlerWithOptions is a variant of AddEventHandlerWithResyncPeriod where + // all optional parameters are passed in as a struct. + AddEventHandlerWithOptions(handler toolscache.ResourceEventHandler, options toolscache.HandlerOptions) (toolscache.ResourceEventHandlerRegistration, error) + + // RemoveEventHandler removes a previously added event handler given by + // its registration handle. + // This function is guaranteed to be idempotent and thread-safe. + RemoveEventHandler(handle toolscache.ResourceEventHandlerRegistration) error + + // AddIndexers adds indexers to this store. It is valid to add indexers + // after an informer was started. + AddIndexers(indexers toolscache.Indexers) error + + // HasSynced return true if the informers underlying store has synced. + HasSynced() bool + + // HasSyncedChecker completes if the informers underlying store has synced. + HasSyncedChecker() toolscache.DoneChecker + + // IsStopped returns true if the informer has been stopped. + IsStopped() bool +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go index ad946daea..23d6103f6 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/client.go @@ -23,16 +23,21 @@ import ( "net/http" "strings" + "github.com/go-logr/logr" "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" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/metadata" "k8s.io/client-go/rest" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" + "sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier" "sigs.k8s.io/controller-runtime/pkg/log" ) @@ -71,6 +76,9 @@ type Options struct { // - FieldValidationStrict // For more details, see: https://kubernetes.io/docs/reference/using-api/api-concepts/#field-validation FieldValidation string + + // Log will be used by the client if it encounters any errors. + Log logr.Logger } // CacheOptions are options for creating a cache-backed client. @@ -85,6 +93,23 @@ type CacheOptions struct { // read unstructured objects or lists from the cache. // If false, unstructured objects will always result in a live lookup. Unstructured bool + + // EnableReadYourWritesConsistency controls if read requests against the cache will + // block until the cache observed all write requests that started before the read + // request. Lists will wait for all pending write requests to the gvk the List is for. + // + // The `DisableReadYourWritesConsistency` option can be used to disable this functionality + // for individual requests, both on reads to keep them from waiting and on writes to + // prevent them from blocking subsequent reads. + // + // The blocking is always scoped to the representation (typed, unstructured or + // PartialObjectMetadata), meaning a write only blocks reads of the same representation. + // + // This is an experimental feature, a form of this will be kept but both the details of + // how exactly it works and how exactly it is configured may change. + // + // Defaults to false. + EnableReadYourWritesConsistency *bool } // NewClientFunc allows a user to define how to create a client. @@ -113,9 +138,17 @@ type NewClientFunc func(config *rest.Config, options Options) (Client, error) // corresponding group, version, and kind for the given type. In the // case of unstructured types, the group, version, and kind will be extracted // from the corresponding fields on the object. -func New(config *rest.Config, options Options) (c Client, err error) { - c, err = newClient(config, options) - if err == nil && options.DryRun != nil && *options.DryRun { +func New(config *rest.Config, options Options) (Client, error) { + _, c, err := newClient(config, options) + if err != nil { + return nil, err + } + + return wrapClient(c, options), nil +} + +func wrapClient(c Client, options Options) Client { + if options.DryRun != nil && *options.DryRun { c = NewDryRunClient(c) } if fo := options.FieldOwner; fo != "" { @@ -125,12 +158,12 @@ func New(config *rest.Config, options Options) (c Client, err error) { c = WithFieldValidation(c, FieldValidation(fv)) } - return c, err + return c } -func newClient(config *rest.Config, options Options) (*client, error) { +func newClient(config *rest.Config, options Options) (*client, Client, error) { if config == nil { - return nil, fmt.Errorf("must provide non-nil rest.Config to client.New") + return nil, nil, fmt.Errorf("must provide non-nil rest.Config to client.New") } config = rest.CopyConfig(config) @@ -152,7 +185,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { var err error options.HTTPClient, err = rest.HTTPClientFor(config) if err != nil { - return nil, err + return nil, nil, err } } @@ -166,10 +199,14 @@ func newClient(config *rest.Config, options Options) (*client, error) { var err error options.Mapper, err = apiutil.NewDynamicRESTMapper(config, options.HTTPClient) if err != nil { - return nil, err + return nil, nil, err } } + if options.Log.IsZero() { + options.Log = log.Log.WithName("client") + } + resources := &clientRestResources{ httpClient: options.HTTPClient, config: config, @@ -182,7 +219,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { rawMetaClient, err := metadata.NewForConfigAndClient(metadata.ConfigFor(config), options.HTTPClient) if err != nil { - return nil, fmt.Errorf("unable to construct metadata-only client for use as part of client: %w", err) + return nil, nil, fmt.Errorf("unable to construct metadata-only client for use as part of client: %w", err) } c := &client{ @@ -202,7 +239,7 @@ func newClient(config *rest.Config, options Options) (*client, error) { mapper: options.Mapper, } if options.Cache == nil || options.Cache.Reader == nil { - return c, nil + return c, c, nil } // We want a cache if we're here. @@ -215,11 +252,26 @@ func newClient(config *rest.Config, options Options) (*client, error) { for _, obj := range options.Cache.DisableFor { gvk, err := c.GroupVersionKindFor(obj) if err != nil { - return nil, err + return nil, nil, err } c.uncachedGVKs[gvk] = struct{}{} } - return c, nil + + if !ptr.Deref(options.Cache.EnableReadYourWritesConsistency, false) { + return c, c, nil + } + + informerCache, isCache := options.Cache.Reader.(cacheapi.Informers) + if !isCache { + return nil, nil, fmt.Errorf("cache reader does not implement %T, can not provide ReadYourWritesConsistency", cacheapi.Informers(nil)) + } + + return c, newConsistentClient( + c, + informerCache, + writebarrier.NewWriteBarrier, + options.Log, + ), nil } var _ Client = &client{} @@ -319,11 +371,18 @@ func (c *client) Update(ctx context.Context, obj Object, opts ...UpdateOption) e // Delete implements client.Client. func (c *client) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { + _, err := c.delete(ctx, obj, opts...) + return err +} + +// delete issues a delete call and returns the response or an error. The response +// gets deserialized into an unstructured and is either a metav1.Status if the object +// is gone from storage or the object if it remains, for example because of finalizers. +func (c *client) delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { switch obj.(type) { case runtime.Unstructured: return c.unstructuredClient.Delete(ctx, obj, opts...) - case *metav1.PartialObjectMetadata: - return c.metadataClient.Delete(ctx, obj, opts...) + // The typed client can also delete PartialObjectMeta default: return c.typedClient.Delete(ctx, obj, opts...) } diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go index 1c39f4d85..9c7187046 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/config/config.go @@ -61,7 +61,7 @@ func RegisterFlags(fs *flag.FlagSet) { // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Config precedence: @@ -81,7 +81,7 @@ func GetConfig() (*rest.Config, error) { // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Config precedence: @@ -169,7 +169,7 @@ func loadConfigWithContext(apiServerURL string, loader clientcmd.ClientConfigLoa // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running // in cluster and use the cluster provided kubeconfig. // -// The returned `*rest.Config` has client-side ratelimting disabled as we can rely on API priority and +// The returned `*rest.Config` has client-side rate limiting disabled as we can rely on API priority and // fairness. Set its QPS to a value equal or bigger than 0 to re-enable it. // // Will log an error and exit if there is an error creating the rest.Config. diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go new file mode 100644 index 000000000..256f86205 --- /dev/null +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/consistency.go @@ -0,0 +1,494 @@ +/* +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 client + +import ( + "context" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "sync" + + "github.com/go-logr/logr" + "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" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" + "sigs.k8s.io/controller-runtime/pkg/client/apiutil" + "sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler" + "sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier" +) + +type consistentClientUpstream interface { + Client + + delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) +} + +var _ Client = (*consistentClient)(nil) + +func newConsistentClient( + upstream consistentClientUpstream, + informers cacheapi.Informers, + newWriteBarrier func() writebarrier.WriteBarrier, + log logr.Logger, +) *consistentClient { + return &consistentClient{ + upstream: upstream, + informers: informers, + writeBarriers: newThreadSafeMap[gvkAndRepresentation](func() writebarrier.WriteBarriers { + return writebarrier.NewWriteBarriers(newWriteBarrier) + }), + consistencyHandlers: newThreadSafeMap[gvkAndRepresentation](func() *consistencyhandler.ConsistencyHandler { + return consistencyhandler.NewHandler(log) + }), + } +} + +type consistentClient struct { + upstream consistentClientUpstream + informers cacheapi.Informers + + writeBarriers *threadSafeMap[gvkAndRepresentation, writebarrier.WriteBarriers] + + consistencyHandlers *threadSafeMap[gvkAndRepresentation, *consistencyhandler.ConsistencyHandler] +} + +type gvkAndRepresentation struct { + gvk schema.GroupVersionKind + representation representationID +} + +func representationIDForObj(obj any) representationID { + switch obj.(type) { + case *unstructured.Unstructured, *unstructured.UnstructuredList: + return representationIDUnstructured + case *metav1.PartialObjectMetadata, *metav1.PartialObjectMetadataList: + return representationIDPartialObjectMetadata + default: + return representationIDTyped + } +} + +type representationID int8 + +const ( + representationIDUnstructured representationID = iota + representationIDPartialObjectMetadata + representationIDTyped +) + +func (c *consistentClient) getConsistencyHandler( + ctx context.Context, + gvkAndRepresentation gvkAndRepresentation, + obj Object, +) (*consistencyhandler.ConsistencyHandler, error) { + h := c.consistencyHandlers.getOrCreate(gvkAndRepresentation) + if h.Registered() { + return h, nil + } + + informer, err := c.informers.GetInformer(ctx, obj, cacheapi.BlockUntilSynced(true)) + if err != nil { + return nil, fmt.Errorf("failed to get informer for GVK %s: %w", gvkAndRepresentation.gvk, err) + } + + if err := h.Register(ctx, informer); err != nil { + return nil, fmt.Errorf("failed to register consistency handler on informer for GVK %s: %w", gvkAndRepresentation.gvk, err) + } + return h, nil +} + +func (c *consistentClient) Get(ctx context.Context, key ObjectKey, obj Object, opts ...GetOption) error { + if (&GetOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.Get(ctx, key, obj, opts...) + } + + gvk, err := apiutil.GVKForObject(obj, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for object %T: %w", obj, err) + } + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(obj)} + + select { + case <-c.writeBarriers.getOrCreate(gvkAndRepresentation).Seal(key): + case <-ctx.Done(): + return ctx.Err() + } + + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + if err := h.WaitForGet(ctx, key); err != nil { + return fmt.Errorf("failed to wait for cache to catch up: %w", err) + } + + return c.upstream.Get(ctx, key, obj, opts...) +} + +func (c *consistentClient) List(ctx context.Context, list ObjectList, opts ...ListOption) error { + if (&ListOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.List(ctx, list, opts...) + } + + gvk, err := apiutil.GVKForObject(list, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for list %T: %w", list, err) + } + gvk.Kind = strings.TrimSuffix(gvk.Kind, "List") + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(list)} + + for _, s := range c.writeBarriers.getOrCreate(gvkAndRepresentation).SealAll() { + select { + case <-s: + case <-ctx.Done(): + return ctx.Err() + } + } + + var obj Object + switch gvkAndRepresentation.representation { + case representationIDUnstructured: + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(gvk) + obj = u + case representationIDPartialObjectMetadata: + m := &metav1.PartialObjectMetadata{} + m.SetGroupVersionKind(gvk) + obj = m + case representationIDTyped: + raw, err := c.upstream.Scheme().New(gvk) + if err != nil { + return fmt.Errorf("failed to create object for GVK %s: %w", gvk, err) + } + asserted, ok := raw.(Object) + if !ok { + return fmt.Errorf("object of type %T for GVK %s does not implement Object", raw, gvk) + } + obj = asserted + } + + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + if err := h.WaitForList(ctx); err != nil { + return fmt.Errorf("failed to wait for cache to catch up: %w", err) + } + + return c.upstream.List(ctx, list, opts...) +} + +func (c *consistentClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { + return c.writeAndRecordRV(ctx, obj, (&CreateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Create(ctx, obj, opts...) + }) +} + +func (c *consistentClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { + return c.writeAndRecordRV(ctx, obj, (&UpdateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Update(ctx, obj, opts...) + }) +} + +func (c *consistentClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { + return c.writeAndRecordRV(ctx, obj, (&PatchOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Patch(ctx, obj, patch, opts...) + }) +} + +func (c *consistentClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...ApplyOption) error { + return c.writeAndRecordRV(ctx, obj, (&ApplyOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Apply(ctx, obj, opts...) + }) +} + +func writeTargetFor(obj any, scheme *runtime.Scheme) (gvkAndRepresentation, types.NamespacedName, Object, func() (string, error), error) { + switch t := obj.(type) { + case *unstructuredApplyConfiguration: + return gvkAndRepresentation{gvk: t.Unstructured.GroupVersionKind(), representation: representationIDUnstructured}, + ObjectKeyFromObject(t), + t.Unstructured, + func() (string, error) { return t.Unstructured.GetResourceVersion(), nil }, + nil + case applyConfiguration: + gvk, err := gvkFromApplyConfiguration(t) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to get GVK for apply configuration %T: %w", obj, err) + } + cacheObj, err := scheme.New(gvk) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to create object for GVK %s: %w", gvk, err) + } + clientObj, ok := cacheObj.(Object) + if !ok { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("object of type %T for GVK %s does not implement client.Object", cacheObj, gvk) + } + clientObj.SetName(ptr.Deref(t.GetName(), "")) + clientObj.SetNamespace(ptr.Deref(t.GetNamespace(), "")) + return gvkAndRepresentation{gvk: gvk, representation: representationIDTyped}, + ObjectKeyFromObject(clientObj), + clientObj, + func() (string, error) { return resourceVersionFromApplyConfiguration(t) }, + nil + case *metav1.PartialObjectMetadata: + return gvkAndRepresentation{gvk: t.GroupVersionKind(), representation: representationIDPartialObjectMetadata}, + ObjectKeyFromObject(t), + t, + func() (string, error) { return t.GetResourceVersion(), nil }, + nil + case Object: + gvk, err := apiutil.GVKForObject(t, scheme) + if err != nil { + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("failed to get GVK for object %T: %w", obj, err) + } + return gvkAndRepresentation{gvk: gvk, representation: representationIDTyped}, + ObjectKeyFromObject(t), + t, + func() (string, error) { return t.GetResourceVersion(), nil }, + nil + default: + return gvkAndRepresentation{}, types.NamespacedName{}, nil, nil, fmt.Errorf("unsupported type %T, must be either %T, %T or %T", obj, Object(nil), &unstructuredApplyConfiguration{}, applyConfiguration(nil)) + } +} + +func (c *consistentClient) writeAndRecordRV(ctx context.Context, obj any, disableConsistency bool, write func() error) error { + if disableConsistency { + return write() + } + + gvkAndRepresentation, namespacedName, cacheObj, getResourceVersion, err := writeTargetFor(obj, c.upstream.Scheme()) + if err != nil { + return err + } + + // We don't technically need an informer since the RV is monotonically increasing, but we want to fail + // ASAP if the cache can not be setup. + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, cacheObj) + if err != nil { + return err + } + + release := c.writeBarriers.getOrCreate(gvkAndRepresentation).Begin(namespacedName) + defer release() + + if err := write(); err != nil { + return err + } + + rvRaw, err := getResourceVersion() + if err != nil { + return fmt.Errorf("failed to get resource version from %T: %w", obj, err) + } + rv, err := strconv.ParseInt(rvRaw, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse resource version %s: %w", rvRaw, err) + } + + h.SetMinimumRV(ObjectKeyFromObject(cacheObj), rv) + + return nil +} + +func resourceVersionFromApplyConfiguration(obj applyConfiguration) (string, error) { + v := reflect.ValueOf(obj) + for v.Kind() == reflect.Pointer { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return "", fmt.Errorf("expected struct, got %s", v.Kind()) + } + rv := v.FieldByName("ResourceVersion") + if !rv.IsValid() { + return "", fmt.Errorf("type %T has no ResourceVersion field", obj) + } + if rv.Kind() != reflect.Pointer || rv.Type().Elem().Kind() != reflect.String { + return "", fmt.Errorf("ResourceVersion field in %T is not *string", obj) + } + if rv.IsNil() { + return "", fmt.Errorf("ResourceVersion field in %T is nil", obj) + } + return rv.Elem().String(), nil +} + +func (c *consistentClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { + if (&DeleteOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency { + return c.upstream.Delete(ctx, obj, opts...) + } + + gvk, err := apiutil.GVKForObject(obj, c.upstream.Scheme()) + if err != nil { + return fmt.Errorf("failed to get GVK for object %v: %w", obj, err) + } + + gvkAndRepresentation := gvkAndRepresentation{gvk: gvk, representation: representationIDForObj(obj)} + h, err := c.getConsistencyHandler(ctx, gvkAndRepresentation, obj) + if err != nil { + return err + } + + namespacedName := ObjectKeyFromObject(obj) + uid, err := c.uidForDelete(ctx, gvk, namespacedName, obj, opts...) + if err != nil { + return err + } + + release := c.writeBarriers.getOrCreate(gvkAndRepresentation).Begin(namespacedName) + defer release() + + // Register the delete before we execute it, otherwise it may be in the cache + // before we register it, causing a deadlock. + h.AddPendingDelete(namespacedName, uid) + + response, err := c.upstream.delete(ctx, obj, opts...) + if err != nil { + h.RemovePendingDelete(namespacedName, uid) + return err + } + + // Prefer waiting for the RV rather than an actual event since that is likely to be more resilient. + // This can only work if the response contains the RV which in turn only happens if the request did + // not delete the object from storage, for example because it had a finalizer. + if rvRaw := response.GetResourceVersion(); rvRaw != "" { + rv, err := strconv.ParseInt(rvRaw, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse resource version %s: %w", rvRaw, err) + } + h.RemovePendingDelete(namespacedName, uid) + h.SetMinimumRV(namespacedName, rv) + } + + return nil +} + +func (c *consistentClient) uidForDelete(ctx context.Context, gvk schema.GroupVersionKind, key ObjectKey, obj Object, opts ...DeleteOption) (types.UID, error) { + deleteOptions := (&DeleteOptions{}).ApplyOptions(opts) + if p := deleteOptions.Preconditions; p != nil && ptr.Deref(p.UID, "") != "" { + return *p.UID, nil + } + + if uid := obj.GetUID(); uid != "" { + return uid, nil + } + + existing, ok := obj.DeepCopyObject().(Object) + if !ok { + return "", fmt.Errorf("deepcopy of %T does not implement client.Object", obj) + } + if err := c.upstream.Get(ctx, key, existing); err != nil { + return "", fmt.Errorf("failed to get %s %s to determine its uid: %w", gvk.Kind, key, err) + } + + return existing.GetUID(), nil +} + +func (c *consistentClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { + return errors.New("DeleteAllOf is not supported by consistentClient, please use List and Delete instead") +} + +func (c *consistentClient) Status() SubResourceWriter { + return c.SubResource("status") +} + +func (c *consistentClient) Scheme() *runtime.Scheme { + return c.upstream.Scheme() +} + +func (c *consistentClient) RESTMapper() meta.RESTMapper { + return c.upstream.RESTMapper() +} + +func (c *consistentClient) GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error) { + return c.upstream.GroupVersionKindFor(obj) +} + +func (c *consistentClient) IsObjectNamespaced(obj runtime.Object) (bool, error) { + return c.upstream.IsObjectNamespaced(obj) +} + +func (c *consistentClient) SubResource(subResource string) SubResourceClient { + return &consistentSubResourceClient{ + writeAndRecordRV: c.writeAndRecordRV, + upstream: c.upstream.SubResource(subResource), + } +} + +type consistentSubResourceClient struct { + writeAndRecordRV func(ctx context.Context, obj any, disableConsistency bool, write func() error) error + upstream SubResourceClient +} + +func (c *consistentSubResourceClient) Get(ctx context.Context, obj, subResource Object, opts ...SubResourceGetOption) error { + return c.upstream.Get(ctx, obj, subResource, opts...) +} + +func (c *consistentSubResourceClient) Create(ctx context.Context, obj, subResource Object, opts ...SubResourceCreateOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourceCreateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Create(ctx, obj, subResource, opts...) + }) +} + +func (c *consistentSubResourceClient) Update(ctx context.Context, obj Object, opts ...SubResourceUpdateOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourceUpdateOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Update(ctx, obj, opts...) + }) +} + +func (c *consistentSubResourceClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...SubResourcePatchOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourcePatchOptions{}).ApplyOptions(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Patch(ctx, obj, patch, opts...) + }) +} + +func (c *consistentSubResourceClient) Apply(ctx context.Context, obj runtime.ApplyConfiguration, opts ...SubResourceApplyOption) error { + return c.writeAndRecordRV(ctx, obj, (&SubResourceApplyOptions{}).ApplyOpts(opts).DisableReadYourWritesConsistency, func() error { + return c.upstream.Apply(ctx, obj, opts...) + }) +} + +func newThreadSafeMap[k comparable, v any](newValue func() v) *threadSafeMap[k, v] { + return &threadSafeMap[k, v]{ + data: map[k]v{}, + newValue: newValue, + } +} + +type threadSafeMap[k comparable, v any] struct { + lock sync.Mutex + data map[k]v + newValue func() v +} + +func (t *threadSafeMap[k, v]) getOrCreate(key k) v { + t.lock.Lock() + defer t.lock.Unlock() + + val, exists := t.data[key] + if !exists { + val = t.newValue() + t.data[key] = val + } + + return val +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go index 1af1f3a36..87c6d17ae 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/interfaces.go @@ -26,6 +26,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" + + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" ) // ObjectKey identifies a Kubernetes Object. @@ -194,20 +196,11 @@ type WithWatch interface { // IndexerFunc knows how to take an object and turn it into a series // of non-namespaced keys. Namespaced objects are automatically given // namespaced and non-spaced variants, so keys do not need to include namespace. -type IndexerFunc func(Object) []string +type IndexerFunc = cacheapi.IndexerFunc // FieldIndexer knows how to index over a particular "field" such that it // can later be used by a field selector. -type FieldIndexer interface { - // IndexField adds an index with the given field name on the given object type - // by using the given function to extract the value for that field. If you want - // compatibility with the Kubernetes API server, only return one key, and only use - // fields that the API server supports. Otherwise, you can return multiple keys, - // and "equality" in the field selector means that at least one key matches the value. - // The FieldIndexer will automatically take care of indexing over namespace - // and supporting efficient all-namespace queries. - IndexField(ctx context.Context, obj Object, field string, extractValue IndexerFunc) error -} +type FieldIndexer = cacheapi.FieldIndexer // IgnoreNotFound returns nil on NotFound errors. // All other values that are not NotFound errors or nil are returned unmodified. diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go new file mode 100644 index 000000000..9c247c2df --- /dev/null +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/consistencyhandler/consistencyhandler.go @@ -0,0 +1,345 @@ +/* +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 consistencyhandler + +import ( + "context" + "fmt" + "maps" + "strconv" + "sync" + "sync/atomic" + + "github.com/go-logr/logr" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/client-go/tools/cache" + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" +) + +func NewHandler(log logr.Logger) *ConsistencyHandler { + return &ConsistencyHandler{ + rvBroadCaster: &broadcaster{}, + pendingDeletesBroadcaster: &broadcaster{}, + pendingDeletes: make(map[types.NamespacedName]sets.Set[types.UID]), + minimumRVs: make(map[types.NamespacedName]int64), + log: log, + triggerCleanup: make(chan struct{}, 1), + } +} + +type ConsistencyHandler struct { + rvBroadCaster *broadcaster + observedRV atomic.Int64 + + pendingDeletesBroadcaster *broadcaster + pendingDeletesLock sync.RWMutex + // pendingDeletes holds pending deletes. Must only be accessed when holding pendingDeletesLock + pendingDeletes map[types.NamespacedName]sets.Set[types.UID] + + minimumRVsLock sync.RWMutex + // minimumRVs stores the minimum RVs we must have seen before returning reads. Must only be + // accessed when holding minimumRVsLock. + minimumRVs map[types.NamespacedName]int64 + + registerLock sync.RWMutex + registered bool + registration *cache.ResourceEventHandlerRegistration + + log logr.Logger + + // triggerCleanup triggers the cleanup of pendingRVs that are smaller + // than observedRV. It holds a one element buffered channel, because + // having more than one queued cleanup doesn't make sense. + triggerCleanup chan struct{} +} + +func (h *ConsistencyHandler) Registered() bool { + h.registerLock.RLock() + defer h.registerLock.RUnlock() + return h.registered +} + +func (h *ConsistencyHandler) Register(ctx context.Context, informer cacheapi.Informer) error { + h.registerLock.Lock() + defer h.registerLock.Unlock() + + // Check again in case it got registered while we waited for the lock + if h.registered { + return nil + } + + if h.registration != nil { + return h.waitForHandlerSyncLocked(ctx, *h.registration) + } + + registration, err := informer.AddEventHandler(h) + if err != nil { + return fmt.Errorf("failed to add consistency handler to informer: %w", err) + } + h.registration = ®istration + + return h.waitForHandlerSyncLocked(ctx, registration) +} + +func (h *ConsistencyHandler) waitForHandlerSyncLocked(ctx context.Context, registration cache.ResourceEventHandlerRegistration) error { + select { + case <-registration.HasSyncedChecker().Done(): + h.registered = true + return nil + case <-ctx.Done(): + return fmt.Errorf("failed waiting for consistency handler to sync: %w", ctx.Err()) + } +} + +func (h *ConsistencyHandler) SetMinimumRV(key types.NamespacedName, rv int64) { + h.minimumRVsLock.Lock() + defer h.minimumRVsLock.Unlock() + if rv > h.minimumRVs[key] && rv > h.observedRV.Load() { + h.minimumRVs[key] = rv + } +} + +func (h *ConsistencyHandler) getMinimumRVForKey(key types.NamespacedName) int64 { + h.minimumRVsLock.RLock() + defer h.minimumRVsLock.RUnlock() + return h.minimumRVs[key] +} + +func (h *ConsistencyHandler) getMinimumRVForGVK() int64 { + h.minimumRVsLock.RLock() + defer h.minimumRVsLock.RUnlock() + var maxRV int64 + for _, rv := range h.minimumRVs { + if rv > maxRV { + maxRV = rv + } + } + return maxRV +} + +func (h *ConsistencyHandler) cleanupMinimumRVs() { + h.minimumRVsLock.Lock() + defer h.minimumRVsLock.Unlock() + for key, rv := range h.minimumRVs { + if rv <= h.observedRV.Load() { + delete(h.minimumRVs, key) + } + } +} + +func (h *ConsistencyHandler) AddPendingDelete(key types.NamespacedName, uid types.UID) { + h.pendingDeletesLock.Lock() + defer h.pendingDeletesLock.Unlock() + + if h.pendingDeletes[key] == nil { + h.pendingDeletes[key] = sets.New(uid) + return + } + h.pendingDeletes[key].Insert(uid) +} + +func (h *ConsistencyHandler) RemovePendingDelete(key types.NamespacedName, uid types.UID) { + h.pendingDeletesLock.Lock() + defer h.pendingDeletesLock.Unlock() + + if h.pendingDeletes[key] != nil { + h.pendingDeletes[key].Delete(uid) + if len(h.pendingDeletes[key]) == 0 { + delete(h.pendingDeletes, key) + } + h.pendingDeletesBroadcaster.broadcast() + } +} + +func (h *ConsistencyHandler) WaitForList(ctx context.Context) error { + // snapshot deletes before waiting for the RV so we don't end up including + // deletes that came in while we waited. + h.pendingDeletesLock.RLock() + pendingDeletes := sets.Set[types.UID]{} + for _, uids := range h.pendingDeletes { + maps.Copy(pendingDeletes, uids) + } + h.pendingDeletesLock.RUnlock() + + if err := h.waitForRV(ctx, h.getMinimumRVForGVK()); err != nil { + return err + } + + return h.waitDeletes(ctx, pendingDeletes) +} + +func (h *ConsistencyHandler) WaitForGet(ctx context.Context, key types.NamespacedName) error { + // snapshot deletes before waiting for the RV so we don't end up including + // deletes that came in while we waited. + h.pendingDeletesLock.RLock() + pendingDeletes := maps.Clone(h.pendingDeletes[key]) + h.pendingDeletesLock.RUnlock() + + if err := h.waitForRV(ctx, h.getMinimumRVForKey(key)); err != nil { + return err + } + + return h.waitDeletes(ctx, pendingDeletes) +} + +func (h *ConsistencyHandler) waitDeletes(ctx context.Context, uids sets.Set[types.UID]) error { + if len(uids) == 0 { + return nil + } + + for { + // must store the chan before checking the deletes to guarantee that even if the deletes + // get updated after our check and before the select, we still get an event. + updatedChan := h.pendingDeletesBroadcaster.getWaitChan() + done := h.allDeleted(uids) + if done { + return nil + } + + select { + case <-updatedChan: + continue + case <-ctx.Done(): + return fmt.Errorf("failed waiting to observe deletes for uids %v: %w", sets.List(uids), ctx.Err()) + } + } +} + +func (h *ConsistencyHandler) allDeleted(uids sets.Set[types.UID]) bool { + h.pendingDeletesLock.RLock() + defer h.pendingDeletesLock.RUnlock() + + for wantDeleted := range uids { + for _, notDeletedUIDs := range h.pendingDeletes { + if notDeletedUIDs.Has(wantDeleted) { + return false + } + } + } + + return true +} + +func (h *ConsistencyHandler) observeDeletion(obj cacheapi.Object) { + h.RemovePendingDelete(types.NamespacedName{Namespace: obj.GetNamespace(), Name: obj.GetName()}, obj.GetUID()) +} + +func (h *ConsistencyHandler) waitForRV(ctx context.Context, rv int64) error { + for { + // must store the chan before checking the RV to guarantee that even if the RV + // gets updated after our check and before the select, we still get an event. + updatedChan := h.rvBroadCaster.getWaitChan() + if h.observedRV.Load() >= rv { + return nil + } + select { + case <-updatedChan: + continue + case <-ctx.Done(): + return fmt.Errorf("failed waiting to observe resource version %d: %w", rv, ctx.Err()) + } + } +} + +func (h *ConsistencyHandler) observeResourceVersion(rv string) { + parsed, err := strconv.ParseInt(rv, 10, 64) + if err != nil { + h.log.Error(err, "Failed to parse resource version as int64", "resourceVersion", rv) + return + } + + for { + current := h.observedRV.Load() + if parsed <= current { + return + } + + if h.observedRV.CompareAndSwap(current, parsed) { + break + } + } + + h.rvBroadCaster.broadcast() + + select { + case h.triggerCleanup <- struct{}{}: + h.cleanupMinimumRVs() + <-h.triggerCleanup + default: + } +} + +func (h *ConsistencyHandler) OnAdd(raw any, _ bool) { + obj, ok := raw.(cacheapi.Object) + if !ok { + h.log.Error(nil, "OnAdd received object that is not a cacheapi.Object", "object", raw) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() +} + +func (h *ConsistencyHandler) OnUpdate(_, newObj any) { + obj, ok := newObj.(cacheapi.Object) + if !ok { + h.log.Error(nil, "OnUpdate received object that is not a cacheapi.Object", "object", newObj) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() +} + +func (h *ConsistencyHandler) OnDelete(raw any) { + var obj cacheapi.Object + switch t := raw.(type) { + case cacheapi.Object: + obj = t + case cache.DeletedFinalStateUnknown: + obj = t.Obj.(cacheapi.Object) + default: + h.log.Error(nil, "OnDelete received object that is not a cacheapi.Object or toolscache.DeletedFinalStateUnknown", "object", raw) + return + } + go func() { h.observeResourceVersion(obj.GetResourceVersion()) }() + go func() { h.observeDeletion(obj) }() +} + +// broadcaster wakes arbitrarily many waiters on broadcast(). +type broadcaster struct { + lock sync.Mutex + ch chan struct{} +} + +func (b *broadcaster) broadcast() { + b.lock.Lock() + defer b.lock.Unlock() + // Lazily create the channel in getWaitChan to avoid creating a channel per event. + if b.ch != nil { + close(b.ch) + b.ch = nil + } +} + +func (b *broadcaster) getWaitChan() <-chan struct{} { + b.lock.Lock() + defer b.lock.Unlock() + + if b.ch == nil { + b.ch = make(chan struct{}) + } + + return b.ch +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go new file mode 100644 index 000000000..77b5f3cbe --- /dev/null +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/internal/writebarrier/writebarrier.go @@ -0,0 +1,195 @@ +/* +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 writebarrier + +import ( + "sync" + + "k8s.io/apimachinery/pkg/types" +) + +// WriteBarriers adds garbage collection for unused keys to WriteBarrier. +type WriteBarriers interface { + // Begin keeps the passed key locked until the returned release func was called. + Begin(key types.NamespacedName) (release func()) + + // Seal seals the currently-active set of locks to key and returns a channel that + // closes when they are done. + Seal(key types.NamespacedName) <-chan struct{} + + // SealAll is Seal for all keys. + SealAll() []<-chan struct{} +} + +// NewWriteBarriers construct WriteBarriers. newBarrier is configurable for testing purposes only. +func NewWriteBarriers(newBarrier func() WriteBarrier) WriteBarriers { + return &writeBarriers{ + data: map[types.NamespacedName]*writeBarrierWithRefCounter{}, + newBarrier: newBarrier, + } +} + +type writeBarrierWithRefCounter struct { + WriteBarrier + inFlightWrites int +} + +// writeBarriers holds one writeBarrier per key that has an in-flight write. +type writeBarriers struct { + lock sync.Mutex + data map[types.NamespacedName]*writeBarrierWithRefCounter + newBarrier func() WriteBarrier +} + +func (w *writeBarriers) Begin(key types.NamespacedName) func() { + w.lock.Lock() + defer w.lock.Unlock() + + barrier, exists := w.data[key] + if !exists { + barrier = &writeBarrierWithRefCounter{WriteBarrier: w.newBarrier()} + w.data[key] = barrier + } + barrier.inFlightWrites++ + release := barrier.Begin() + + return func() { + release() + + w.lock.Lock() + defer w.lock.Unlock() + barrier.inFlightWrites-- + if barrier.inFlightWrites == 0 { + delete(w.data, key) + } + } +} + +func (w *writeBarriers) Seal(key types.NamespacedName) <-chan struct{} { + w.lock.Lock() + defer w.lock.Unlock() + + barrier, exists := w.data[key] + if !exists { + return closedChannel + } + + return barrier.Seal() +} + +func (w *writeBarriers) SealAll() []<-chan struct{} { + w.lock.Lock() + defer w.lock.Unlock() + + result := make([]<-chan struct{}, 0, len(w.data)) + for _, barrier := range w.data { + result = append(result, barrier.Seal()) + } + + return result +} + +var closedChannel chan struct{} + +func init() { + closedChannel = make(chan struct{}) + close(closedChannel) +} + +type WriteBarrier interface { + Begin() (release func()) + Seal() <-chan struct{} +} + +// NewWriteBarrier creates a new WriteBarrier +func NewWriteBarrier() WriteBarrier { + return &keyWriteBarrier{previous: closedChannel} +} + +// keyWriteBarrier allows to wait for a set of in-flight writes to finish. +type keyWriteBarrier struct { + // lock must be held to access current or previous. + lock sync.Mutex + + // current is the current write batch. It has a reference to the key write + // barrier that it uses to delete itself once done. + current *writeBatch + + // previous is closed once all previous write batches are done. + previous <-chan struct{} +} + +// Begin adds a write to the current batch, starting one if needed. +func (b *keyWriteBarrier) Begin() func() { + b.lock.Lock() + defer b.lock.Unlock() + + if b.current == nil { + b.current = &writeBatch{barrier: b, done: make(chan struct{})} + } + b.current.inFlight++ + + return b.current.release +} + +func (b *keyWriteBarrier) Seal() <-chan struct{} { + b.lock.Lock() + defer b.lock.Unlock() + + if b.current == nil { + return b.previous + } + + // Create a new chan that blocks until both previous + // and current are done. + done := make(chan struct{}) + previous := b.previous + b.previous = done + + current := b.current.done + b.current = nil + + go func() { + for _, c := range []<-chan struct{}{previous, current} { + <-c + } + close(done) + }() + + return done +} + +type writeBatch struct { + barrier *keyWriteBarrier + inFlight int + done chan struct{} +} + +func (w *writeBatch) release() { + w.barrier.lock.Lock() + defer w.barrier.lock.Unlock() + + w.inFlight-- + if w.inFlight > 0 { + return + } + + close(w.done) + if w.barrier.current == w { + w.barrier.current = nil + } +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go index d0c6b8e13..6c0a2078d 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/metadata_client.go @@ -49,24 +49,6 @@ func (mc *metadataClient) getResourceInterface(gvk schema.GroupVersionKind, ns s return mc.client.Resource(mapping.Resource).Namespace(ns), nil } -// Delete implements client.Client. -func (mc *metadataClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { - metadata, ok := obj.(*metav1.PartialObjectMetadata) - if !ok { - return fmt.Errorf("metadata client did not understand object: %T", obj) - } - - resInt, err := mc.getResourceInterface(metadata.GroupVersionKind(), metadata.Namespace) - if err != nil { - return err - } - - deleteOpts := DeleteOptions{} - deleteOpts.ApplyOptions(opts) - - return resInt.Delete(ctx, metadata.Name, *deleteOpts.AsDeleteOptions()) -} - // DeleteAllOf implements client.Client. func (mc *metadataClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go index 31e334d6c..e5f820438 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/object.go @@ -19,6 +19,8 @@ package client import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + + "sigs.k8s.io/controller-runtime/pkg/cache/cacheapi" ) // Object is a Kubernetes object, allows functions to work indistinctly with @@ -42,10 +44,7 @@ import ( // a `metadata` field). // // Notice that XYZList types are distinct: they implement ObjectList instead. -type Object interface { - metav1.Object - runtime.Object -} +type Object = cacheapi.Object // ObjectList is a Kubernetes object list, allows functions to work // indistinctly with any resource that implements both runtime.Object and diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go index c5bd9f0b8..aae55edfc 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/options.go @@ -200,6 +200,72 @@ func (f FieldOwner) ApplyToSubResourceApply(opts *SubResourceApplyOptions) { opts.FieldManager = string(f) } +// DisableReadYourWritesConsistency disables read-your-own-write consistency for the +// request it is passed to. It has no effect if the client was not configured with +// CacheOptions.EnableReadYourWritesConsistency. +// +// On a read request, the request will not wait for the cache to have observed +// previous writes. On a write request, subsequent read requests will not wait +// for the cache to have observed this write. +const DisableReadYourWritesConsistency = disableReadYourWritesConsistency(true) + +type disableReadYourWritesConsistency bool + +// ApplyToGet applies this configuration to the given get options. +func (disableReadYourWritesConsistency) ApplyToGet(opts *GetOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToList applies this configuration to the given list options. +func (disableReadYourWritesConsistency) ApplyToList(opts *ListOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToCreate applies this configuration to the given create options. +func (disableReadYourWritesConsistency) ApplyToCreate(opts *CreateOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToUpdate applies this configuration to the given update options. +func (disableReadYourWritesConsistency) ApplyToUpdate(opts *UpdateOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToPatch applies this configuration to the given patch options. +func (disableReadYourWritesConsistency) ApplyToPatch(opts *PatchOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToApply applies this configuration to the given apply options. +func (disableReadYourWritesConsistency) ApplyToApply(opts *ApplyOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToDelete applies this configuration to the given delete options. +func (disableReadYourWritesConsistency) ApplyToDelete(opts *DeleteOptions) { + opts.DisableReadYourWritesConsistency = true +} + +// ApplyToSubResourceCreate applies this configuration to the given create options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceCreate(opts *SubResourceCreateOptions) { + d.ApplyToCreate(&opts.CreateOptions) +} + +// ApplyToSubResourceUpdate applies this configuration to the given update options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceUpdate(opts *SubResourceUpdateOptions) { + d.ApplyToUpdate(&opts.UpdateOptions) +} + +// ApplyToSubResourcePatch applies this configuration to the given patch options. +func (d disableReadYourWritesConsistency) ApplyToSubResourcePatch(opts *SubResourcePatchOptions) { + d.ApplyToPatch(&opts.PatchOptions) +} + +// ApplyToSubResourceApply applies this configuration to the given apply options. +func (d disableReadYourWritesConsistency) ApplyToSubResourceApply(opts *SubResourceApplyOptions) { + d.ApplyToApply(&opts.ApplyOptions) +} + // FieldValidation configures field validation for the given requests. type FieldValidation string @@ -269,6 +335,11 @@ type CreateOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw CreateOptions, as passed to the API server. Raw *metav1.CreateOptions } @@ -309,6 +380,9 @@ func (o *CreateOptions) ApplyToCreate(co *CreateOptions) { if o.FieldValidation != "" { co.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + co.DisableReadYourWritesConsistency = true + } if o.Raw != nil { co.Raw = o.Raw } @@ -343,6 +417,11 @@ type DeleteOptions struct { // foreground. PropagationPolicy *metav1.DeletionPropagation + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this delete. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw DeleteOptions, as passed to the API server. Raw *metav1.DeleteOptions @@ -393,6 +472,9 @@ func (o *DeleteOptions) ApplyToDelete(do *DeleteOptions) { if o.PropagationPolicy != nil { do.PropagationPolicy = o.PropagationPolicy } + if o.DisableReadYourWritesConsistency { + do.DisableReadYourWritesConsistency = true + } if o.Raw != nil { do.Raw = o.Raw } @@ -468,6 +550,11 @@ type GetOptions struct { // otherwise you will mutate the object in the cache. // +optional UnsafeDisableDeepCopy *bool + + // DisableReadYourWritesConsistency indicates that the request will not wait for the + // cache to have observed previous writes. It has no effect if the client was not + // configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool } var _ GetOption = &GetOptions{} @@ -480,6 +567,9 @@ func (o *GetOptions) ApplyToGet(lo *GetOptions) { if o.UnsafeDisableDeepCopy != nil { lo.UnsafeDisableDeepCopy = o.UnsafeDisableDeepCopy } + if o.DisableReadYourWritesConsistency { + lo.DisableReadYourWritesConsistency = true + } } // AsGetOptions returns these options as a flattened metav1.GetOptions. @@ -538,6 +628,11 @@ type ListOptions struct { // +optional UnsafeDisableDeepCopy *bool + // DisableReadYourWritesConsistency indicates that the request will not wait for the + // cache to have observed previous writes. It has no effect if the client was not + // configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw ListOptions, as passed to the API server. Note // that these may not be respected by all implementations of interface, // and the LabelSelector, FieldSelector, Limit and Continue fields are ignored. @@ -569,6 +664,10 @@ func (o *ListOptions) ApplyToList(lo *ListOptions) { if o.UnsafeDisableDeepCopy != nil { lo.UnsafeDisableDeepCopy = o.UnsafeDisableDeepCopy } + + if o.DisableReadYourWritesConsistency { + lo.DisableReadYourWritesConsistency = true + } } // AsListOptions returns these options as a flattened metav1.ListOptions. @@ -797,6 +896,11 @@ type UpdateOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw UpdateOptions, as passed to the API server. Raw *metav1.UpdateOptions } @@ -839,6 +943,9 @@ func (o *UpdateOptions) ApplyToUpdate(uo *UpdateOptions) { if o.FieldValidation != "" { uo.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + uo.DisableReadYourWritesConsistency = true + } if o.Raw != nil { uo.Raw = o.Raw } @@ -885,6 +992,11 @@ type PatchOptions struct { // will contain all unknown and duplicate fields encountered. FieldValidation string + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool + // Raw represents raw PatchOptions, as passed to the API server. Raw *metav1.PatchOptions } @@ -939,6 +1051,9 @@ func (o *PatchOptions) ApplyToPatch(po *PatchOptions) { if o.FieldValidation != "" { po.FieldValidation = o.FieldValidation } + if o.DisableReadYourWritesConsistency { + po.DisableReadYourWritesConsistency = true + } if o.Raw != nil { po.Raw = o.Raw } @@ -1020,6 +1135,11 @@ type ApplyOptions struct { // // +required FieldManager string + + // DisableReadYourWritesConsistency indicates that subsequent read requests will not + // wait for the cache to have observed this write. It has no effect if the client + // was not configured with CacheOptions.EnableReadYourWritesConsistency. + DisableReadYourWritesConsistency bool } // ApplyOptions applies the given opts onto the ApplyOptions @@ -1042,6 +1162,10 @@ func (o *ApplyOptions) ApplyToApply(opts *ApplyOptions) { if o.FieldManager != "" { opts.FieldManager = o.FieldManager } + + if o.DisableReadYourWritesConsistency { + opts.DisableReadYourWritesConsistency = true + } } // AsPatchOptions constructs patch options from the given ApplyOptions diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go index 5a8594172..396bc6ea6 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/typed_client.go @@ -18,15 +18,15 @@ package client import ( "context" + "encoding/json" "fmt" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/json" "k8s.io/client-go/util/apply" ) var _ Reader = &typedClient{} -var _ Writer = &typedClient{} type typedClient struct { resources *clientRestResources @@ -73,22 +73,35 @@ func (c *typedClient) Update(ctx context.Context, obj Object, opts ...UpdateOpti } // Delete implements client.Client. -func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { +func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { o, err := c.resources.getObjMeta(obj) if err != nil { - return err + return nil, err } deleteOpts := DeleteOptions{} deleteOpts.ApplyOptions(opts) - return o.Delete(). + // directly deserializing into unstructured fails in the decoder + runtimeObj, err := o.Delete(). NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). - Error() + Get() + if err != nil { + return nil, err + } + data, err := json.Marshal(runtimeObj) + if err != nil { + return nil, fmt.Errorf("failed to marshal delete response: %w", err) + } + response := &unstructured.Unstructured{} + if err := json.Unmarshal(data, &response.Object); err != nil { + return nil, fmt.Errorf("failed to unmarshal delete response: %w", err) + } + return response, nil } // DeleteAllOf implements client.Client. diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go index d2ea6d7a3..31e935e55 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/unstructured_client.go @@ -21,12 +21,12 @@ import ( "fmt" "strings" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/util/apply" ) var _ Reader = &unstructuredClient{} -var _ Writer = &unstructuredClient{} type unstructuredClient struct { resources *clientRestResources @@ -93,26 +93,23 @@ func (uc *unstructuredClient) Update(ctx context.Context, obj Object, opts ...Up } // Delete implements client.Client. -func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { - if _, ok := obj.(runtime.Unstructured); !ok { - return fmt.Errorf("unstructured client did not understand object: %T", obj) - } - +func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) (*unstructured.Unstructured, error) { o, err := uc.resources.getObjMeta(obj) if err != nil { - return err + return nil, err } deleteOpts := DeleteOptions{} deleteOpts.ApplyOptions(opts) - return o.Delete(). + response := &unstructured.Unstructured{} + return response, o.Delete(). NamespaceIfScoped(o.namespace, o.isNamespaced()). Resource(o.resource()). Name(o.name). Body(deleteOpts.AsDeleteOptions()). Do(ctx). - Error() + Into(response) } // DeleteAllOf implements client.Client. diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go index 181b22a67..6f1d81471 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/client/watch.go @@ -28,15 +28,16 @@ import ( // NewWithWatch returns a new WithWatch. func NewWithWatch(config *rest.Config, options Options) (WithWatch, error) { - client, err := newClient(config, options) + base, c, err := newClient(config, options) if err != nil { return nil, err } - return &watchingClient{client: client}, nil + return &watchingClient{Client: wrapClient(c, options), base: base}, nil } type watchingClient struct { - *client + Client + base *client } func (w *watchingClient) Watch(ctx context.Context, list ObjectList, opts ...ListOption) (watch.Interface, error) { @@ -67,7 +68,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO listOpts := w.listOpts(opts...) - resInt, err := w.client.metadataClient.getResourceInterface(gvk, listOpts.Namespace) + resInt, err := w.base.metadataClient.getResourceInterface(gvk, listOpts.Namespace) if err != nil { return nil, err } @@ -76,7 +77,7 @@ func (w *watchingClient) metadataWatch(ctx context.Context, obj *metav1.PartialO } func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unstructured, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.unstructuredClient.resources.getResource(obj) + r, err := w.base.unstructuredClient.resources.getResource(obj) if err != nil { return nil, err } @@ -86,12 +87,12 @@ func (w *watchingClient) unstructuredWatch(ctx context.Context, obj runtime.Unst return r.Get(). NamespaceIfScoped(listOpts.Namespace, r.isNamespaced()). Resource(r.resource()). - VersionedParams(listOpts.AsListOptions(), w.client.unstructuredClient.paramCodec). + VersionedParams(listOpts.AsListOptions(), w.base.unstructuredClient.paramCodec). Watch(ctx) } func (w *watchingClient) typedWatch(ctx context.Context, obj ObjectList, opts ...ListOption) (watch.Interface, error) { - r, err := w.client.typedClient.resources.getResource(obj) + r, err := w.base.typedClient.resources.getResource(obj) if err != nil { return nil, err } @@ -101,6 +102,6 @@ func (w *watchingClient) typedWatch(ctx context.Context, obj ObjectList, opts .. return r.Get(). NamespaceIfScoped(listOpts.Namespace, r.isNamespaced()). Resource(r.resource()). - VersionedParams(listOpts.AsListOptions(), w.client.typedClient.paramCodec). + VersionedParams(listOpts.AsListOptions(), w.base.typedClient.paramCodec). Watch(ctx) } diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go index a6961bf7c..7e176304c 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/webhook.go @@ -1,9 +1,12 @@ /* Copyright 2019 The Kubernetes Authors. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go index f1bfda425..9436c9178 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/process.go @@ -18,6 +18,7 @@ package process import ( "crypto/tls" + "errors" "fmt" "io" "net" @@ -128,6 +129,8 @@ func (ps *State) Init(name string) error { type stopChannel chan struct{} +var signalProcess = signalProcessImpl + // CheckFlag checks the help output of this command for the presence of the given flag, specified // without the leading `--` (e.g. `CheckFlag("insecure-port")` checks for `--insecure-port`), // returning true if the flag is present. @@ -266,10 +269,11 @@ func (ps *State) Stop() error { case <-ps.waitDone: break case <-timedOut: + timeoutErr := fmt.Errorf("timeout waiting for process %s to stop", path.Base(ps.Path)) if err := signalProcess(ps.Cmd.Process, syscall.SIGKILL); err != nil { - return fmt.Errorf("unable to kill process %s: %w", ps.Path, err) + return errors.Join(timeoutErr, fmt.Errorf("unable to kill process %s: %w", ps.Path, err)) } - return fmt.Errorf("timeout waiting for process %s to stop", path.Base(ps.Path)) + return timeoutErr } ps.ready = false return nil diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go index 5cbce8f41..6a41ca77b 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_other.go @@ -1,4 +1,4 @@ -//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !zos +//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows && !zos /* Copyright 2026 The Kubernetes Authors. @@ -23,6 +23,6 @@ import ( "syscall" ) -func signalProcess(process *os.Process, sig syscall.Signal) error { +func signalProcessImpl(process *os.Process, sig syscall.Signal) error { return process.Signal(sig) } diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go index d86fc9721..1993962ab 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_unix.go @@ -23,6 +23,6 @@ import ( "syscall" ) -func signalProcess(process *os.Process, sig syscall.Signal) error { +func signalProcessImpl(process *os.Process, sig syscall.Signal) error { return syscall.Kill(-process.Pid, sig) } diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go new file mode 100644 index 000000000..678d5924c --- /dev/null +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/internal/testing/process/signal_windows.go @@ -0,0 +1,28 @@ +//go:build windows + +/* +Copyright 2026 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 process + +import ( + "os" + "syscall" +) + +func signalProcess(process *os.Process, _ syscall.Signal) error { + return process.Kill() +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go index ff28998c4..7d3d31970 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/client_go_adapter.go @@ -18,6 +18,10 @@ package metrics import ( "context" + "net/url" + "sync" + "sync/atomic" + "time" "github.com/prometheus/client_golang/prometheus" clientmetrics "k8s.io/client-go/tools/metrics" @@ -27,16 +31,134 @@ import ( // that client-go registers metrics. We copy the names and formats // from Kubernetes so that we match the core controllers. -var ( - // client metrics. +const ( + hostLabel = "host" + verbLabel = "verb" +) + +// defaultRESTClientDurationBuckets matches Kubernetes core controller REST client metrics. +// They start at 5ms; override via RESTClientMetricsOptions.DurationBuckets if a scrape +// pipeline still consumes classic buckets and needs sub-5ms resolution. +var defaultRESTClientDurationBuckets = []float64{0.005, 0.025, 0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 15.0, 30.0, 60.0} + +func restClientDurationHistogram(name, help string, labels []string, buckets []float64) *prometheus.HistogramVec { + if len(buckets) == 0 { + buckets = defaultRESTClientDurationBuckets + } + return prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Name: name, + Help: help, + Buckets: buckets, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, labels) +} +func newRequestLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_request_duration_seconds", + "Request latency in seconds. Broken down by verb and host.", + []string{verbLabel, hostLabel}, + buckets, + ) +} + +func newResolverLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_dns_resolution_duration_seconds", + "DNS resolver latency in seconds. Broken down by host.", + []string{hostLabel}, + buckets, + ) +} + +func newRateLimiterLatency(buckets []float64) *prometheus.HistogramVec { + return restClientDurationHistogram( + "rest_client_rate_limiter_duration_seconds", + "Client side rate limiter latency in seconds. Broken down by verb, and host.", + []string{verbLabel, hostLabel}, + buckets, + ) +} + +func newRequestSize() *prometheus.HistogramVec { + return prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "rest_client_request_size_bytes", + Help: "Request size in bytes. Broken down by verb and host.", + // 64 bytes to 16MB + Buckets: []float64{64, 256, 512, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{verbLabel, hostLabel}, + ) +} + +func newResponseSize() *prometheus.HistogramVec { + return prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "rest_client_response_size_bytes", + Help: "Response size in bytes. Broken down by verb and host.", + // 64 bytes to 16MB + Buckets: []float64{64, 256, 512, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{verbLabel, hostLabel}, + ) +} + +func newRequestRetry() *prometheus.CounterVec { + return prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "rest_client_request_retries_total", + Help: "Number of request retries, partitioned by status code, verb, and host.", + }, + []string{"code", verbLabel, hostLabel}, + ) +} + +var ( + // requestResult is registered by default. The other client metrics are + // opt-in: adapters start with a nil collector and RegisterRESTClientMetrics* + // stores the HistogramVec / CounterVec. requestResult = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_client_requests_total", Help: "Number of HTTP requests, partitioned by status code, method, and host.", }, - []string{"code", "method", "host"}, + []string{"code", "method", hostLabel}, ) + + requestLatency = &latencyAdapter{} + resolverLatency = &resolverLatencyAdapter{} + requestSize = &sizeAdapter{} + responseSize = &sizeAdapter{} + rateLimiterLatency = &latencyAdapter{} + requestRetry = &retryAdapter{} +) + +// RESTClientMetric identifies an opt-in client-go REST client metric. +// Pass values to RegisterRESTClientMetrics to enable a subset. +type RESTClientMetric int + +const ( + // MetricRequestLatency enables the rest_client_request_duration_seconds metric. + MetricRequestLatency = iota + 1 + // MetricDNSResolutionLatency enables the rest_client_dns_resolution_duration_seconds metric. + MetricDNSResolutionLatency + // MetricRequestSize enables the rest_client_request_size_bytes metric. + MetricRequestSize + // MetricResponseSize enables the rest_client_response_size_bytes metric. + MetricResponseSize + // MetricRateLimiterLatency enables the rest_client_rate_limiter_duration_seconds metric. + MetricRateLimiterLatency + // MetricRequestRetry enables the rest_client_request_retries_total metric. + MetricRequestRetry ) func init() { @@ -50,10 +172,66 @@ func registerClientMetrics() { // register the metrics with client-go clientmetrics.Register(clientmetrics.RegisterOpts{ - RequestResult: &resultAdapter{metric: requestResult}, + RequestResult: &resultAdapter{metric: requestResult}, + RequestLatency: requestLatency, + ResolverLatency: resolverLatency, + RequestSize: requestSize, + ResponseSize: responseSize, + RateLimiterLatency: rateLimiterLatency, + RequestRetry: requestRetry, }) } +// RESTClientMetricsOptions configures RegisterRESTClientMetricsWithOptions. +type RESTClientMetricsOptions struct { + // DurationBuckets overrides the classic Prometheus histogram buckets used by + // rest_client_request_duration_seconds, rest_client_dns_resolution_duration_seconds, + // and rest_client_rate_limiter_duration_seconds. + // + // If nil or empty, the Kubernetes-default buckets are kept (starting at 5ms). + // Native histogram settings are not changed. + // + // DurationBuckets is read when each duration metric is first registered. + // Later calls for the same metric are ignored so already-registered collectors + // are not replaced. + DurationBuckets []float64 +} + +// RegisterRESTClientMetrics enables the given client metrics using default buckets +// that match Kubernetes core controllers. +func RegisterRESTClientMetrics(metrics ...RESTClientMetric) { + RegisterRESTClientMetricsWithOptions(RESTClientMetricsOptions{}, metrics...) +} + +// RegisterRESTClientMetricsWithOptions enables the given client metrics. +// See RESTClientMetricsOptions for knobs such as custom duration buckets. +func RegisterRESTClientMetricsWithOptions(opts RESTClientMetricsOptions, metrics ...RESTClientMetric) { + for _, m := range metrics { + switch m { + case MetricRequestLatency: + requestLatency.enable(func() *prometheus.HistogramVec { + return newRequestLatency(opts.DurationBuckets) + }) + case MetricDNSResolutionLatency: + resolverLatency.enable(func() *prometheus.HistogramVec { + return newResolverLatency(opts.DurationBuckets) + }) + case MetricRequestSize: + requestSize.enable(newRequestSize) + case MetricResponseSize: + responseSize.enable(newResponseSize) + case MetricRateLimiterLatency: + rateLimiterLatency.enable(func() *prometheus.HistogramVec { + return newRateLimiterLatency(opts.DurationBuckets) + }) + case MetricRequestRetry: + requestRetry.enable(newRequestRetry) + default: + // unknown metric, ignore + } + } +} + // this section contains adapters, implementations, and other sundry organic, artisanally // hand-crafted syntax trees required to convince client-go that it actually wants to let // someone use its metrics. @@ -69,3 +247,87 @@ type resultAdapter struct { func (r *resultAdapter) Increment(_ context.Context, code, method, host string) { r.metric.WithLabelValues(code, method, host).Inc() } + +type latencyAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (l *latencyAdapter) enable(newMetric func() *prometheus.HistogramVec) { + l.once.Do(func() { + h := newMetric() + l.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (l *latencyAdapter) Observe(_ context.Context, verb string, u url.URL, duration time.Duration) { + h := l.metric.Load() + if h == nil { + return + } + h.WithLabelValues(verb, u.Host).Observe(duration.Seconds()) +} + +type resolverLatencyAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (r *resolverLatencyAdapter) enable(newMetric func() *prometheus.HistogramVec) { + r.once.Do(func() { + h := newMetric() + r.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (r *resolverLatencyAdapter) Observe(_ context.Context, host string, duration time.Duration) { + h := r.metric.Load() + if h == nil { + return + } + h.WithLabelValues(host).Observe(duration.Seconds()) +} + +type sizeAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.HistogramVec] +} + +func (r *sizeAdapter) enable(newMetric func() *prometheus.HistogramVec) { + r.once.Do(func() { + h := newMetric() + r.metric.Store(h) + Registry.MustRegister(h) + }) +} + +func (r *sizeAdapter) Observe(_ context.Context, verb string, host string, size float64) { + h := r.metric.Load() + if h == nil { + return + } + h.WithLabelValues(verb, host).Observe(size) +} + +type retryAdapter struct { + once sync.Once + metric atomic.Pointer[prometheus.CounterVec] +} + +func (r *retryAdapter) enable(newMetric func() *prometheus.CounterVec) { + r.once.Do(func() { + c := newMetric() + r.metric.Store(c) + Registry.MustRegister(c) + }) +} + +func (r *retryAdapter) IncrementRetry(_ context.Context, code, verb, host string) { + c := r.metric.Load() + if c == nil { + return + } + c.WithLabelValues(code, verb, host).Inc() +} diff --git a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go index 61e1009d3..2253827b8 100644 --- a/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go +++ b/constraint/vendor/sigs.k8s.io/controller-runtime/pkg/metrics/leaderelection.go @@ -1,3 +1,19 @@ +/* +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 metrics import ( diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/element.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/element.go index 73436912c..f1607601c 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/element.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/element.go @@ -19,7 +19,7 @@ package fieldpath import ( "fmt" "iter" - "sort" + "slices" "strings" "sigs.k8s.io/structured-merge-diff/v6/value" @@ -255,19 +255,13 @@ func (s PathElementSet) Copy() PathElementSet { // Insert adds pe to the set. func (s *PathElementSet) Insert(pe PathElement) { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].Less(pe) + loc, found := slices.BinarySearchFunc(s.members, pe, func(a, b PathElement) int { + return a.Compare(b) }) - if loc == len(s.members) { - s.members = append(s.members, pe) + if found { return } - if s.members[loc].Equals(pe) { - return - } - s.members = append(s.members, PathElement{}) - copy(s.members[loc+1:], s.members[loc:]) - s.members[loc] = pe + s.members = slices.Insert(s.members, loc, pe) } // Union returns a set containing elements that appear in either s or s2. @@ -344,16 +338,10 @@ func (s *PathElementSet) Size() int { return len(s.members) } // Has returns true if pe is a member of the set. func (s *PathElementSet) Has(pe PathElement) bool { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].Less(pe) + _, found := slices.BinarySearchFunc(s.members, pe, func(a, b PathElement) int { + return a.Compare(b) }) - if loc == len(s.members) { - return false - } - if s.members[loc].Equals(pe) { - return true - } - return false + return found } // Equals returns true if s and s2 have exactly the same members. diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/pathelementmap.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/pathelementmap.go index ff7ee510c..ca50b84e9 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/pathelementmap.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/pathelementmap.go @@ -17,7 +17,7 @@ limitations under the License. package fieldpath import ( - "sort" + "slices" "sigs.k8s.io/structured-merge-diff/v6/value" ) @@ -82,32 +82,23 @@ func MakePathElementMap(size int) PathElementMap { // Insert adds the pathelement and associated value in the map. // If insert is called twice with the same PathElement, the value is replaced. func (s *PathElementMap) Insert(pe PathElement, v interface{}) { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].PathElement.Less(pe) + loc, found := slices.BinarySearchFunc(s.members, pe, func(a pathElementValue, b PathElement) int { + return a.PathElement.Compare(b) }) - if loc == len(s.members) { - s.members = append(s.members, pathElementValue{pe, v}) - return - } - if s.members[loc].PathElement.Equals(pe) { + if found { s.members[loc].Value = v return } - s.members = append(s.members, pathElementValue{}) - copy(s.members[loc+1:], s.members[loc:]) - s.members[loc] = pathElementValue{pe, v} + s.members = slices.Insert(s.members, loc, pathElementValue{PathElement: pe, Value: v}) } // Get retrieves the value associated with the given PathElement from the map. // (nil, false) is returned if there is no such PathElement. func (s *PathElementMap) Get(pe PathElement) (interface{}, bool) { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].PathElement.Less(pe) + loc, found := slices.BinarySearchFunc(s.members, pe, func(a pathElementValue, b PathElement) int { + return a.PathElement.Compare(b) }) - if loc == len(s.members) { - return nil, false - } - if s.members[loc].PathElement.Equals(pe) { + if found { return s.members[loc].Value, true } return nil, false diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize-pe.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize-pe.go index f4b00c2ee..b2f62dc69 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize-pe.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize-pe.go @@ -97,6 +97,14 @@ func DeserializePathElement(s string) (PathElement, error) { if err != nil { return PathElement{}, err } + // Lookahead validates that there is no unexpected trailing data. + // io.EOF is a successful termination indicator; all other errors or trailing data fail. + if iter.WhatIsNext(); iter.Error != io.EOF { + if iter.Error == nil { + iter.ReportError("managedFields parsing", "unexpected trailing data after JSON object") + } + return PathElement{}, iter.Error + } return PathElement{Value: &v}, nil case peKeySepBytes[0]: iter := readPool.BorrowIterator(b) @@ -112,8 +120,16 @@ func DeserializePathElement(s string) (PathElement, error) { fields = append(fields, value.Field{Name: key, Value: v}) return true }) + // Lookahead validates that there is no unexpected trailing data. + // io.EOF is a successful termination indicator; all other errors or trailing data fail. + if iter.WhatIsNext(); iter.Error != io.EOF { + if iter.Error == nil { + iter.ReportError("managedFields parsing", "unexpected trailing data after JSON object") + } + return PathElement{}, iter.Error + } fields.Sort() - return PathElement{Key: &fields}, iter.Error + return PathElement{Key: &fields}, nil case peIndexSepBytes[0]: i, err := strconv.Atoi(s[2:]) if err != nil { diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize.go index b992b93c5..6701f17ee 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/serialize.go @@ -175,6 +175,17 @@ func (s *Set) FromJSON(r io.Reader) error { } else { *s = *found } + if iter.Error != nil { + return iter.Error + } + if iter.WhatIsNext(); iter.Error == nil { + // Piggy back on scanner aware error reporting here. + iter.ReportError("managedFields parsing", "unexpected trailing data after JSON object") + return iter.Error + } + if iter.Error == io.EOF { + return nil + } return iter.Error } diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/set.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/set.go index d2d8c8a42..d7fe643be 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/set.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/fieldpath/set.go @@ -19,6 +19,7 @@ package fieldpath import ( "fmt" "iter" + "slices" "sort" "strings" @@ -486,19 +487,13 @@ func (s *SetNodeMap) Copy() SetNodeMap { // Descend adds pe to the set if necessary, returning the associated subset. func (s *SetNodeMap) Descend(pe PathElement) *Set { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].pathElement.Less(pe) + loc, found := slices.BinarySearchFunc(s.members, pe, func(a setNode, b PathElement) int { + return a.pathElement.Compare(b) }) - if loc == len(s.members) { - s.members = append(s.members, setNode{pathElement: pe, set: &Set{}}) + if found { return s.members[loc].set } - if s.members[loc].pathElement.Equals(pe) { - return s.members[loc].set - } - s.members = append(s.members, setNode{}) - copy(s.members[loc+1:], s.members[loc:]) - s.members[loc] = setNode{pathElement: pe, set: &Set{}} + s.members = slices.Insert(s.members, loc, setNode{pathElement: pe, set: &Set{}}) return s.members[loc].set } @@ -523,13 +518,10 @@ func (s *SetNodeMap) Empty() bool { // Get returns (the associated set, true) or (nil, false) if there is none. func (s *SetNodeMap) Get(pe PathElement) (*Set, bool) { - loc := sort.Search(len(s.members), func(i int) bool { - return !s.members[i].pathElement.Less(pe) + loc, found := slices.BinarySearchFunc(s.members, pe, func(a setNode, b PathElement) int { + return a.pathElement.Compare(b) }) - if loc == len(s.members) { - return nil, false - } - if s.members[loc].pathElement.Equals(pe) { + if found { return s.members[loc].set, true } return nil, false diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go index c8138a654..4c0e30b25 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/elements.go @@ -62,6 +62,10 @@ type TypeRef struct { // If this field is nil, then it has no effect. // See `Map` and `List` for more information about `ElementRelationship` ElementRelationship *ElementRelationship `yaml:"elementRelationship,omitempty"` + + // Nullable indicates that an explicit null is a valid value, + // corresponding to OpenAPI's `nullable: true`. + Nullable bool `yaml:"nullable,omitempty"` } // Atom represents the smallest possible pieces of the type system. diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go index b668eff83..e1fa5c95d 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/equals.go @@ -55,6 +55,9 @@ func (a *TypeRef) Equals(b *TypeRef) bool { if a.ElementRelationship != b.ElementRelationship { return false } + if a.Nullable != b.Nullable { + return false + } return a.Inlined.Equals(&b.Inlined) } diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go index 6eb6c36df..4eb367b65 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/schema/schemaschema.go @@ -69,6 +69,9 @@ var SchemaSchemaYAML = `types: - name: elementRelationship type: scalar: string + - name: nullable + type: + scalar: boolean - name: scalar scalar: string - name: map diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/allocator.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/allocator.go index f70cd4167..acbfe8ceb 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/allocator.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/allocator.go @@ -16,6 +16,8 @@ limitations under the License. package value +import "reflect" + // Allocator provides a value object allocation strategy. // Value objects can be allocated by passing an allocator to the "Using" // receiver functions on the value interfaces, e.g. Map.ZipUsing(allocator, ...). @@ -24,8 +26,8 @@ package value type Allocator interface { // Free gives the allocator back any value objects returned by the "Using" // receiver functions on the value interfaces. - // interface{} may be any of: Value, Map, List or Range. - Free(interface{}) + // any may be any of: Value, Map, List or Range. + Free(any) // The unexported functions are for "Using" receiver functions of the value types // to request what they need from the allocator. @@ -74,7 +76,7 @@ func (p *heapAllocator) allocListReflectRange() *listReflectRange { return &listReflectRange{vr: &valueReflect{}} } -func (p *heapAllocator) Free(_ interface{}) {} +func (p *heapAllocator) Free(_ any) {} // NewFreelistAllocator creates freelist based allocator. // This allocator provides fast allocation and freeing of short lived value objects. @@ -89,25 +91,25 @@ func (p *heapAllocator) Free(_ interface{}) {} // for all temporary value access. func NewFreelistAllocator() Allocator { return &freelistAllocator{ - valueUnstructured: &freelist{new: func() interface{} { + valueUnstructured: &freelist[*valueUnstructured]{new: func() *valueUnstructured { return &valueUnstructured{} }}, - listUnstructuredRange: &freelist{new: func() interface{} { + listUnstructuredRange: &freelist[*listUnstructuredRange]{new: func() *listUnstructuredRange { return &listUnstructuredRange{vv: &valueUnstructured{}} }}, - valueReflect: &freelist{new: func() interface{} { + valueReflect: &freelist[*valueReflect]{new: func() *valueReflect { return &valueReflect{} }}, - mapReflect: &freelist{new: func() interface{} { + mapReflect: &freelist[*mapReflect]{new: func() *mapReflect { return &mapReflect{} }}, - structReflect: &freelist{new: func() interface{} { + structReflect: &freelist[*structReflect]{new: func() *structReflect { return &structReflect{} }}, - listReflect: &freelist{new: func() interface{} { + listReflect: &freelist[*listReflect]{new: func() *listReflect { return &listReflect{} }}, - listReflectRange: &freelist{new: func() interface{} { + listReflectRange: &freelist[*listReflectRange]{new: func() *listReflectRange { return &listReflectRange{vr: &valueReflect{}} }}, } @@ -119,22 +121,22 @@ func NewFreelistAllocator() Allocator { const freelistMaxSize = 1000 type freelistAllocator struct { - valueUnstructured *freelist - listUnstructuredRange *freelist - valueReflect *freelist - mapReflect *freelist - structReflect *freelist - listReflect *freelist - listReflectRange *freelist + valueUnstructured *freelist[*valueUnstructured] + listUnstructuredRange *freelist[*listUnstructuredRange] + valueReflect *freelist[*valueReflect] + mapReflect *freelist[*mapReflect] + structReflect *freelist[*structReflect] + listReflect *freelist[*listReflect] + listReflectRange *freelist[*listReflectRange] } -type freelist struct { - list []interface{} - new func() interface{} +type freelist[T any] struct { + list []T + new func() T } -func (f *freelist) allocate() interface{} { - var w2 interface{} +func (f *freelist[T]) allocate() T { + var w2 T if n := len(f.list); n > 0 { w2, f.list = f.list[n-1], f.list[:n-1] } else { @@ -143,61 +145,73 @@ func (f *freelist) allocate() interface{} { return w2 } -func (f *freelist) free(v interface{}) { +func (f *freelist[T]) free(v T) { if len(f.list) < freelistMaxSize { f.list = append(f.list, v) } } -func (w *freelistAllocator) Free(value interface{}) { +func (w *freelistAllocator) Free(value any) { switch v := value.(type) { case *valueUnstructured: v.Value = nil // don't hold references to unstructured objects w.valueUnstructured.free(v) case *listUnstructuredRange: + v.list = nil // don't hold references to unstructured objects v.vv.Value = nil // don't hold references to unstructured objects w.listUnstructuredRange.free(v) case *valueReflect: - v.ParentMapKey = nil v.ParentMap = nil + v.ParentMapKey = nil + v.Value = reflect.Value{} // don't hold references to reflected objects w.valueReflect.free(v) case *mapReflect: + v.valueReflect.ParentMap = nil + v.valueReflect.ParentMapKey = nil + v.valueReflect.Value = reflect.Value{} // don't hold references to reflected objects w.mapReflect.free(v) case *structReflect: + v.valueReflect.ParentMap = nil + v.valueReflect.ParentMapKey = nil + v.valueReflect.Value = reflect.Value{} // don't hold references to reflected objects w.structReflect.free(v) case *listReflect: + v.Value = reflect.Value{} // don't hold references to reflected objects w.listReflect.free(v) case *listReflectRange: - v.vr.ParentMapKey = nil + v.list = reflect.Value{} // don't hold references to reflected objects v.vr.ParentMap = nil + v.vr.ParentMapKey = nil + v.vr.Value = reflect.Value{} // don't hold references to reflected objects + v.entry = nil w.listReflectRange.free(v) } } func (w *freelistAllocator) allocValueUnstructured() *valueUnstructured { - return w.valueUnstructured.allocate().(*valueUnstructured) + return w.valueUnstructured.allocate() } func (w *freelistAllocator) allocListUnstructuredRange() *listUnstructuredRange { - return w.listUnstructuredRange.allocate().(*listUnstructuredRange) + return w.listUnstructuredRange.allocate() } func (w *freelistAllocator) allocValueReflect() *valueReflect { - return w.valueReflect.allocate().(*valueReflect) + return w.valueReflect.allocate() } func (w *freelistAllocator) allocStructReflect() *structReflect { - return w.structReflect.allocate().(*structReflect) + return w.structReflect.allocate() } func (w *freelistAllocator) allocMapReflect() *mapReflect { - return w.mapReflect.allocate().(*mapReflect) + return w.mapReflect.allocate() } func (w *freelistAllocator) allocListReflect() *listReflect { - return w.listReflect.allocate().(*listReflect) + return w.listReflect.allocate() } func (w *freelistAllocator) allocListReflectRange() *listReflectRange { - return w.listReflectRange.allocate().(*listReflectRange) + return w.listReflectRange.allocate() } diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/jsontagutil.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/jsontagutil.go index 3aadceb22..db2561373 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/jsontagutil.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/jsontagutil.go @@ -76,11 +76,16 @@ func OmitZeroFunc(t reflect.Type) func(reflect.Value) bool { // but is based on the highly efficient approach from https://golang.org/src/encoding/json/encode.go func lookupJsonTags(f reflect.StructField) (name string, omit bool, inline bool, omitempty bool, omitzero func(reflect.Value) bool) { + // Skip unexported non-embedded fields, matching encoding/json behavior. + if f.PkgPath != "" && !f.Anonymous { + return "", true, false, false, nil + } tag := f.Tag.Get("json") if tag == "-" { return "", true, false, false, nil } name, opts := parseTag(tag) + inline = f.Anonymous && name == "" if name == "" { name = f.Name } @@ -89,7 +94,7 @@ func lookupJsonTags(f reflect.StructField) (name string, omit bool, inline bool, omitzero = OmitZeroFunc(f.Type) } - return name, false, opts.Contains("inline"), opts.Contains("omitempty"), omitzero + return name, false, inline, opts.Contains("omitempty"), omitzero } func isEmpty(v reflect.Value) bool { diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/reflectcache.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/reflectcache.go index 75b7085c3..f4f4c2b44 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/reflectcache.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/reflectcache.go @@ -39,14 +39,28 @@ type UnstructuredConverter interface { ToUnstructured() interface{} } +// UnstructuredConverterWithError is implemented instead of UnstructuredConverter by types for which +// some, but not all, values can be converted directly to unstructured. If a type implements both +// UnstructuredConverter and UnstructuredConverterWithError, its UnstructuredConverterWithError +// implementation takes precedence during conversion. +type UnstructuredConverterWithError interface { + json.Marshaler // require that json.Marshaler is implemented + + // ToUnstructured returns the unstructured representation, or a non-nil error if the value + // cannot be converted to unstructured. + ToUnstructuredWithError() (any, error) +} + // TypeReflectCacheEntry keeps data gathered using reflection about how a type is converted to/from unstructured. type TypeReflectCacheEntry struct { - isJsonMarshaler bool - ptrIsJsonMarshaler bool - isJsonUnmarshaler bool - ptrIsJsonUnmarshaler bool - isStringConvertable bool - ptrIsStringConvertable bool + isJsonMarshaler bool + ptrIsJsonMarshaler bool + isJsonUnmarshaler bool + ptrIsJsonUnmarshaler bool + isUnstructuredConverter bool + ptrIsUnstructuredConverter bool + isUnstructuredConverterWithError bool + ptrIsUnstructuredConverterWithError bool structFields map[string]*FieldCacheEntry orderedStructFields []*FieldCacheEntry @@ -93,9 +107,10 @@ func (f *FieldCacheEntry) GetFrom(structVal reflect.Value) reflect.Value { return structVal } -var marshalerType = reflect.TypeOf(new(json.Marshaler)).Elem() -var unmarshalerType = reflect.TypeOf(new(json.Unmarshaler)).Elem() -var unstructuredConvertableType = reflect.TypeOf(new(UnstructuredConverter)).Elem() +var marshalerType = reflect.TypeFor[json.Marshaler]() +var unmarshalerType = reflect.TypeFor[json.Unmarshaler]() +var unstructuredConverterType = reflect.TypeFor[UnstructuredConverter]() +var unstructuredConverterWithErrorType = reflect.TypeFor[UnstructuredConverterWithError]() var defaultReflectCache = newReflectCache() // TypeReflectEntryOf returns the TypeReflectCacheEntry of the provided reflect.Type. @@ -122,11 +137,13 @@ func typeReflectEntryOf(cm reflectCacheMap, t reflect.Type, updates reflectCache return record } typeEntry := &TypeReflectCacheEntry{ - isJsonMarshaler: t.Implements(marshalerType), - ptrIsJsonMarshaler: reflect.PtrTo(t).Implements(marshalerType), - isJsonUnmarshaler: reflect.PtrTo(t).Implements(unmarshalerType), - isStringConvertable: t.Implements(unstructuredConvertableType), - ptrIsStringConvertable: reflect.PtrTo(t).Implements(unstructuredConvertableType), + isJsonMarshaler: t.Implements(marshalerType), + ptrIsJsonMarshaler: reflect.PointerTo(t).Implements(marshalerType), + isJsonUnmarshaler: reflect.PointerTo(t).Implements(unmarshalerType), + isUnstructuredConverter: t.Implements(unstructuredConverterType), + ptrIsUnstructuredConverter: reflect.PointerTo(t).Implements(unstructuredConverterType), + isUnstructuredConverterWithError: t.Implements(unstructuredConverterWithErrorType), + ptrIsUnstructuredConverterWithError: reflect.PointerTo(t).Implements(unstructuredConverterWithErrorType), } if t.Kind() == reflect.Struct { fieldEntries := map[string]*FieldCacheEntry{} @@ -190,7 +207,7 @@ func (e TypeReflectCacheEntry) OrderedFields() []*FieldCacheEntry { // CanConvertToUnstructured returns true if this TypeReflectCacheEntry can convert values of its type to unstructured. func (e TypeReflectCacheEntry) CanConvertToUnstructured() bool { - return e.isJsonMarshaler || e.ptrIsJsonMarshaler || e.isStringConvertable || e.ptrIsStringConvertable + return e.isJsonMarshaler || e.ptrIsJsonMarshaler || e.isUnstructuredConverter || e.ptrIsUnstructuredConverter || e.isUnstructuredConverterWithError || e.ptrIsUnstructuredConverterWithError } // ToUnstructured converts the provided value to unstructured and returns it. @@ -206,7 +223,7 @@ func (e TypeReflectCacheEntry) ToUnstructured(sv reflect.Value) (interface{}, er // Check if the object has a custom string converter and use it if available, since it is much more efficient // than round tripping through json. if converter, ok := e.getUnstructuredConverter(sv); ok { - return converter.ToUnstructured(), nil + return converter.ToUnstructuredWithError() } // Check if the object has a custom JSON marshaller/unmarshaller. if marshaler, ok := e.getJsonMarshaler(sv); ok { @@ -318,16 +335,26 @@ func (e TypeReflectCacheEntry) getJsonUnmarshaler(v reflect.Value) (json.Unmarsh return v.Addr().Interface().(json.Unmarshaler), true } -func (e TypeReflectCacheEntry) getUnstructuredConverter(v reflect.Value) (UnstructuredConverter, bool) { - if e.isStringConvertable { - return v.Interface().(UnstructuredConverter), true - } - if e.ptrIsStringConvertable { +type unstructuredConverterWithNilError struct { + UnstructuredConverter +} + +func (c unstructuredConverterWithNilError) ToUnstructuredWithError() (any, error) { + return c.UnstructuredConverter.ToUnstructured(), nil +} + +func (e TypeReflectCacheEntry) getUnstructuredConverter(v reflect.Value) (UnstructuredConverterWithError, bool) { + switch { + case e.isUnstructuredConverterWithError: + return v.Interface().(UnstructuredConverterWithError), true + case e.ptrIsUnstructuredConverterWithError && v.CanAddr(): // Check pointer receivers if v is not a pointer - if v.CanAddr() { - v = v.Addr() - return v.Interface().(UnstructuredConverter), true - } + return v.Addr().Interface().(UnstructuredConverterWithError), true + case e.isUnstructuredConverter: + return unstructuredConverterWithNilError{v.Interface().(UnstructuredConverter)}, true + case e.ptrIsUnstructuredConverter && v.CanAddr(): + // Check pointer receivers if v is not a pointer + return unstructuredConverterWithNilError{v.Addr().Interface().(UnstructuredConverter)}, true } return nil, false } diff --git a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/value.go b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/value.go index 140b99038..167848ebe 100644 --- a/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/value.go +++ b/constraint/vendor/sigs.k8s.io/structured-merge-diff/v6/value/value.go @@ -118,6 +118,11 @@ func readJSONIter(iter *jsoniter.Iterator) (Value, error) { if iter.Error != nil && iter.Error != io.EOF { return nil, iter.Error } + if iter.WhatIsNext(); iter.Error == nil { + // Piggy back on scanner aware error reporting here. + iter.ReportError("managedFields parsing", "unexpected trailing data after JSON object") + return nil, iter.Error + } return NewValueInterface(v), nil }