From 27ae01f0c1bf95182db8920f858f735067aaec98 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 24 Apr 2026 07:24:00 +0000 Subject: [PATCH] build(deps): Bump k8s.io/apimachinery Bumps the k8sio group with 1 update in the / directory: [k8s.io/apimachinery](https://github.com/kubernetes/apimachinery). Updates `k8s.io/apimachinery` from 0.35.3 to 0.36.0 - [Commits](https://github.com/kubernetes/apimachinery/compare/v0.35.3...v0.36.0) --- updated-dependencies: - dependency-name: k8s.io/apimachinery dependency-version: 0.36.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8sio ... Signed-off-by: dependabot[bot] --- go.mod | 6 +- go.sum | 8 +- .../encoding/protodelim/protodelim.go | 9 +- .../protobuf/encoding/prototext/decode.go | 18 + .../protobuf/internal/descfmt/stringer.go | 269 +++++++------ .../protobuf/internal/version/version.go | 2 +- .../apimachinery/pkg/api/equality/semantic.go | 3 + .../pkg/api/validate/content/errors.go | 6 + .../pkg/api/validate/content/path.go | 63 ++++ .../pkg/api/validate/discriminator.go | 71 ++++ .../apimachinery/pkg/api/validate/limits.go | 85 ++++- .../apimachinery/pkg/api/validate/strfmt.go | 17 + .../apimachinery/pkg/api/validate/union.go | 19 +- .../meta/internalversion/conversion.go} | 18 +- .../pkg/apis/meta/internalversion/types.go | 5 + .../zz_generated.conversion.go | 16 +- .../apimachinery/pkg/apis/meta/v1/fieldsv1.go | 170 +++++++++ .../pkg/apis/meta/v1/fieldsv1_byte.go | 105 ++++++ .../pkg/apis/meta/v1/fieldsv1_string.go | 113 ++++++ .../pkg/apis/meta/v1/generated.pb.go | 353 +++++++++++------- .../pkg/apis/meta/v1/generated.proto | 56 +++ .../apis/meta/v1/generated.protomessage.pb.go | 112 ------ .../apimachinery/pkg/apis/meta/v1/helpers.go | 27 +- .../apimachinery/pkg/apis/meta/v1/meta.go | 9 + .../pkg/apis/meta/v1/micro_time_fuzz.go | 1 - .../pkg/apis/meta/v1/time_fuzz.go | 1 - .../apimachinery/pkg/apis/meta/v1/types.go | 73 ++-- .../meta/v1/types_swagger_doc_generated.go | 19 +- .../apis/meta/v1/zz_generated.conversion.go | 7 + .../pkg/apis/meta/v1/zz_generated.deepcopy.go | 45 ++- .../apis/meta/v1/zz_generated.model_name.go | 5 + .../meta/v1beta1/generated.protomessage.pb.go | 24 -- .../pkg/runtime/generated.protomessage.pb.go | 28 -- .../schema/generated.protomessage.pb.go | 22 -- .../serializer/cbor/internal/modes/decode.go | 18 +- .../pkg/runtime/serializer/cbor/raw.go | 4 +- .../k8s.io/apimachinery/pkg/util/diff/cmp.go | 31 -- .../k8s.io/apimachinery/pkg/util/diff/diff.go | 5 +- .../apimachinery/pkg/util/diff/legacy_diff.go | 2 +- .../k8s.io/apimachinery/pkg/util/dump/dump.go | 38 +- .../util/intstr/generated.protomessage.pb.go | 24 -- .../pkg/util/intstr/instr_fuzz.go | 1 - .../pkg/util/managedfields/extract.go | 3 +- .../pkg/util/managedfields/internal/fields.go | 7 +- .../apimachinery/pkg/util/mergepatch/util.go | 2 +- .../k8s.io/apimachinery/pkg/util/net/http.go | 5 + .../apimachinery/pkg/util/net/interface.go | 112 ++++-- .../apimachinery/pkg/util/runtime/runtime.go | 33 +- .../pkg/util/strategicpatch/patch.go | 8 +- .../util/validation/field/error_matcher.go | 40 +- .../pkg/util/validation/field/errors.go | 232 +++++++++++- .../apimachinery/pkg/util/validation/ip.go | 4 +- .../forked/golang/reflect/deep_equal.go | 4 +- .../klog/v2/internal/verbosity/verbosity.go | 303 +++++++++++++++ vendor/k8s.io/klog/v2/textlogger/options.go | 172 +++++++++ .../k8s.io/klog/v2/textlogger/textlogger.go | 200 ++++++++++ .../klog/v2/textlogger/textlogger_slog.go | 52 +++ vendor/k8s.io/utils/dump/dump.go | 54 +++ vendor/modules.txt | 9 +- 59 files changed, 2429 insertions(+), 719 deletions(-) create mode 100644 vendor/k8s.io/apimachinery/pkg/api/validate/content/path.go create mode 100644 vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go rename vendor/k8s.io/apimachinery/pkg/{api/resource/generated.protomessage.pb.go => apis/meta/internalversion/conversion.go} (51%) create mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1.go create mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_byte.go create mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_string.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.protomessage.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.protomessage.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/generated.protomessage.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.protomessage.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/diff/cmp.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/intstr/generated.protomessage.pb.go create mode 100644 vendor/k8s.io/klog/v2/internal/verbosity/verbosity.go create mode 100644 vendor/k8s.io/klog/v2/textlogger/options.go create mode 100644 vendor/k8s.io/klog/v2/textlogger/textlogger.go create mode 100644 vendor/k8s.io/klog/v2/textlogger/textlogger_slog.go create mode 100644 vendor/k8s.io/utils/dump/dump.go diff --git a/go.mod b/go.mod index f33b34e1f..679d33b96 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/NVIDIA/gpu-operator -go 1.25.7 +go 1.26.0 require ( github.com/Masterminds/sprig/v3 v3.3.0 @@ -26,7 +26,7 @@ require ( golang.org/x/mod v0.35.0 k8s.io/api v0.35.3 k8s.io/apiextensions-apiserver v0.35.3 - k8s.io/apimachinery v0.35.3 + k8s.io/apimachinery v0.36.0 k8s.io/client-go v0.35.3 k8s.io/klog/v2 v2.140.0 k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 @@ -117,7 +117,7 @@ require ( golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.43.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect - google.golang.org/protobuf v1.36.11 // indirect + 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 diff --git a/go.sum b/go.sum index 21d253ee0..a3bd5ae12 100644 --- a/go.sum +++ b/go.sum @@ -296,8 +296,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -312,8 +312,8 @@ k8s.io/api v0.35.3 h1:pA2fiBc6+N9PDf7SAiluKGEBuScsTzd2uYBkA5RzNWQ= k8s.io/api v0.35.3/go.mod h1:9Y9tkBcFwKNq2sxwZTQh1Njh9qHl81D0As56tu42GA4= k8s.io/apiextensions-apiserver v0.35.3 h1:2fQUhEO7P17sijylbdwt0nBdXP0TvHrHj0KeqHD8FiU= k8s.io/apiextensions-apiserver v0.35.3/go.mod h1:tK4Kz58ykRpwAEkXUb634HD1ZAegEElktz/B3jgETd8= -k8s.io/apimachinery v0.35.3 h1:MeaUwQCV3tjKP4bcwWGgZ/cp/vpsRnQzqO6J6tJyoF8= -k8s.io/apimachinery v0.35.3/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= +k8s.io/apimachinery v0.36.0 h1:jZyPzhd5Z+3h9vJLt0z9XdzW9VzNzWAUw+P1xZ9PXtQ= +k8s.io/apimachinery v0.36.0/go.mod h1:FklypaRJt6n5wUIwWXIP6GJlIpUizTgfo1T/As+Tyxc= k8s.io/cli-runtime v0.35.1 h1:uKcXFe8J7AMAM4Gm2JDK4mp198dBEq2nyeYtO+JfGJE= k8s.io/cli-runtime v0.35.1/go.mod h1:55/hiXIq1C8qIJ3WBrWxEwDLdHQYhBNRdZOz9f7yvTw= k8s.io/client-go v0.35.3 h1:s1lZbpN4uI6IxeTM2cpdtrwHcSOBML1ODNTCCfsP1pg= diff --git a/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go b/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go index 2ef36bbcf..ec63689e7 100644 --- a/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go +++ b/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go @@ -10,6 +10,7 @@ import ( "encoding/binary" "fmt" "io" + "math" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" @@ -117,7 +118,13 @@ func (o UnmarshalOptions) UnmarshalFrom(r Reader, m proto.Message) error { if maxSize == 0 { maxSize = defaultMaxSize } - if maxSize != -1 && size > uint64(maxSize) { + if maxSize == -1 { + // No limit specified: Just check that size fits into an integer, + // otherwise the make([]byte, size) call below will panic. + if size > math.MaxInt { + return errors.Wrap(&SizeTooLargeError{Size: size, MaxSize: math.MaxInt}, "") + } + } else if size > uint64(maxSize) { return errors.Wrap(&SizeTooLargeError{Size: size, MaxSize: uint64(maxSize)}, "") } diff --git a/vendor/google.golang.org/protobuf/encoding/prototext/decode.go b/vendor/google.golang.org/protobuf/encoding/prototext/decode.go index b53805056..20ec09e19 100644 --- a/vendor/google.golang.org/protobuf/encoding/prototext/decode.go +++ b/vendor/google.golang.org/protobuf/encoding/prototext/decode.go @@ -8,6 +8,7 @@ import ( "fmt" "unicode/utf8" + "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" @@ -49,12 +50,19 @@ type UnmarshalOptions struct { protoregistry.MessageTypeResolver protoregistry.ExtensionTypeResolver } + + // RecursionLimit limits how deeply messages may be nested. + // If zero, a default limit is applied. + RecursionLimit int } // Unmarshal reads the given []byte and populates the given [proto.Message] // using options in the UnmarshalOptions object. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { + if o.RecursionLimit == 0 { + o.RecursionLimit = protowire.DefaultRecursionLimit + } return o.unmarshal(b, m) } @@ -102,8 +110,14 @@ func (d decoder) syntaxError(pos int, f string, x ...any) error { return errors.New(head+f, x...) } +var errRecursionDepth = errors.New("exceeded maximum recursion depth") + // unmarshalMessage unmarshals into the given protoreflect.Message. func (d decoder) unmarshalMessage(m protoreflect.Message, checkDelims bool) error { + if d.opts.RecursionLimit--; d.opts.RecursionLimit < 0 { + return errRecursionDepth + } + messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") @@ -437,6 +451,10 @@ func (d decoder) unmarshalList(fd protoreflect.FieldDescriptor, list protoreflec // unmarshalMap unmarshals into given protoreflect.Map. A map value is a // textproto message containing {key: , value: }. func (d decoder) unmarshalMap(fd protoreflect.FieldDescriptor, mmap protoreflect.Map) error { + if d.opts.RecursionLimit--; d.opts.RecursionLimit < 0 { + return errRecursionDepth + } + // Determine ahead whether map entry is a scalar type or a message type in // order to call the appropriate unmarshalMapValue func inside // unmarshalMapEntry. diff --git a/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go index 87e46bd4d..0b0dfacbe 100644 --- a/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go +++ b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go @@ -83,12 +83,13 @@ func formatListOpt(vs list, isRoot, allowMulti bool) string { case protoreflect.FileImports: for i := 0; i < vs.Len(); i++ { var rs records - rv := reflect.ValueOf(vs.Get(i)) - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Path"), "Path"}, - {rv.MethodByName("Package"), "Package"}, - {rv.MethodByName("IsPublic"), "IsPublic"}, - {rv.MethodByName("IsWeak"), "IsWeak"}, + fi := vs.Get(i) + rv := reflect.ValueOf(fi) + rs.Append(rv, []attrAndName{ + {fi.Path(), "Path"}, + {fi.Package(), "Package"}, + {fi.IsPublic, "IsPublic"}, + {fi.IsWeak, "IsWeak"}, }...) ss = append(ss, "{"+rs.Join()+"}") } @@ -104,9 +105,9 @@ func formatListOpt(vs list, isRoot, allowMulti bool) string { } } -type methodAndName struct { - method reflect.Value - name string +type attrAndName struct { + attr any + name string } func FormatDesc(s fmt.State, r rune, t protoreflect.Descriptor) { @@ -126,58 +127,58 @@ func formatDescOpt(t protoreflect.Descriptor, isRoot, allowMulti bool, record fu start = rt.Name() + "{" } - _, isFile := t.(protoreflect.FileDescriptor) + fd, isFile := t.(protoreflect.FileDescriptor) rs := records{ allowMulti: allowMulti, record: record, } if t.IsPlaceholder() { if isFile { - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Path"), "Path"}, - {rv.MethodByName("Package"), "Package"}, - {rv.MethodByName("IsPlaceholder"), "IsPlaceholder"}, + rs.Append(rv, []attrAndName{ + {fd.Path(), "Path"}, + {fd.Package(), "Package"}, + {fd.IsPlaceholder(), "IsPlaceholder"}, }...) } else { - rs.Append(rv, []methodAndName{ - {rv.MethodByName("FullName"), "FullName"}, - {rv.MethodByName("IsPlaceholder"), "IsPlaceholder"}, + rs.Append(rv, []attrAndName{ + {t.FullName(), "FullName"}, + {t.IsPlaceholder(), "IsPlaceholder"}, }...) } } else { switch { case isFile: - rs.Append(rv, methodAndName{rv.MethodByName("Syntax"), "Syntax"}) + rs.Append(rv, attrAndName{fd.Syntax(), "Syntax"}) case isRoot: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Syntax"), "Syntax"}, - {rv.MethodByName("FullName"), "FullName"}, + rs.Append(rv, []attrAndName{ + {t.Syntax(), "Syntax"}, + {t.FullName(), "FullName"}, }...) default: - rs.Append(rv, methodAndName{rv.MethodByName("Name"), "Name"}) + rs.Append(rv, attrAndName{t.Name(), "Name"}) } switch t := t.(type) { case protoreflect.FieldDescriptor: - accessors := []methodAndName{ - {rv.MethodByName("Number"), "Number"}, - {rv.MethodByName("Cardinality"), "Cardinality"}, - {rv.MethodByName("Kind"), "Kind"}, - {rv.MethodByName("HasJSONName"), "HasJSONName"}, - {rv.MethodByName("JSONName"), "JSONName"}, - {rv.MethodByName("HasPresence"), "HasPresence"}, - {rv.MethodByName("IsExtension"), "IsExtension"}, - {rv.MethodByName("IsPacked"), "IsPacked"}, - {rv.MethodByName("IsWeak"), "IsWeak"}, - {rv.MethodByName("IsList"), "IsList"}, - {rv.MethodByName("IsMap"), "IsMap"}, - {rv.MethodByName("MapKey"), "MapKey"}, - {rv.MethodByName("MapValue"), "MapValue"}, - {rv.MethodByName("HasDefault"), "HasDefault"}, - {rv.MethodByName("Default"), "Default"}, - {rv.MethodByName("ContainingOneof"), "ContainingOneof"}, - {rv.MethodByName("ContainingMessage"), "ContainingMessage"}, - {rv.MethodByName("Message"), "Message"}, - {rv.MethodByName("Enum"), "Enum"}, + accessors := []attrAndName{ + {t.Number(), "Number"}, + {t.Cardinality(), "Cardinality"}, + {t.Kind(), "Kind"}, + {t.HasJSONName(), "HasJSONName"}, + {t.JSONName(), "JSONName"}, + {t.HasPresence(), "HasPresence"}, + {t.IsExtension(), "IsExtension"}, + {t.IsPacked(), "IsPacked"}, + {t.IsWeak(), "IsWeak"}, + {t.IsList(), "IsList"}, + {t.IsMap(), "IsMap"}, + {t.MapKey(), "MapKey"}, + {t.MapValue(), "MapValue"}, + {t.HasDefault(), "HasDefault"}, + {t.Default(), "Default"}, + {t.ContainingOneof(), "ContainingOneof"}, + {t.ContainingMessage(), "ContainingMessage"}, + {t.Message(), "Message"}, + {t.Enum(), "Enum"}, } for _, s := range accessors { switch s.name { @@ -223,58 +224,54 @@ func formatDescOpt(t protoreflect.Descriptor, isRoot, allowMulti bool, record fu } case protoreflect.FileDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Path"), "Path"}, - {rv.MethodByName("Package"), "Package"}, - {rv.MethodByName("Imports"), "Imports"}, - {rv.MethodByName("Messages"), "Messages"}, - {rv.MethodByName("Enums"), "Enums"}, - {rv.MethodByName("Extensions"), "Extensions"}, - {rv.MethodByName("Services"), "Services"}, + rs.Append(rv, []attrAndName{ + {t.Path(), "Path"}, + {t.Package(), "Package"}, + {t.Imports(), "Imports"}, + {t.Messages(), "Messages"}, + {t.Enums(), "Enums"}, + {t.Extensions(), "Extensions"}, + {t.Services(), "Services"}, }...) case protoreflect.MessageDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("IsMapEntry"), "IsMapEntry"}, - {rv.MethodByName("Fields"), "Fields"}, - {rv.MethodByName("Oneofs"), "Oneofs"}, - {rv.MethodByName("ReservedNames"), "ReservedNames"}, - {rv.MethodByName("ReservedRanges"), "ReservedRanges"}, - {rv.MethodByName("RequiredNumbers"), "RequiredNumbers"}, - {rv.MethodByName("ExtensionRanges"), "ExtensionRanges"}, - {rv.MethodByName("Messages"), "Messages"}, - {rv.MethodByName("Enums"), "Enums"}, - {rv.MethodByName("Extensions"), "Extensions"}, + rs.Append(rv, []attrAndName{ + {t.IsMapEntry(), "IsMapEntry"}, + {t.Fields(), "Fields"}, + {t.Oneofs(), "Oneofs"}, + {t.ReservedNames(), "ReservedNames"}, + {t.ReservedRanges(), "ReservedRanges"}, + {t.RequiredNumbers(), "RequiredNumbers"}, + {t.ExtensionRanges(), "ExtensionRanges"}, + {t.Messages(), "Messages"}, + {t.Enums(), "Enums"}, + {t.Extensions(), "Extensions"}, }...) case protoreflect.EnumDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Values"), "Values"}, - {rv.MethodByName("ReservedNames"), "ReservedNames"}, - {rv.MethodByName("ReservedRanges"), "ReservedRanges"}, - {rv.MethodByName("IsClosed"), "IsClosed"}, + rs.Append(rv, []attrAndName{ + {t.Values(), "Values"}, + {t.ReservedNames(), "ReservedNames"}, + {t.ReservedRanges(), "ReservedRanges"}, + {t.IsClosed(), "IsClosed"}, }...) case protoreflect.EnumValueDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Number"), "Number"}, - }...) + rs.Append(rv, attrAndName{t.Number(), "Number"}) case protoreflect.ServiceDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Methods"), "Methods"}, - }...) + rs.Append(rv, attrAndName{t.Methods(), "Methods"}) case protoreflect.MethodDescriptor: - rs.Append(rv, []methodAndName{ - {rv.MethodByName("Input"), "Input"}, - {rv.MethodByName("Output"), "Output"}, - {rv.MethodByName("IsStreamingClient"), "IsStreamingClient"}, - {rv.MethodByName("IsStreamingServer"), "IsStreamingServer"}, + rs.Append(rv, []attrAndName{ + {t.Input(), "Input"}, + {t.Output(), "Output"}, + {t.IsStreamingClient(), "IsStreamingClient"}, + {t.IsStreamingServer(), "IsStreamingServer"}, }...) } - if m := rv.MethodByName("GoType"); m.IsValid() { - rs.Append(rv, methodAndName{m, "GoType"}) + if m, ok := t.(interface{ GoType() reflect.Type }); ok { + rs.Append(rv, attrAndName{m.GoType(), "GoType"}) } } return start + rs.Join() + end @@ -297,68 +294,66 @@ func (rs *records) AppendRecs(fieldName string, newRecs [2]string) { rs.recs = append(rs.recs, newRecs) } -func (rs *records) Append(v reflect.Value, accessors ...methodAndName) { - for _, a := range accessors { - if rs.record != nil { - rs.record(a.name) - } - var rv reflect.Value - if a.method.IsValid() { - rv = a.method.Call(nil)[0] - } - if v.Kind() == reflect.Struct && !rv.IsValid() { - rv = v.FieldByName(a.name) - } - if !rv.IsValid() { - panic(fmt.Sprintf("unknown accessor: %v.%s", v.Type(), a.name)) - } - if _, ok := rv.Interface().(protoreflect.Value); ok { - rv = rv.MethodByName("Interface").Call(nil)[0] - if !rv.IsNil() { - rv = rv.Elem() - } - } +func (rs *records) Append(v reflect.Value, results ...attrAndName) { + for _, r := range results { + rs.appendAttribute(v, r.name, r.attr) + } +} - // Ignore zero values. - var isZero bool - switch rv.Kind() { - case reflect.Interface, reflect.Slice: - isZero = rv.IsNil() - case reflect.Bool: - isZero = rv.Bool() == false - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - isZero = rv.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - isZero = rv.Uint() == 0 - case reflect.String: - isZero = rv.String() == "" - } - if n, ok := rv.Interface().(list); ok { - isZero = n.Len() == 0 - } - if isZero { - continue +func (rs *records) appendAttribute(val reflect.Value, name string, attrVal any) { + if rs.record != nil { + rs.record(name) + } + if attrVal == nil { + return + } + rv := reflect.ValueOf(attrVal) + if _, ok := rv.Interface().(protoreflect.Value); ok { + rv = rv.MethodByName("Interface").Call(nil)[0] + if !rv.IsNil() { + rv = rv.Elem() } + } - // Format the value. - var s string - v := rv.Interface() - switch v := v.(type) { - case list: - s = formatListOpt(v, false, rs.allowMulti) - case protoreflect.FieldDescriptor, protoreflect.OneofDescriptor, protoreflect.EnumValueDescriptor, protoreflect.MethodDescriptor: - s = string(v.(protoreflect.Descriptor).Name()) - case protoreflect.Descriptor: - s = string(v.FullName()) - case string: - s = strconv.Quote(v) - case []byte: - s = fmt.Sprintf("%q", v) - default: - s = fmt.Sprint(v) - } - rs.recs = append(rs.recs, [2]string{a.name, s}) + // Ignore zero values. + var isZero bool + switch rv.Kind() { + case reflect.Interface, reflect.Slice: + isZero = rv.IsNil() + case reflect.Bool: + isZero = rv.Bool() == false + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + isZero = rv.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + isZero = rv.Uint() == 0 + case reflect.String: + isZero = rv.String() == "" + } + if n, ok := rv.Interface().(list); ok { + isZero = n.Len() == 0 + } + if isZero { + return + } + + // Format the value. + var s string + v := rv.Interface() + switch v := v.(type) { + case list: + s = formatListOpt(v, false, rs.allowMulti) + case protoreflect.FieldDescriptor, protoreflect.OneofDescriptor, protoreflect.EnumValueDescriptor, protoreflect.MethodDescriptor: + s = string(v.(protoreflect.Descriptor).Name()) + case protoreflect.Descriptor: + s = string(v.FullName()) + case string: + s = strconv.Quote(v) + case []byte: + s = fmt.Sprintf("%q", v) + default: + s = fmt.Sprint(v) } + rs.recs = append(rs.recs, [2]string{name, s}) } func (rs *records) Join() string { diff --git a/vendor/google.golang.org/protobuf/internal/version/version.go b/vendor/google.golang.org/protobuf/internal/version/version.go index 763fd8284..bfb2cfdea 100644 --- a/vendor/google.golang.org/protobuf/internal/version/version.go +++ b/vendor/google.golang.org/protobuf/internal/version/version.go @@ -53,7 +53,7 @@ const ( Major = 1 Minor = 36 Patch = 11 - PreRelease = "" + PreRelease = "devel" ) // String formats the version string for this module in semver format. diff --git a/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go b/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go index f02fa8e43..cd78c3841 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go +++ b/vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go @@ -40,6 +40,9 @@ var Semantic = conversion.EqualitiesOrDie( func(a, b metav1.Time) bool { return a.UTC() == b.UTC() }, + func(a, b metav1.FieldsV1) bool { + return a.Equal(b) + }, func(a, b labels.Selector) bool { return a.String() == b.String() }, diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/content/errors.go b/vendor/k8s.io/apimachinery/pkg/api/validate/content/errors.go index a4a1b5574..13eeced1a 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/validate/content/errors.go +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/content/errors.go @@ -29,6 +29,12 @@ func MinError[T constraints.Integer](min T) string { return fmt.Sprintf("must be greater than or equal to %d", min) } +// MaxError returns a string explanation of a "must be less than or equal" +// validation failure. +func MaxError[T constraints.Integer](max T) string { + return fmt.Sprintf("must be less than or equal to %d", max) +} + // MaxLenError returns a string explanation of a "string too long" validation // failure. func MaxLenError(length int) string { diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/content/path.go b/vendor/k8s.io/apimachinery/pkg/api/validate/content/path.go new file mode 100644 index 000000000..c41b1d473 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/content/path.go @@ -0,0 +1,63 @@ +/* +Copyright 2015 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package content + +import ( + "fmt" + "strings" +) + +// Strings that cannot be used as names specified as path segments (like the +// REST API or etcd store). +var pathSegmentNameMayNotBe = []string{".", ".."} + +// Substrings that cannot be used in names specified as path segments (like the +// REST API or etcd store). +var pathSegmentNameMayNotContain = []string{"/", "%"} + +// IsPathSegmentName validates the name can be safely encoded as a path +// segment. +// +// Note that, for historical reason, this function does not check for +// empty strings or impose a limit on the length of the name. +func IsPathSegmentName(name string) []string { + for _, illegalName := range pathSegmentNameMayNotBe { + if name == illegalName { + return []string{fmt.Sprintf(`may not be '%s'`, illegalName)} + } + } + + return IsPathSegmentPrefix(name) +} + +// IsPathSegmentPrefix validates the name can be used as a prefix for a +// name which will be encoded as a path segment It does not check for exact +// matches with disallowed names, since an arbitrary suffix might make the name +// valid. +// +// Note that, for historical reason, this function does not check for +// empty strings or impose a limit on the length of the name. +func IsPathSegmentPrefix(name string) []string { + var errors []string + for _, illegalContent := range pathSegmentNameMayNotContain { + if strings.Contains(name, illegalContent) { + errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent)) + } + } + + return errors +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go b/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go new file mode 100644 index 000000000..787ae6b0b --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/discriminator.go @@ -0,0 +1,71 @@ +/* +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" + + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +// DiscriminatedRule defines a validation to apply for a specific discriminator value. +type DiscriminatedRule[Tfield any, Tdisc comparable] struct { + Value Tdisc + Validation ValidateFunc[Tfield] +} + +// Discriminated validates a member field based on a discriminator value. +// It iterates through the rules and applies the first one that matches the discriminator. +// If no rule matches, it applies the defaultValidation if provided. +// +// It performs ratcheting: if the operation is an Update, and neither the discriminator +// nor the value (checked via equiv) have changed, validation is skipped. +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], +) field.ErrorList { + value := getMemberValue(obj) + discriminator := getDiscriminator(obj) + var oldValue Tfield + var oldDiscriminator Tdisc + + if oldObj != nil { + oldValue = getMemberValue(oldObj) + oldDiscriminator = getDiscriminator(oldObj) + } + + if op.Type == operation.Update && oldObj != nil && discriminator == oldDiscriminator && equiv(value, oldValue) { + return nil + } + + fldPath := structPath.Child(fieldName) + for _, rule := range rules { + if rule.Value == discriminator { + if rule.Validation == nil { + return nil + } + return rule.Validation(ctx, op, fldPath, value, oldValue) + } + } + + if defaultValidation != nil { + return defaultValidation(ctx, op, fldPath, value, oldValue) + } + + return nil +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go b/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go index b6db5e08c..dcc7f518d 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/limits.go @@ -18,6 +18,8 @@ package validate import ( "context" + "math" + "unicode/utf8" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/api/validate/constraints" @@ -31,9 +33,40 @@ func MaxLength[T ~string](_ context.Context, _ operation.Operation, fldPath *fie if value == nil { return nil } + + // if the length of the value in bytes is less + // than the maximum size then we can confidently + // say that this value is within the bounds + // enforced by the maximum value regardless + // of the actual makeup of characters in the value + byteLength := len(*value) + if byteLength <= max { + return nil + } + + // because runes are up to 4 byte characters, if we assume all characters + // in the input are runes, the minimum number of characters that + // are specified is len(value)/4. If the minimum multi-byte + // character count is greater than our enforced maximum, we + // can confidently say that the value is invalid without having + // to actually perform the more expensive rune counting step + minimum := int(math.Ceil(float64(byteLength) / 4.0)) + if minimum > max || utf8.RuneCountInString(string(*value)) > max { + return field.ErrorList{field.TooLongCharacters(fldPath, *value, max).WithOrigin("maxLength")} + } + return nil +} + +// MaxBytes verifies that the specified value is not longer than max bytes. +func MaxBytes[T ~string](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, max int) field.ErrorList { + if value == nil { + return nil + } + if len(*value) > max { - return field.ErrorList{field.TooLong(fldPath, *value, max).WithOrigin("maxLength")} + return field.ErrorList{field.TooLong(fldPath, *value, max).WithOrigin("maxBytes")} } + return nil } @@ -45,6 +78,14 @@ func MaxItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Pa 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 { + return field.ErrorList{field.TooFew(fldPath, len(value), min).WithOrigin("minItems")} + } + 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 { @@ -55,3 +96,45 @@ func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fl } return nil } + +// Maximum verifies that the specified value is less than or equal to max. +func Maximum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, max T) field.ErrorList { + if value == nil { + return nil + } + if *value > max { + return field.ErrorList{field.Invalid(fldPath, *value, content.MaxError(max)).WithOrigin("maximum")} + } + return nil +} + +// MinLength verifies that the specified value is at least min characters, if non-nil. +func MinLength[T ~string](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min int) field.ErrorList { + if value == nil { + return nil + } + + byteLength := len(*value) + + // because runes are up to 4 byte characters, if we assume all characters + // in the input are 4 byte runes, the minimum number of characters that + // are specified is len(value)/4. If the minimum multi-byte + // character count is greater than or equal to our enforced minimum, we + // can confidently say that the value is valid without having + // to actually perform the more expensive rune counting step + if int(math.Ceil(float64(byteLength)/4.0)) >= min { + return nil + } + + // if the length of the value in bytes is less + // than the minimum size then we can confidently + // say that this value is not within the bounds + // enforced by the maximum value regardless + // of the actual makeup of characters in the value. + // Otherwise, perform a rune count to determine if the + // number of characters is less than the minimum. + if byteLength < min || utf8.RuneCountInString(string(*value)) < min { + return field.ErrorList{field.TooShort(fldPath, *value, min).WithOrigin("minLength")} + } + return nil +} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go b/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go index 9a2147305..190fa8dbe 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/strfmt.go @@ -133,6 +133,23 @@ func LabelValue[T ~string](_ context.Context, op operation.Operation, fldPath *f return allErrs } +// PathSegmentName verifies that the specified value is a valid path segment name. +// A path segment name can be safely encoded as a path segment in URLs and file paths. +// - must not be exactly "." or ".." +// - must not contain "/" (forward slash) +// - must not contain "%" (percent sign) +// - can contain any other characters including mixed case, numbers, dots, hyphens, underscores, and non-ASCII characters +func PathSegmentName[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.IsPathSegmentName((string)(*value)) { + allErrs = append(allErrs, field.Invalid(fldPath, *value, msg).WithOrigin("format=k8s-path-segment-name")) + } + return allErrs +} + // UUID verifies that the specified value is a valid UUID (RFC 4122). // - must be 36 characters long // - must be in the normalized form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` diff --git a/vendor/k8s.io/apimachinery/pkg/api/validate/union.go b/vendor/k8s.io/apimachinery/pkg/api/validate/union.go index 03f45f866..753a4a9ee 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/validate/union.go +++ b/vendor/k8s.io/apimachinery/pkg/api/validate/union.go @@ -19,6 +19,7 @@ package validate import ( "context" "fmt" + "reflect" "strings" "k8s.io/apimachinery/pkg/api/operation" @@ -60,6 +61,10 @@ type UnionValidationOptions struct { // )...) // return errs // } +// +// Note that T is "any", rather than "comparable", because union-members can be +// slices, meaning T might be a struct with a slice, meaning it is not +// comparable. func Union[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, isSetFns ...ExtractorFn[T, bool]) field.ErrorList { options := UnionValidationOptions{ ErrorForEmpty: func(fldPath *field.Path, allFields []string) *field.Error { @@ -72,7 +77,7 @@ func Union[T any](_ context.Context, op operation.Operation, fldPath *field.Path }, } - return unionValidate(op, fldPath, obj, oldObj, union, options, isSetFns...) + return unionValidate(op, fldPath, obj, oldObj, union, options, isSetFns...).WithOrigin("union") } // DiscriminatedUnion verifies specified union member matches the discriminator. @@ -98,6 +103,10 @@ func Union[T any](_ context.Context, op operation.Operation, fldPath *field.Path // // It is not an error for the discriminatorValue to be unknown. That must be // validated on its own. +// +// Note that T is "any", rather than "comparable", because union-members can be +// slices, meaning T might be a struct with a slice, meaning it is not +// comparable. func DiscriminatedUnion[T any, D ~string](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, discriminatorExtractor ExtractorFn[T, D], isSetFns ...ExtractorFn[T, bool]) (errs field.ErrorList) { if len(union.members) != len(isSetFns) { return field.ErrorList{ @@ -106,6 +115,7 @@ func DiscriminatedUnion[T any, D ~string](_ context.Context, op operation.Operat len(isSetFns), len(union.members))), } } + hasOldValue := !reflect.ValueOf(oldObj).IsZero() // because T is any, rather than comparable var changed bool discriminatorValue := discriminatorExtractor(obj) if op.Type == operation.Update { @@ -131,10 +141,10 @@ func DiscriminatedUnion[T any, D ~string](_ context.Context, op operation.Operat } // If the union discriminator and membership is unchanged, we don't need to // re-validate. - if op.Type == operation.Update && !changed { + if op.Type == operation.Update && hasOldValue && !changed { return nil } - return errs + return errs.WithOrigin("union") } // UnionMember represents a member of a union. @@ -195,6 +205,7 @@ func unionValidate[T any](op operation.Operation, fldPath *field.Path, } } + hasOldValue := !reflect.ValueOf(oldObj).IsZero() // because T is any, rather than comparable var specifiedFields []string var changed bool for i, fieldIsSet := range isSetFns { @@ -209,7 +220,7 @@ func unionValidate[T any](op operation.Operation, fldPath *field.Path, } // If the union membership is unchanged, we don't need to re-validate. - if op.Type == operation.Update && !changed { + if op.Type == operation.Update && hasOldValue && !changed { return nil } diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go similarity index 51% rename from vendor/k8s.io/apimachinery/pkg/api/resource/generated.protomessage.pb.go rename to vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go index 712e155c3..f431157ec 100644 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/generated.protomessage.pb.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go @@ -1,6 +1,3 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - /* Copyright The Kubernetes Authors. @@ -17,10 +14,17 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Code generated by go-to-protobuf. DO NOT EDIT. +package internalversion -package resource +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/conversion" +) -func (*Quantity) ProtoMessage() {} +func Convert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOptions, out *ListOptions, s conversion.Scope) error { + return autoConvert_v1_ListOptions_To_internalversion_ListOptions(in, out, s) +} -func (*QuantityValue) ProtoMessage() {} +func Convert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *v1.ListOptions, s conversion.Scope) error { + return autoConvert_internalversion_ListOptions_To_v1_ListOptions(in, out, s) +} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go index 8c60e7d2a..a34a11c3e 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go @@ -89,6 +89,11 @@ type ListOptions struct { // Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward // compatibility reasons) and to false otherwise. SendInitialEvents *bool + + // ShardSelector is the raw shard selector string from the request. + // Parsing is deferred to the apiserver storage layer where the CEL + // parser dependency is available. + ShardSelector string } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go index a6552c276..f321ad234 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go @@ -46,12 +46,12 @@ func RegisterConversions(s *runtime.Scheme) error { }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*ListOptions)(nil), (*v1.ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error { + if err := s.AddConversionFunc((*ListOptions)(nil), (*v1.ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_internalversion_ListOptions_To_v1_ListOptions(a.(*ListOptions), b.(*v1.ListOptions), scope) }); err != nil { return err } - if err := s.AddGeneratedConversionFunc((*v1.ListOptions)(nil), (*ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error { + if err := s.AddConversionFunc((*v1.ListOptions)(nil), (*ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_ListOptions_To_internalversion_ListOptions(a.(*v1.ListOptions), b.(*ListOptions), scope) }); err != nil { return err @@ -116,14 +116,10 @@ func autoConvert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out.Limit = in.Limit out.Continue = in.Continue out.SendInitialEvents = (*bool)(unsafe.Pointer(in.SendInitialEvents)) + out.ShardSelector = in.ShardSelector return nil } -// Convert_internalversion_ListOptions_To_v1_ListOptions is an autogenerated conversion function. -func Convert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *v1.ListOptions, s conversion.Scope) error { - return autoConvert_internalversion_ListOptions_To_v1_ListOptions(in, out, s) -} - func autoConvert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOptions, out *ListOptions, s conversion.Scope) error { if err := v1.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil { return err @@ -139,10 +135,6 @@ func autoConvert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOption out.Limit = in.Limit out.Continue = in.Continue out.SendInitialEvents = (*bool)(unsafe.Pointer(in.SendInitialEvents)) + out.ShardSelector = in.ShardSelector return nil } - -// Convert_v1_ListOptions_To_internalversion_ListOptions is an autogenerated conversion function. -func Convert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOptions, out *ListOptions, s conversion.Scope) error { - return autoConvert_v1_ListOptions_To_internalversion_ListOptions(in, out, s) -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1.go new file mode 100644 index 000000000..81aca59fa --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1.go @@ -0,0 +1,170 @@ +/* +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 ( + "fmt" + "io" +) + +func (FieldsV1) SwaggerDoc() map[string]string { + return map[string]string{ + "": "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff", + } +} + +type FieldsV1Reader interface { + io.Reader + io.ReaderAt + // Size returns the original byte length of the underlying data. Size is the number of bytes available for reading via ReadAt. + Size() int64 +} + +func (f *FieldsV1) DeepCopy() *FieldsV1 { + if f == nil { + return nil + } + out := new(FieldsV1) + f.DeepCopyInto(out) + return out +} + +func (f *FieldsV1) Marshal() (dAtA []byte, err error) { + size := f.Size() + dAtA = make([]byte, size) + n, err := f.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (f *FieldsV1) MarshalTo(dAtA []byte) (int, error) { + size := f.Size() + return f.MarshalToSizedBuffer(dAtA[:size]) +} + +func (f *FieldsV1) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + rawBytes := f.GetRawBytes() + if len(rawBytes) > 0 { + i -= len(rawBytes) + copy(dAtA[i:], rawBytes) + i = encodeVarintGenerated(dAtA, i, uint64(len(rawBytes))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (f *FieldsV1) Size() (n int) { + if f == nil { + return 0 + } + var l int + _ = l + if l := int(f.GetRawReader().Size()); l > 0 { + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func (f *FieldsV1) 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: FieldsV1: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: FieldsV1: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Raw", 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 + } + + f.SetRawBytes(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 +} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_byte.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_byte.go new file mode 100644 index 000000000..66f28e1d9 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_byte.go @@ -0,0 +1,105 @@ +//go:build !fieldsv1string + +/* +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 ( + "bytes" +) + +// FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format. +// +// Each key is either a '.' representing the field itself, and will always map to an empty set, +// or a string representing a sub-field or item. The string will follow one of these four formats: +// 'f:', where is the name of a field in a struct, or key in a map +// 'v:', where is the exact json formatted value of a list item +// 'i:', where is position of a item in a list +// 'k:', where is a map of a list item's key fields to their unique values +// If a key maps to an empty Fields value, the field that key represents is part of the set. +// +// The exact format is defined in sigs.k8s.io/structured-merge-diff +// +k8s:deepcopy-gen=false +// +protobuf.options.marshal=false +// +protobuf.options.(gogoproto.goproto_stringer)=false +type FieldsV1 struct { + // Raw is the underlying serialization of this object. + // + // Deprecated: Direct access to this field is deprecated. Use GetRawBytes, GetRawString, SetRawBytes, SetRawString, GetRawReader, NewFieldsV1 instead. + Raw []byte `json:"-" protobuf:"bytes,1,opt,name=Raw"` +} + +func (f FieldsV1) String() string { + return string(f.Raw) +} + +func (f FieldsV1) Equal(f2 FieldsV1) bool { + return bytes.Equal(f.Raw, f2.Raw) +} + +func (f *FieldsV1) GetRawReader() FieldsV1Reader { + if f == nil || len(f.Raw) == 0 { + return bytes.NewReader(nil) + } + return bytes.NewReader(f.Raw) +} + +// GetRawBytes returns the raw bytes. +// These may or may not be a copy of the underlying bytes. +// If mutating the underlying bytes is desired, the returned bytes may be mutated and then passed to SetRawBytes(). +// If mutating the underlying bytes is not desired, make a copy of the returned bytes. +func (f *FieldsV1) GetRawBytes() []byte { + if f == nil { + return nil + } + return f.Raw +} + +// GetRawString returns the raw data as a string. +func (f *FieldsV1) GetRawString() string { + if f == nil { + return "" + } + return string(f.Raw) +} + +// SetRawBytes sets the raw bytes. It does not retain the passed-in byte slice. +func (f *FieldsV1) SetRawBytes(b []byte) { + if f != nil { + f.Raw = bytes.Clone(b) + } +} + +// SetRawString sets the raw data from a string. +func (f *FieldsV1) SetRawString(s string) { + if f != nil { + f.Raw = []byte(s) + } +} + +func NewFieldsV1(raw string) *FieldsV1 { + return &FieldsV1{Raw: []byte(raw)} +} + +func (f *FieldsV1) DeepCopyInto(out *FieldsV1) { + *out = *f + if f.Raw != nil { + in, out := &f.Raw, &out.Raw + *out = make([]byte, len(*in)) + copy(*out, *in) + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_string.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_string.go new file mode 100644 index 000000000..679452ae1 --- /dev/null +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/fieldsv1_string.go @@ -0,0 +1,113 @@ +//go:build fieldsv1string + +/* +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 ( + "strings" + "unique" +) + +// FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format. +// +// Each key is either a '.' representing the field itself, and will always map to an empty set, +// or a string representing a sub-field or item. The string will follow one of these four formats: +// 'f:', where is the name of a field in a struct, or key in a map +// 'v:', where is the exact json formatted value of a list item +// 'i:', where is position of a item in a list +// 'k:', where is a map of a list item's key fields to their unique values +// If a key maps to an empty Fields value, the field that key represents is part of the set. +// +// The exact format is defined in sigs.k8s.io/structured-merge-diff +// +k8s:deepcopy-gen=false +// +protobuf.options.marshal=false +// +protobuf.options.(gogoproto.goproto_stringer)=false +type FieldsV1 struct { + // The zero value of a unique.Handle[string] has an uninitialized underlying pointer. + // Calling .Value() on it panics. We must explicitly check for this uninitialized + // state (f.handle == unique.Handle[string]{}) across accessors to safely support + // uninitialized metav1.FieldsV1{} objects. + // See ongoing golang discussion related to this here: https://github.com/golang/go/issues/73344 + handle unique.Handle[string] +} + +func (f FieldsV1) String() string { + if f.handle == (unique.Handle[string]{}) { + return "" + } + return f.handle.Value() +} + +func (f FieldsV1) Equal(f2 FieldsV1) bool { + if f.handle == f2.handle { + return true + } + // An uninitialized FieldsV1 compared to an explicitly empty + // FieldsV1 (unique.Make("") will fail the handle check above. + // Evaluate string contents directly as well to maintain parity with legacy + // bytes.Equal(nil, []byte{}) == true behavior. + return f.GetRawString() == f2.GetRawString() +} + +func (f *FieldsV1) GetRawReader() FieldsV1Reader { + if f == nil || f.handle == (unique.Handle[string]{}) { + return strings.NewReader("") + } + return strings.NewReader(f.handle.Value()) +} + +// GetRawBytes returns the raw bytes. +// These may or may not be a copy of the underlying bytes. +// If mutating the underlying bytes is desired, the returned bytes may be mutated and then passed to SetRawBytes(). +// If mutating the underlying bytes is not desired, make a copy of the returned bytes. +func (f *FieldsV1) GetRawBytes() []byte { + if f == nil || f.handle == (unique.Handle[string]{}) { + return nil + } + return []byte(f.handle.Value()) +} + +// GetRawString returns the raw data as a string. +func (f *FieldsV1) GetRawString() string { + if f == nil || f.handle == (unique.Handle[string]{}) { + return "" + } + return f.handle.Value() +} + +// SetRawBytes sets the raw bytes. It does not retain the passed-in byte slice. +func (f *FieldsV1) SetRawBytes(b []byte) { + if f != nil { + f.handle = unique.Make(string(b)) + } +} + +// SetRawString sets the raw data from a string. +func (f *FieldsV1) SetRawString(s string) { + if f != nil { + f.handle = unique.Make(s) + } +} + +func NewFieldsV1(raw string) *FieldsV1 { + return &FieldsV1{handle: unique.Make(raw)} +} + +func (f *FieldsV1) DeepCopyInto(out *FieldsV1) { + *out = *f +} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.pb.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.pb.go index f6b1a6a4e..293b0223a 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.pb.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.pb.go @@ -105,6 +105,8 @@ func (m *RootPaths) Reset() { *m = RootPaths{} } func (m *ServerAddressByClientCIDR) Reset() { *m = ServerAddressByClientCIDR{} } +func (m *ShardInfo) Reset() { *m = ShardInfo{} } + func (m *Status) Reset() { *m = Status{} } func (m *StatusCause) Reset() { *m = StatusCause{} } @@ -694,36 +696,6 @@ func (m *FieldSelectorRequirement) MarshalToSizedBuffer(dAtA []byte) (int, error return len(dAtA) - i, nil } -func (m *FieldsV1) 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 *FieldsV1) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *FieldsV1) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Raw != nil { - i -= len(m.Raw) - copy(dAtA[i:], m.Raw) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Raw))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - func (m *GetOptions) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1130,6 +1102,18 @@ func (m *ListMeta) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.ShardInfo != nil { + { + size, err := m.ShardInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenerated(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } if m.RemainingItemCount != nil { i = encodeVarintGenerated(dAtA, i, uint64(*m.RemainingItemCount)) i-- @@ -1173,6 +1157,11 @@ func (m *ListOptions) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + i -= len(m.ShardSelector) + copy(dAtA[i:], m.ShardSelector) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.ShardSelector))) + i-- + dAtA[i] = 0x7a if m.SendInitialEvents != nil { i-- if *m.SendInitialEvents { @@ -1797,6 +1786,34 @@ func (m *ServerAddressByClientCIDR) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } +func (m *ShardInfo) 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 *ShardInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ShardInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + i -= len(m.Selector) + copy(dAtA[i:], m.Selector) + i = encodeVarintGenerated(dAtA, i, uint64(len(m.Selector))) + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *Status) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2405,19 +2422,6 @@ func (m *FieldSelectorRequirement) Size() (n int) { return n } -func (m *FieldsV1) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Raw != nil { - l = len(m.Raw) - n += 1 + l + sovGenerated(uint64(l)) - } - return n -} - func (m *GetOptions) Size() (n int) { if m == nil { return 0 @@ -2585,6 +2589,10 @@ func (m *ListMeta) Size() (n int) { if m.RemainingItemCount != nil { n += 1 + sovGenerated(uint64(*m.RemainingItemCount)) } + if m.ShardInfo != nil { + l = m.ShardInfo.Size() + n += 1 + l + sovGenerated(uint64(l)) + } return n } @@ -2613,6 +2621,8 @@ func (m *ListOptions) Size() (n int) { if m.SendInitialEvents != nil { n += 2 } + l = len(m.ShardSelector) + n += 1 + l + sovGenerated(uint64(l)) return n } @@ -2835,6 +2845,17 @@ func (m *ServerAddressByClientCIDR) Size() (n int) { return n } +func (m *ShardInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Selector) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *Status) Size() (n int) { if m == nil { return 0 @@ -3217,6 +3238,7 @@ func (this *ListMeta) String() string { `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, `Continue:` + fmt.Sprintf("%v", this.Continue) + `,`, `RemainingItemCount:` + valueToStringGenerated(this.RemainingItemCount) + `,`, + `ShardInfo:` + strings.Replace(this.ShardInfo.String(), "ShardInfo", "ShardInfo", 1) + `,`, `}`, }, "") return s @@ -3236,6 +3258,7 @@ func (this *ListOptions) String() string { `AllowWatchBookmarks:` + fmt.Sprintf("%v", this.AllowWatchBookmarks) + `,`, `ResourceVersionMatch:` + fmt.Sprintf("%v", this.ResourceVersionMatch) + `,`, `SendInitialEvents:` + valueToStringGenerated(this.SendInitialEvents) + `,`, + `ShardSelector:` + fmt.Sprintf("%v", this.ShardSelector) + `,`, `}`, }, "") return s @@ -3405,6 +3428,16 @@ func (this *ServerAddressByClientCIDR) String() string { }, "") return s } +func (this *ShardInfo) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ShardInfo{`, + `Selector:` + fmt.Sprintf("%v", this.Selector) + `,`, + `}`, + }, "") + return s +} func (this *Status) String() string { if this == nil { return "nil" @@ -5314,90 +5347,6 @@ func (m *FieldSelectorRequirement) Unmarshal(dAtA []byte) error { } return nil } -func (m *FieldsV1) 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: FieldsV1: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: FieldsV1: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Raw", 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.Raw = append(m.Raw[:0], dAtA[iNdEx:postIndex]...) - if m.Raw == nil { - m.Raw = []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 *GetOptions) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -6847,6 +6796,42 @@ func (m *ListMeta) Unmarshal(dAtA []byte) error { } } m.RemainingItemCount = &v + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShardInfo", 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.ShardInfo == nil { + m.ShardInfo = &ShardInfo{} + } + if err := m.ShardInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -7157,6 +7142,38 @@ func (m *ListOptions) Unmarshal(dAtA []byte) error { } b := bool(v != 0) m.SendInitialEvents = &b + case 15: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShardSelector", 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.ShardSelector = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) @@ -9113,6 +9130,88 @@ func (m *ServerAddressByClientCIDR) Unmarshal(dAtA []byte) error { } return nil } +func (m *ShardInfo) 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: ShardInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ShardInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Selector", 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.Selector = 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 *Status) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto index fb21b7236..d03a73314 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto @@ -369,9 +369,13 @@ message FieldSelectorRequirement { // If a key maps to an empty Fields value, the field that key represents is part of the set. // // The exact format is defined in sigs.k8s.io/structured-merge-diff +// +k8s:deepcopy-gen=false +// +protobuf.options.marshal=false // +protobuf.options.(gogoproto.goproto_stringer)=false message FieldsV1 { // Raw is the underlying serialization of this object. + // + // Deprecated: Direct access to this field is deprecated. Use GetRawBytes, GetRawString, SetRawBytes, SetRawString, GetRawReader, NewFieldsV1 instead. optional bytes Raw = 1; } @@ -533,6 +537,17 @@ message ListMeta { // should not rely on the remainingItemCount to be set or to be exact. // +optional optional int64 remainingItemCount = 4; + + // shardInfo is set when the list is a filtered subset of the full collection, + // as selected by a shard selector on the request. It echoes back the selector + // so clients can verify which shard they received and merge sharded responses. + // Clients should not cache sharded list responses as a full representation + // of the collection. + // + // This is an alpha field and requires enabling the ShardedListAndWatch feature gate. + // +featureGate=ShardedListAndWatch + // +optional + optional ShardInfo shardInfo = 5; } // ListOptions is the query options to a standard REST list call. @@ -643,6 +658,38 @@ message ListOptions { // compatibility reasons) and to false otherwise. // +optional optional bool sendInitialEvents = 11; + + // shardSelector restricts the list of returned objects using a CEL-based + // shard selector expression. The format uses the shardRange() function + // combined with || (logical OR) to specify one or more hash ranges: + // + // shardRange(object.metadata.uid, '0x0', '0x8000000000000000') + // shardRange(object.metadata.uid, '0x0', '0x8000000000000000') || shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000') + // + // Field paths use CEL-style object-rooted syntax (e.g. "object.metadata.uid"), + // NOT the fieldSelector format ("metadata.uid"). Currently supported paths: + // - object.metadata.uid + // - object.metadata.namespace + // + // hexStart and hexEnd are single-quoted CEL string literals with a '0x' prefix, + // defining the inclusive lower and exclusive upper bounds over the 64-bit FNV-1a + // hash space. The full range is [0x0, 0x10000000000000000), where the exclusive + // upper bound equals 2^64. + // + // Examples: + // 2-shard split: + // shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x8000000000000000') + // shard 1: shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000') + // 4-shard split: + // shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x4000000000000000') + // shard 1: shardRange(object.metadata.uid, '0x4000000000000000', '0x8000000000000000') + // shard 2: shardRange(object.metadata.uid, '0x8000000000000000', '0xc000000000000000') + // shard 3: shardRange(object.metadata.uid, '0xc000000000000000', '0x10000000000000000') + // + // This is an alpha field and requires enabling the ShardedListAndWatch feature gate. + // +featureGate=ShardedListAndWatch + // +optional + optional string shardSelector = 15; } // ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource @@ -1009,6 +1056,15 @@ message ServerAddressByClientCIDR { optional string serverAddress = 2; } +// ShardInfo describes the shard selector that was applied to produce a list response. +// Its presence on a list response indicates the list is a filtered subset. +message ShardInfo { + // selector is the shard selector string from the request, echoed back so clients + // can verify which shard they received and merge responses from multiple shards. + // +required + optional string selector = 1; +} + // Status is a return value for calls that don't return other objects. message Status { // Standard list metadata. diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.protomessage.pb.go deleted file mode 100644 index 459ae1ad8..000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.protomessage.pb.go +++ /dev/null @@ -1,112 +0,0 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - -/* -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 go-to-protobuf. DO NOT EDIT. - -package v1 - -func (*APIGroup) ProtoMessage() {} - -func (*APIGroupList) ProtoMessage() {} - -func (*APIResource) ProtoMessage() {} - -func (*APIResourceList) ProtoMessage() {} - -func (*APIVersions) ProtoMessage() {} - -func (*ApplyOptions) ProtoMessage() {} - -func (*Condition) ProtoMessage() {} - -func (*CreateOptions) ProtoMessage() {} - -func (*DeleteOptions) ProtoMessage() {} - -func (*Duration) ProtoMessage() {} - -func (*FieldSelectorRequirement) ProtoMessage() {} - -func (*FieldsV1) ProtoMessage() {} - -func (*GetOptions) ProtoMessage() {} - -func (*GroupKind) ProtoMessage() {} - -func (*GroupResource) ProtoMessage() {} - -func (*GroupVersion) ProtoMessage() {} - -func (*GroupVersionForDiscovery) ProtoMessage() {} - -func (*GroupVersionKind) ProtoMessage() {} - -func (*GroupVersionResource) ProtoMessage() {} - -func (*LabelSelector) ProtoMessage() {} - -func (*LabelSelectorRequirement) ProtoMessage() {} - -func (*List) ProtoMessage() {} - -func (*ListMeta) ProtoMessage() {} - -func (*ListOptions) ProtoMessage() {} - -func (*ManagedFieldsEntry) ProtoMessage() {} - -func (*MicroTime) ProtoMessage() {} - -func (*ObjectMeta) ProtoMessage() {} - -func (*OwnerReference) ProtoMessage() {} - -func (*PartialObjectMetadata) ProtoMessage() {} - -func (*PartialObjectMetadataList) ProtoMessage() {} - -func (*Patch) ProtoMessage() {} - -func (*PatchOptions) ProtoMessage() {} - -func (*Preconditions) ProtoMessage() {} - -func (*RootPaths) ProtoMessage() {} - -func (*ServerAddressByClientCIDR) ProtoMessage() {} - -func (*Status) ProtoMessage() {} - -func (*StatusCause) ProtoMessage() {} - -func (*StatusDetails) ProtoMessage() {} - -func (*TableOptions) ProtoMessage() {} - -func (*Time) ProtoMessage() {} - -func (*Timestamp) ProtoMessage() {} - -func (*TypeMeta) ProtoMessage() {} - -func (*UpdateOptions) ProtoMessage() {} - -func (*Verbs) ProtoMessage() {} - -func (*WatchEvent) ProtoMessage() {} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go index c748071ed..45ed1e989 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go @@ -279,17 +279,18 @@ func ResetObjectMetaForStatus(meta, existingMeta Object) { // MarshalJSON may get called on pointers or values, so implement MarshalJSON on value. // http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go func (f FieldsV1) MarshalJSON() ([]byte, error) { - if f.Raw == nil { + raw := f.GetRawBytes() + if len(raw) == 0 { return []byte("null"), nil } if f.getContentType() == fieldsV1InvalidOrValidCBORObject { var u map[string]interface{} - if err := cbor.Unmarshal(f.Raw, &u); err != nil { + if err := cbor.Unmarshal(raw, &u); err != nil { return nil, fmt.Errorf("metav1.FieldsV1 cbor invalid: %w", err) } return utiljson.Marshal(u) } - return f.Raw, nil + return raw, nil } // UnmarshalJSON implements json.Unmarshaler @@ -298,7 +299,7 @@ func (f *FieldsV1) UnmarshalJSON(b []byte) error { return errors.New("metav1.FieldsV1: UnmarshalJSON on nil pointer") } if !bytes.Equal(b, []byte("null")) { - f.Raw = append(f.Raw[0:0], b...) + f.SetRawBytes(b) } return nil } @@ -307,17 +308,18 @@ var _ json.Marshaler = FieldsV1{} var _ json.Unmarshaler = &FieldsV1{} func (f FieldsV1) MarshalCBOR() ([]byte, error) { - if f.Raw == nil { + raw := f.GetRawBytes() + if len(raw) == 0 { return cbor.Marshal(nil) } if f.getContentType() == fieldsV1InvalidOrValidJSONObject { var u map[string]interface{} - if err := utiljson.Unmarshal(f.Raw, &u); err != nil { + if err := utiljson.Unmarshal(raw, &u); err != nil { return nil, fmt.Errorf("metav1.FieldsV1 json invalid: %w", err) } return cbor.Marshal(u) } - return f.Raw, nil + return raw, nil } var cborNull = []byte{0xf6} @@ -327,7 +329,7 @@ func (f *FieldsV1) UnmarshalCBOR(b []byte) error { return errors.New("metav1.FieldsV1: UnmarshalCBOR on nil pointer") } if !bytes.Equal(b, cborNull) { - f.Raw = append(f.Raw[0:0], b...) + f.SetRawBytes(b) } return nil } @@ -362,8 +364,13 @@ const ( // or, if a tag-enclosed map, an initial byte with major type "tag" (0xf6, 0xa0...0xbf, or // 0xc6...0xdb). The two sets of valid initial bytes don't intersect. func (f FieldsV1) getContentType() int { - if len(f.Raw) > 0 { - p := f.Raw[0] + reader := f.GetRawReader() + if reader.Size() > 0 { + var buf [1]byte + if _, err := reader.Read(buf[:]); err != nil { + return fieldsV1InvalidOrEmpty + } + p := buf[0] switch p { case 'n', '{', '\t', '\r', '\n', ' ': return fieldsV1InvalidOrValidJSONObject diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go index 92d3ed5e0..6ae1b095f 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go @@ -94,6 +94,13 @@ type ListInterface interface { SetRemainingItemCount(c *int64) } +// ShardedListInterface can be implemented by list types to indicate that they +// represent a sharded subset of the full collection rather than the complete list. +type ShardedListInterface interface { + GetShardInfo() *ShardInfo + SetShardInfo(*ShardInfo) +} + // Type exposes the type and APIVersion of versioned or internal API objects. // TODO: move this, and TypeMeta and ListMeta, to a different package type Type interface { @@ -113,6 +120,8 @@ func (meta *ListMeta) GetContinue() string { return meta.Continue func (meta *ListMeta) SetContinue(c string) { meta.Continue = c } func (meta *ListMeta) GetRemainingItemCount() *int64 { return meta.RemainingItemCount } func (meta *ListMeta) SetRemainingItemCount(c *int64) { meta.RemainingItemCount = c } +func (meta *ListMeta) GetShardInfo() *ShardInfo { return meta.ShardInfo } +func (meta *ListMeta) SetShardInfo(s *ShardInfo) { meta.ShardInfo = s } func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj } diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go index a5f437b4b..338ea9be7 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go @@ -1,5 +1,4 @@ //go:build !notest -// +build !notest /* Copyright 2020 The Kubernetes Authors. diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go index 48fb97845..14ec5f058 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go @@ -1,5 +1,4 @@ //go:build !notest -// +build !notest /* Copyright 2020 The Kubernetes Authors. diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go index 9970e877d..c8b87f20c 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go @@ -92,6 +92,26 @@ type ListMeta struct { // should not rely on the remainingItemCount to be set or to be exact. // +optional RemainingItemCount *int64 `json:"remainingItemCount,omitempty" protobuf:"bytes,4,opt,name=remainingItemCount"` + + // shardInfo is set when the list is a filtered subset of the full collection, + // as selected by a shard selector on the request. It echoes back the selector + // so clients can verify which shard they received and merge sharded responses. + // Clients should not cache sharded list responses as a full representation + // of the collection. + // + // This is an alpha field and requires enabling the ShardedListAndWatch feature gate. + // +featureGate=ShardedListAndWatch + // +optional + ShardInfo *ShardInfo `json:"shardInfo,omitempty" protobuf:"bytes,5,opt,name=shardInfo"` +} + +// ShardInfo describes the shard selector that was applied to produce a list response. +// Its presence on a list response indicates the list is a filtered subset. +type ShardInfo struct { + // selector is the shard selector string from the request, echoed back so clients + // can verify which shard they received and merge responses from multiple shards. + // +required + Selector string `json:"selector" protobuf:"bytes,1,opt,name=selector"` } // Field path constants that are specific to the internal API @@ -430,6 +450,38 @@ type ListOptions struct { // compatibility reasons) and to false otherwise. // +optional SendInitialEvents *bool `json:"sendInitialEvents,omitempty" protobuf:"varint,11,opt,name=sendInitialEvents"` + + // shardSelector restricts the list of returned objects using a CEL-based + // shard selector expression. The format uses the shardRange() function + // combined with || (logical OR) to specify one or more hash ranges: + // + // shardRange(object.metadata.uid, '0x0', '0x8000000000000000') + // shardRange(object.metadata.uid, '0x0', '0x8000000000000000') || shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000') + // + // Field paths use CEL-style object-rooted syntax (e.g. "object.metadata.uid"), + // NOT the fieldSelector format ("metadata.uid"). Currently supported paths: + // - object.metadata.uid + // - object.metadata.namespace + // + // hexStart and hexEnd are single-quoted CEL string literals with a '0x' prefix, + // defining the inclusive lower and exclusive upper bounds over the 64-bit FNV-1a + // hash space. The full range is [0x0, 0x10000000000000000), where the exclusive + // upper bound equals 2^64. + // + // Examples: + // 2-shard split: + // shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x8000000000000000') + // shard 1: shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000') + // 4-shard split: + // shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x4000000000000000') + // shard 1: shardRange(object.metadata.uid, '0x4000000000000000', '0x8000000000000000') + // shard 2: shardRange(object.metadata.uid, '0x8000000000000000', '0xc000000000000000') + // shard 3: shardRange(object.metadata.uid, '0xc000000000000000', '0x10000000000000000') + // + // This is an alpha field and requires enabling the ShardedListAndWatch feature gate. + // +featureGate=ShardedListAndWatch + // +optional + ShardSelector string `json:"shardSelector,omitempty" protobuf:"bytes,15,opt,name=shardSelector"` } const ( @@ -1384,27 +1436,6 @@ const ( ManagedFieldsOperationUpdate ManagedFieldsOperationType = "Update" ) -// FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format. -// -// Each key is either a '.' representing the field itself, and will always map to an empty set, -// or a string representing a sub-field or item. The string will follow one of these four formats: -// 'f:', where is the name of a field in a struct, or key in a map -// 'v:', where is the exact json formatted value of a list item -// 'i:', where is position of a item in a list -// 'k:', where is a map of a list item's key fields to their unique values -// If a key maps to an empty Fields value, the field that key represents is part of the set. -// -// The exact format is defined in sigs.k8s.io/structured-merge-diff -// +protobuf.options.(gogoproto.goproto_stringer)=false -type FieldsV1 struct { - // Raw is the underlying serialization of this object. - Raw []byte `json:"-" protobuf:"bytes,1,opt,name=Raw"` -} - -func (f FieldsV1) String() string { - return string(f.Raw) -} - // TODO: Table does not generate to protobuf because of the interface{} - fix protobuf // generation to support a meta type that can accept any valid JSON. This can be introduced // in a v1 because clients a) receive an error if they try to access proto today, and b) diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_swagger_doc_generated.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_swagger_doc_generated.go index 405496d3d..c45c00f1a 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_swagger_doc_generated.go @@ -147,14 +147,6 @@ func (FieldSelectorRequirement) SwaggerDoc() map[string]string { return map_FieldSelectorRequirement } -var map_FieldsV1 = map[string]string{ - "": "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff", -} - -func (FieldsV1) SwaggerDoc() map[string]string { - return map_FieldsV1 -} - var map_GetOptions = map[string]string{ "": "GetOptions is the standard query options to the standard REST get call.", "resourceVersion": "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.\n\nDefaults to unset", @@ -211,6 +203,7 @@ var map_ListMeta = map[string]string{ "resourceVersion": "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", "continue": "continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.", "remainingItemCount": "remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.", + "shardInfo": "shardInfo is set when the list is a filtered subset of the full collection, as selected by a shard selector on the request. It echoes back the selector so clients can verify which shard they received and merge sharded responses. Clients should not cache sharded list responses as a full representation of the collection.\n\nThis is an alpha field and requires enabling the ShardedListAndWatch feature gate.", } func (ListMeta) SwaggerDoc() map[string]string { @@ -229,6 +222,7 @@ var map_ListOptions = map[string]string{ "limit": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", "continue": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", "sendInitialEvents": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", + "shardSelector": "shardSelector restricts the list of returned objects using a CEL-based shard selector expression. The format uses the shardRange() function combined with || (logical OR) to specify one or more hash ranges:\n\n shardRange(object.metadata.uid, '0x0', '0x8000000000000000')\n shardRange(object.metadata.uid, '0x0', '0x8000000000000000') || shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000')\n\nField paths use CEL-style object-rooted syntax (e.g. \"object.metadata.uid\"), NOT the fieldSelector format (\"metadata.uid\"). Currently supported paths:\n - object.metadata.uid\n - object.metadata.namespace\n\nhexStart and hexEnd are single-quoted CEL string literals with a '0x' prefix, defining the inclusive lower and exclusive upper bounds over the 64-bit FNV-1a hash space. The full range is [0x0, 0x10000000000000000), where the exclusive upper bound equals 2^64.\n\nExamples:\n 2-shard split:\n shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x8000000000000000')\n shard 1: shardRange(object.metadata.uid, '0x8000000000000000', '0x10000000000000000')\n 4-shard split:\n shard 0: shardRange(object.metadata.uid, '0x0000000000000000', '0x4000000000000000')\n shard 1: shardRange(object.metadata.uid, '0x4000000000000000', '0x8000000000000000')\n shard 2: shardRange(object.metadata.uid, '0x8000000000000000', '0xc000000000000000')\n shard 3: shardRange(object.metadata.uid, '0xc000000000000000', '0x10000000000000000')\n\nThis is an alpha field and requires enabling the ShardedListAndWatch feature gate.", } func (ListOptions) SwaggerDoc() map[string]string { @@ -355,6 +349,15 @@ func (ServerAddressByClientCIDR) SwaggerDoc() map[string]string { return map_ServerAddressByClientCIDR } +var map_ShardInfo = map[string]string{ + "": "ShardInfo describes the shard selector that was applied to produce a list response. Its presence on a list response indicates the list is a filtered subset.", + "selector": "selector is the shard selector string from the request, echoed back so clients can verify which shard they received and merge responses from multiple shards.", +} + +func (ShardInfo) SwaggerDoc() map[string]string { + return map_ShardInfo +} + var map_Status = map[string]string{ "": "Status is a return value for calls that don't return other objects.", "metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.conversion.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.conversion.go index 82e272240..735cbcb08 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.conversion.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.conversion.go @@ -440,6 +440,13 @@ func autoConvert_url_Values_To_v1_ListOptions(in *url.Values, out *ListOptions, } else { out.SendInitialEvents = nil } + if values, ok := map[string][]string(*in)["shardSelector"]; ok && len(values) > 0 { + if err := runtime.Convert_Slice_string_To_string(&values, &out.ShardSelector, s); err != nil { + return err + } + } else { + out.ShardSelector = "" + } return nil } diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.deepcopy.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.deepcopy.go index 6b0d0dfee..eb7eb80d9 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.deepcopy.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.deepcopy.go @@ -353,27 +353,6 @@ func (in *FieldSelectorRequirement) DeepCopy() *FieldSelectorRequirement { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FieldsV1) DeepCopyInto(out *FieldsV1) { - *out = *in - if in.Raw != nil { - in, out := &in.Raw, &out.Raw - *out = make([]byte, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FieldsV1. -func (in *FieldsV1) DeepCopy() *FieldsV1 { - if in == nil { - return nil - } - out := new(FieldsV1) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GetOptions) DeepCopyInto(out *GetOptions) { *out = *in @@ -606,6 +585,11 @@ func (in *ListMeta) DeepCopyInto(out *ListMeta) { *out = new(int64) **out = **in } + if in.ShardInfo != nil { + in, out := &in.ShardInfo, &out.ShardInfo + *out = new(ShardInfo) + **out = **in + } return } @@ -663,8 +647,7 @@ func (in *ManagedFieldsEntry) DeepCopyInto(out *ManagedFieldsEntry) { } if in.FieldsV1 != nil { in, out := &in.FieldsV1, &out.FieldsV1 - *out = new(FieldsV1) - (*in).DeepCopyInto(*out) + *out = (*in).DeepCopy() } return } @@ -947,6 +930,22 @@ func (in *ServerAddressByClientCIDR) DeepCopy() *ServerAddressByClientCIDR { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ShardInfo) DeepCopyInto(out *ShardInfo) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ShardInfo. +func (in *ShardInfo) DeepCopy() *ShardInfo { + if in == nil { + return nil + } + out := new(ShardInfo) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Status) DeepCopyInto(out *Status) { *out = *in diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.model_name.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.model_name.go index fd6e876ec..3df687707 100644 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.model_name.go +++ b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.model_name.go @@ -201,6 +201,11 @@ func (in ServerAddressByClientCIDR) OpenAPIModelName() string { return "io.k8s.apimachinery.pkg.apis.meta.v1.ServerAddressByClientCIDR" } +// OpenAPIModelName returns the OpenAPI model name for this type. +func (in ShardInfo) OpenAPIModelName() string { + return "io.k8s.apimachinery.pkg.apis.meta.v1.ShardInfo" +} + // OpenAPIModelName returns the OpenAPI model name for this type. func (in Status) OpenAPIModelName() string { return "io.k8s.apimachinery.pkg.apis.meta.v1.Status" diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.protomessage.pb.go deleted file mode 100644 index a782b1d8f..000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.protomessage.pb.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - -/* -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 go-to-protobuf. DO NOT EDIT. - -package v1beta1 - -func (*PartialObjectMetadataList) ProtoMessage() {} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/runtime/generated.protomessage.pb.go deleted file mode 100644 index 1716853ff..000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/generated.protomessage.pb.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - -/* -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 go-to-protobuf. DO NOT EDIT. - -package runtime - -func (*RawExtension) ProtoMessage() {} - -func (*TypeMeta) ProtoMessage() {} - -func (*Unknown) ProtoMessage() {} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.protomessage.pb.go deleted file mode 100644 index 047437377..000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.protomessage.pb.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - -/* -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 go-to-protobuf. DO NOT EDIT. - -package schema diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/decode.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/decode.go index 0210132ff..4a7055c10 100644 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/decode.go +++ b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/decode.go @@ -58,12 +58,18 @@ var decode cbor.DecMode = func() cbor.DecMode { // with or without tagging. If a tag number is present, it must be valid. TimeTag: cbor.DecTagOptional, - // Observed depth up to 16 in fuzzed batch/v1 CronJobList. JSON implementation limit - // is 10000. - MaxNestedLevels: 64, - - MaxArrayElements: 1024, - MaxMapPairs: 1024, + // MaxNestedLevels is set to the same value used in the JSON implementation. + MaxNestedLevels: 10000, + + // MaxArrayElements is set to the maximum allowed by the cbor library. We rely on + // the library initial wellformedness scan and on the api max request limit to + // prevent preallocating very large slices during decoding. + MaxArrayElements: 2147483647, + + // MaxMapPairs specifies the maximum number of key-value pairs allowed in a map. + // We selected this value as it is large enough so that in practice the API server + // decoder will always hit the request body limit before the limit here is reached. + MaxMapPairs: 2097152, // Indefinite-length sequences aren't produced by this serializer, but other // implementations can. diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/raw.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/raw.go index 09d1340f9..6d4f283ca 100644 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/raw.go +++ b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/raw.go @@ -50,7 +50,7 @@ var rawTypeTranscodeFuncs = map[reflect.Type]func(reflect.Value) error{ return nil } fields := rv.Addr().Interface().(*metav1.FieldsV1) - if fields.Raw == nil { + if fields.GetRawReader().Size() == 0 { // When Raw is nil it encodes to null. Don't change nil Raw values during // transcoding, they would have unmarshalled from JSON as nil too. return nil @@ -59,7 +59,7 @@ var rawTypeTranscodeFuncs = map[reflect.Type]func(reflect.Value) error{ if err != nil { return fmt.Errorf("failed to transcode FieldsV1 to JSON: %w", err) } - fields.Raw = j + fields.SetRawBytes(j) return nil }, } diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/cmp.go b/vendor/k8s.io/apimachinery/pkg/util/diff/cmp.go deleted file mode 100644 index 0a8100d06..000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/diff/cmp.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build usegocmp -// +build usegocmp - -/* -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 diff - -import ( - "github.com/google/go-cmp/cmp" //nolint:depguard -) - -// Diff returns a string representation of the difference between two objects. -// When built with the usegocmp tag, it uses go-cmp/cmp to generate a diff -// between the objects. -func Diff(a, b any) string { - return cmp.Diff(a, b) -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go b/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go index aed04524b..7bfa6088b 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go +++ b/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go @@ -1,6 +1,3 @@ -//go:build !usegocmp -// +build !usegocmp - /* Copyright 2025 The Kubernetes Authors. @@ -25,7 +22,7 @@ import ( "github.com/pmezard/go-difflib/difflib" - "k8s.io/apimachinery/pkg/util/dump" + "k8s.io/utils/dump" ) // Diff returns a string representation of the difference between two objects. diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/legacy_diff.go b/vendor/k8s.io/apimachinery/pkg/util/diff/legacy_diff.go index 4d32d36ad..9f0dc2f6a 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/diff/legacy_diff.go +++ b/vendor/k8s.io/apimachinery/pkg/util/diff/legacy_diff.go @@ -22,7 +22,7 @@ import ( "strings" "text/tabwriter" - "k8s.io/apimachinery/pkg/util/dump" + "k8s.io/utils/dump" ) // ObjectGoPrintSideBySide prints a and b as textual dumps side by side, diff --git a/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go b/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go index cf61ef76a..5cf55473c 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go +++ b/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go @@ -17,38 +17,26 @@ limitations under the License. package dump import ( - "github.com/davecgh/go-spew/spew" + "k8s.io/utils/dump" ) -var prettyPrintConfig = &spew.ConfigState{ - Indent: " ", - DisableMethods: true, - DisablePointerAddresses: true, - DisableCapacities: true, -} - -// The config MUST NOT be changed because that could change the result of a hash operation -var prettyPrintConfigForHash = &spew.ConfigState{ - Indent: " ", - SortKeys: true, - DisableMethods: true, - SpewKeys: true, - DisablePointerAddresses: true, - DisableCapacities: true, -} - -// Pretty wrap the spew.Sdump with Indent, and disabled methods like error() and String() -// The output may change over time, so for guaranteed output please take more direct control +// Deprecated: Use k8s.io/utils/dump.Pretty instead. +// +//go:fix inline func Pretty(a interface{}) string { - return prettyPrintConfig.Sdump(a) + return dump.Pretty(a) } -// ForHash keeps the original Spew.Sprintf format to ensure the same checksum +// Deprecated: Use k8s.io/utils/dump.ForHash instead. +// +//go:fix inline func ForHash(a interface{}) string { - return prettyPrintConfigForHash.Sprintf("%#v", a) + return dump.ForHash(a) } -// OneLine outputs the object in one line +// Deprecated: Use k8s.io/utils/dump.OneLine instead. +// +//go:fix inline func OneLine(a interface{}) string { - return prettyPrintConfig.Sprintf("%#v", a) + return dump.OneLine(a) } diff --git a/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.protomessage.pb.go b/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.protomessage.pb.go deleted file mode 100644 index 2853a0183..000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.protomessage.pb.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build kubernetes_protomessage_one_more_release -// +build kubernetes_protomessage_one_more_release - -/* -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 go-to-protobuf. DO NOT EDIT. - -package intstr - -func (*IntOrString) ProtoMessage() {} diff --git a/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go b/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go index 2d6f6a0cc..494325c1f 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go +++ b/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go @@ -1,5 +1,4 @@ //go:build !notest -// +build !notest /* Copyright 2020 The Kubernetes Authors. diff --git a/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go b/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go index aef858b26..ff7dda1a5 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go +++ b/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go @@ -17,7 +17,6 @@ limitations under the License. package managedfields import ( - "bytes" "fmt" "sigs.k8s.io/structured-merge-diff/v6/fieldpath" @@ -65,7 +64,7 @@ func ExtractInto(object runtime.Object, objectType typed.ParseableType, fieldMan return nil } fieldset := &fieldpath.Set{} - err = fieldset.FromJSON(bytes.NewReader(fieldsEntry.FieldsV1.Raw)) + err = fieldset.FromJSON(fieldsEntry.FieldsV1.GetRawReader()) if err != nil { return fmt.Errorf("error marshalling FieldsV1 to JSON: %w", err) } diff --git a/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go b/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go index 5c47b9c54..549412b41 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go +++ b/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go @@ -17,8 +17,6 @@ limitations under the License. package internal import ( - "bytes" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/structured-merge-diff/v6/fieldpath" @@ -36,12 +34,13 @@ var EmptyFields = func() metav1.FieldsV1 { // FieldsToSet creates a set paths from an input trie of fields func FieldsToSet(f metav1.FieldsV1) (s fieldpath.Set, err error) { - err = s.FromJSON(bytes.NewReader(f.Raw)) + err = s.FromJSON(f.GetRawReader()) return s, err } // SetToFields creates a trie of fields from an input set of paths func SetToFields(s fieldpath.Set) (f metav1.FieldsV1, err error) { - f.Raw, err = s.ToJSON() + raw, err := s.ToJSON() + f.SetRawBytes(raw) return f, err } diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go index 25626cf3a..46e3bb75d 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go +++ b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go @@ -20,7 +20,7 @@ import ( "fmt" "reflect" - "k8s.io/apimachinery/pkg/util/dump" + "k8s.io/utils/dump" "sigs.k8s.io/yaml" ) diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/http.go b/vendor/k8s.io/apimachinery/pkg/util/net/http.go index 8cc1810af..8912804c5 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/net/http.go +++ b/vendor/k8s.io/apimachinery/pkg/util/net/http.go @@ -132,9 +132,11 @@ func SetTransportDefaults(t *http.Transport) *http.Transport { t = SetOldTransportDefaults(t) // Allow clients to disable http2 if needed. if s := os.Getenv("DISABLE_HTTP2"); len(s) > 0 { + //nolint:logcheck // Should be rare, not worth converting. klog.Info("HTTP2 has been explicitly disabled") } else if allowsHTTP2(t) { if err := configureHTTP2Transport(t); err != nil { + //nolint:logcheck // Should be rare, not worth converting. klog.Warningf("Transport failed http2 configuration: %v", err) } } @@ -148,6 +150,7 @@ func readIdleTimeoutSeconds() int { if s := os.Getenv("HTTP2_READ_IDLE_TIMEOUT_SECONDS"); len(s) > 0 { i, err := strconv.Atoi(s) if err != nil { + //nolint:logcheck // Should be rare, not worth converting. klog.Warningf("Illegal HTTP2_READ_IDLE_TIMEOUT_SECONDS(%q): %v."+ " Default value %d is used", s, err, ret) return ret @@ -162,6 +165,7 @@ func pingTimeoutSeconds() int { if s := os.Getenv("HTTP2_PING_TIMEOUT_SECONDS"); len(s) > 0 { i, err := strconv.Atoi(s) if err != nil { + //nolint:logcheck // Should be rare, not worth converting. klog.Warningf("Illegal HTTP2_PING_TIMEOUT_SECONDS(%q): %v."+ " Default value %d is used", s, err, ret) return ret @@ -256,6 +260,7 @@ func CloseIdleConnectionsFor(transport http.RoundTripper) { case RoundTripperWrapper: CloseIdleConnectionsFor(transport.WrappedRoundTripper()) default: + //nolint:logcheck // Should be rare, not worth converting. klog.Warningf("unknown transport type: %T", transport) } } diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/interface.go b/vendor/k8s.io/apimachinery/pkg/util/net/interface.go index 01d028e72..3ccf227af 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/net/interface.go +++ b/vendor/k8s.io/apimachinery/pkg/util/net/interface.go @@ -201,12 +201,12 @@ func parseIP(str string, family AddressFamily) (net.IP, error) { return net.IP(bytes), nil } -func isInterfaceUp(intf *net.Interface) bool { +func isInterfaceUp(logger klog.Logger, intf *net.Interface) bool { if intf == nil { return false } if intf.Flags&net.FlagUp != 0 { - klog.V(4).Infof("Interface %v is up", intf.Name) + logger.V(4).Info("Interface is up", "interface", intf.Name) return true } return false @@ -218,23 +218,23 @@ func isLoopbackOrPointToPoint(intf *net.Interface) bool { // getMatchingGlobalIP returns the first valid global unicast address of the given // 'family' from the list of 'addrs'. -func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) { +func getMatchingGlobalIP(logger klog.Logger, addrs []net.Addr, family AddressFamily) (net.IP, error) { if len(addrs) > 0 { for i := range addrs { - klog.V(4).Infof("Checking addr %s.", addrs[i].String()) + logger.V(4).Info("Checking for matching global IP", "address", addrs[i]) ip, _, err := netutils.ParseCIDRSloppy(addrs[i].String()) if err != nil { return nil, err } if memberOf(ip, family) { if ip.IsGlobalUnicast() { - klog.V(4).Infof("IP found %v", ip) + logger.V(4).Info("IP found", "IP", ip) return ip, nil } else { - klog.V(4).Infof("Non-global unicast address found %v", ip) + logger.V(4).Info("Non-global unicast address found", "IP", ip) } } else { - klog.V(4).Infof("%v is not an IPv%d address", ip, int(family)) + logger.V(4).Info("IP address has wrong version", "IP", ip, "IPVersion", int(family)) } } @@ -244,23 +244,23 @@ func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) // getIPFromInterface gets the IPs on an interface and returns a global unicast address, if any. The // interface must be up, the IP must in the family requested, and the IP must be a global unicast address. -func getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInterfacer) (net.IP, error) { +func getIPFromInterface(logger klog.Logger, intfName string, forFamily AddressFamily, nw networkInterfacer) (net.IP, error) { intf, err := nw.InterfaceByName(intfName) if err != nil { return nil, err } - if isInterfaceUp(intf) { + if isInterfaceUp(logger, intf) { addrs, err := nw.Addrs(intf) if err != nil { return nil, err } - klog.V(4).Infof("Interface %q has %d addresses :%v.", intfName, len(addrs), addrs) - matchingIP, err := getMatchingGlobalIP(addrs, forFamily) + logger.V(4).Info("Found addresses for interface", "interface", intfName, "numAddresses", len(addrs), "addresses", addrs) + matchingIP, err := getMatchingGlobalIP(logger, addrs, forFamily) if err != nil { return nil, err } if matchingIP != nil { - klog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intfName) + logger.V(4).Info("Found valid address", "IPVersion", int(forFamily), "IP", matchingIP, "interface", intfName) return matchingIP, nil } } @@ -269,13 +269,13 @@ func getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInte // getIPFromLoopbackInterface gets the IPs on a loopback interface and returns a global unicast address, if any. // The loopback interface must be up, the IP must in the family requested, and the IP must be a global unicast address. -func getIPFromLoopbackInterface(forFamily AddressFamily, nw networkInterfacer) (net.IP, error) { +func getIPFromLoopbackInterface(logger klog.Logger, forFamily AddressFamily, nw networkInterfacer) (net.IP, error) { intfs, err := nw.Interfaces() if err != nil { return nil, err } for _, intf := range intfs { - if !isInterfaceUp(&intf) { + if !isInterfaceUp(logger, &intf) { continue } if intf.Flags&(net.FlagLoopback) != 0 { @@ -283,13 +283,13 @@ func getIPFromLoopbackInterface(forFamily AddressFamily, nw networkInterfacer) ( if err != nil { return nil, err } - klog.V(4).Infof("Interface %q has %d addresses :%v.", intf.Name, len(addrs), addrs) - matchingIP, err := getMatchingGlobalIP(addrs, forFamily) + logger.V(4).Info("Found addresses for interface", "interface", intf.Name, "numAddresses", len(addrs), "addresses", addrs) + matchingIP, err := getMatchingGlobalIP(logger, addrs, forFamily) if err != nil { return nil, err } if matchingIP != nil { - klog.V(4).Infof("Found valid IPv%d address %v for interface %q.", int(forFamily), matchingIP, intf.Name) + logger.V(4).Info("Found valid address", "IPVersion", int(forFamily), "IP", matchingIP, "interface", intf.Name) return matchingIP, nil } } @@ -309,7 +309,7 @@ func memberOf(ip net.IP, family AddressFamily) bool { // chooseIPFromHostInterfaces looks at all system interfaces, trying to find one that is up that // has a global unicast address (non-loopback, non-link local, non-point2point), and returns the IP. // addressFamilies determines whether it prefers IPv4 or IPv6 -func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) { +func chooseIPFromHostInterfaces(logger klog.Logger, nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) { intfs, err := nw.Interfaces() if err != nil { return nil, err @@ -318,14 +318,14 @@ func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFam return nil, fmt.Errorf("no interfaces found on host.") } for _, family := range addressFamilies { - klog.V(4).Infof("Looking for system interface with a global IPv%d address", uint(family)) + logger.V(4).Info("Looking for system interface with a global address", "IPVersion", uint(family)) for _, intf := range intfs { - if !isInterfaceUp(&intf) { - klog.V(4).Infof("Skipping: down interface %q", intf.Name) + if !isInterfaceUp(logger, &intf) { + logger.V(4).Info("Skipping: interface is down", "interface", intf.Name) continue } if isLoopbackOrPointToPoint(&intf) { - klog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name) + logger.V(4).Info("Skipping: is LB or P2P", "interface", intf.Name) continue } addrs, err := nw.Addrs(&intf) @@ -333,7 +333,7 @@ func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFam return nil, err } if len(addrs) == 0 { - klog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name) + logger.V(4).Info("Skipping: no addresses", "interface", intf.Name) continue } for _, addr := range addrs { @@ -342,15 +342,15 @@ func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFam return nil, fmt.Errorf("unable to parse CIDR for interface %q: %s", intf.Name, err) } if !memberOf(ip, family) { - klog.V(4).Infof("Skipping: no address family match for %q on interface %q.", ip, intf.Name) + logger.V(4).Info("Skipping: no address family match", "IP", ip, "interface", intf.Name) continue } // TODO: Decide if should open up to allow IPv6 LLAs in future. if !ip.IsGlobalUnicast() { - klog.V(4).Infof("Skipping: non-global address %q on interface %q.", ip, intf.Name) + logger.V(4).Info("Skipping: non-global address", "IP", ip, "interface", intf.Name) continue } - klog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name) + logger.V(4).Info("Found global unicast address", "IP", ip, "interface", intf.Name) return ip, nil } } @@ -363,20 +363,31 @@ func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFam // interfaces. Otherwise, it will use IPv4 and IPv6 route information to return the // IP of the interface with a gateway on it (with priority given to IPv4). For a node // with no internet connection, it returns error. +// +//logcheck:context // [ChooseHostInterfaceWithLogger] should be used instead of ChooseHostInterface in code which supports contextual logging. func ChooseHostInterface() (net.IP, error) { - return chooseHostInterface(preferIPv4) + return ChooseHostInterfaceWithLogger(klog.Background()) } -func chooseHostInterface(addressFamilies AddressFamilyPreference) (net.IP, error) { +// ChooseHostInterfaceWithLogger is a method used fetch an IP for a daemon. +// If there is no routing info file, it will choose a global IP from the system +// interfaces. Otherwise, it will use IPv4 and IPv6 route information to return the +// IP of the interface with a gateway on it (with priority given to IPv4). For a node +// with no internet connection, it returns error. +func ChooseHostInterfaceWithLogger(logger klog.Logger) (net.IP, error) { + return chooseHostInterface(logger, preferIPv4) +} + +func chooseHostInterface(logger klog.Logger, addressFamilies AddressFamilyPreference) (net.IP, error) { var nw networkInterfacer = networkInterface{} if _, err := os.Stat(ipv4RouteFile); os.IsNotExist(err) { - return chooseIPFromHostInterfaces(nw, addressFamilies) + return chooseIPFromHostInterfaces(logger, nw, addressFamilies) } routes, err := getAllDefaultRoutes() if err != nil { return nil, err } - return chooseHostInterfaceFromRoute(routes, nw, addressFamilies) + return chooseHostInterfaceFromRoute(logger, routes, nw, addressFamilies) } // networkInterfacer defines an interface for several net library functions. Production @@ -427,36 +438,36 @@ func getAllDefaultRoutes() ([]Route, error) { // global IP address from the interface for the route. If there are routes but no global // address is obtained from the interfaces, it checks if the loopback interface has a global address. // addressFamilies determines whether it prefers IPv4 or IPv6 -func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) { +func chooseHostInterfaceFromRoute(logger klog.Logger, routes []Route, nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) { for _, family := range addressFamilies { - klog.V(4).Infof("Looking for default routes with IPv%d addresses", uint(family)) + logger.V(4).Info("Looking for default routes with IP addresses", "IPVersion", uint(family)) for _, route := range routes { if route.Family != family { continue } - klog.V(4).Infof("Default route transits interface %q", route.Interface) - finalIP, err := getIPFromInterface(route.Interface, family, nw) + logger.V(4).Info("Default route transits interface", "interface", route.Interface) + finalIP, err := getIPFromInterface(logger, route.Interface, family, nw) if err != nil { return nil, err } if finalIP != nil { - klog.V(4).Infof("Found active IP %v ", finalIP) + logger.V(4).Info("Found active IP", "IP", finalIP) return finalIP, nil } // In case of network setups where default routes are present, but network // interfaces use only link-local addresses (e.g. as described in RFC5549). // the global IP is assigned to the loopback interface, and we should use it - loopbackIP, err := getIPFromLoopbackInterface(family, nw) + loopbackIP, err := getIPFromLoopbackInterface(logger, family, nw) if err != nil { return nil, err } if loopbackIP != nil { - klog.V(4).Infof("Found active IP %v on Loopback interface", loopbackIP) + logger.V(4).Info("Found active IP on Loopback interface", "IP", loopbackIP) return loopbackIP, nil } } } - klog.V(4).Infof("No active IP found by looking at default routes") + logger.V(4).Info("No active IP found by looking at default routes") return nil, fmt.Errorf("unable to select an IP from default routes.") } @@ -465,14 +476,25 @@ func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer, addressF // If bindAddress is unspecified or loopback, it returns the default IP of the same // address family as bindAddress. // Otherwise, it just returns bindAddress. +// +//logcheck:context // [ResolveBindAddressWithLogger] should be used instead of ResolveBindAddress in code which supports contextual logging. func ResolveBindAddress(bindAddress net.IP) (net.IP, error) { + return ResolveBindAddressWithLogger(klog.Background(), bindAddress) +} + +// ResolveBindAddressWithLogger returns the IP address of a daemon, based on the given bindAddress: +// If bindAddress is unset, it returns the host's default IP, as with ChooseHostInterface(). +// If bindAddress is unspecified or loopback, it returns the default IP of the same +// address family as bindAddress. +// Otherwise, it just returns bindAddress. +func ResolveBindAddressWithLogger(logger klog.Logger, bindAddress net.IP) (net.IP, error) { addressFamilies := preferIPv4 if bindAddress != nil && memberOf(bindAddress, familyIPv6) { addressFamilies = preferIPv6 } if bindAddress == nil || bindAddress.IsUnspecified() || bindAddress.IsLoopback() { - hostIP, err := chooseHostInterface(addressFamilies) + hostIP, err := chooseHostInterface(logger, addressFamilies) if err != nil { return nil, err } @@ -485,10 +507,20 @@ func ResolveBindAddress(bindAddress net.IP) (net.IP, error) { // This is required in case of network setups where default routes are present, but network // interfaces use only link-local addresses (e.g. as described in RFC5549). // e.g when using BGP to announce a host IP over link-local ip addresses and this ip address is attached to the lo interface. +// +//logcheck:context // [ChooseBindAddressForInterfaceWithLogger] should be used instead of ChooseBindAddressForInterface in code which supports contextual logging. func ChooseBindAddressForInterface(intfName string) (net.IP, error) { + return ChooseBindAddressForInterfaceWithLogger(klog.Background(), intfName) +} + +// ChooseBindAddressForInterfaceWithLogger choose a global IP for a specific interface, with priority given to IPv4. +// This is required in case of network setups where default routes are present, but network +// interfaces use only link-local addresses (e.g. as described in RFC5549). +// e.g when using BGP to announce a host IP over link-local ip addresses and this ip address is attached to the lo interface. +func ChooseBindAddressForInterfaceWithLogger(logger klog.Logger, intfName string) (net.IP, error) { var nw networkInterfacer = networkInterface{} for _, family := range preferIPv4 { - ip, err := getIPFromInterface(intfName, family, nw) + ip, err := getIPFromInterface(logger, intfName, family, nw) if err != nil { return nil, err } diff --git a/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go b/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go index cc09bdbc4..38c1f7b03 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go +++ b/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go @@ -17,14 +17,17 @@ limitations under the License. package runtime import ( + "bytes" "context" "fmt" "net/http" "runtime" + "strings" "sync" "time" "k8s.io/klog/v2" + "k8s.io/klog/v2/textlogger" ) var ( @@ -55,7 +58,6 @@ func HandleCrash(additionalHandlers ...func(interface{})) { if r := recover(); r != nil { additionalHandlersWithContext := make([]func(context.Context, interface{}), len(additionalHandlers)) for i, handler := range additionalHandlers { - handler := handler // capture loop variable additionalHandlersWithContext[i] = func(_ context.Context, r interface{}) { handler(r) } @@ -155,8 +157,37 @@ var ErrorHandlers = []ErrorHandler{ backoffError(1 * time.Millisecond), } +// ErrorHandler is called indirectly through [HandleError], [HandleErrorWithContext] or [HandleErrorWithLogger]. +// It is passed the same parameters that a structured logging backend needs to log a problem. +// It follows the semantic described for [HandleErrorWithContext] and [logr.Logger.Error]: +// - err is optional and may be nil +// - msg is string that describes the problem +// - keysAndValues contains additional information that varies between different occurrences of the problem +// +// [ErrorToString] can be used to convert these parameters into a single string, using the klog text output. type ErrorHandler func(ctx context.Context, err error, msg string, keysAndValues ...interface{}) +// ErrorToString takes the parameters passed to [ErrorHandler] and +// formats them as a string using the klog text output. +// +// If any of the values is a multi-line string, then the resulting +// string also uses line breaks and indention for the sake of readability. +// Does not include a trailing newline. +// +// Use errors.New if an error instead of a string is needed. +func ErrorToString(err error, msg string, keysAndValues ...interface{}) string { + var buffer bytes.Buffer + config := textlogger.NewConfig( + textlogger.Output(&buffer), + textlogger.WithHeader(false), + ) + logger := textlogger.NewLogger(config) + logger.Error(err, msg, keysAndValues...) + result := buffer.String() + result = strings.TrimSpace(result) + return result +} + // HandlerError is a method to invoke when a non-user facing piece of code cannot // return an error and needs to indicate it has been ignored. Invoking this method // is preferable to logging the error - the default behavior is to log but the diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go index 6825a808e..71f6b5e87 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go +++ b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go @@ -1827,9 +1827,7 @@ func (ss SortableSliceOfMaps) Less(i, j int) bool { } func (ss SortableSliceOfMaps) Swap(i, j int) { - tmp := ss.s[i] - ss.s[i] = ss.s[j] - ss.s[j] = tmp + ss.s[i], ss.s[j] = ss.s[j], ss.s[i] } func deduplicateAndSortScalars(s []interface{}) []interface{} { @@ -1875,9 +1873,7 @@ func (ss SortableSliceOfScalars) Less(i, j int) bool { } func (ss SortableSliceOfScalars) Swap(i, j int) { - tmp := ss.s[i] - ss.s[i] = ss.s[j] - ss.s[j] = tmp + ss.s[i], ss.s[j] = ss.s[j], ss.s[i] } // Returns the type of the elements of N slice(s). If the type is different, diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go b/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go index f0264e50c..1eeb71ff5 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go +++ b/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go @@ -40,10 +40,12 @@ type ErrorMatcher struct { matchField bool // TODO(thockin): consider whether value could be assumed - if the // "want" error has a nil value, don't match on value. - matchValue bool - matchOrigin bool - matchDetail func(want, got string) bool - requireOriginWhenInvalid bool + matchValue bool + matchOrigin bool + matchDetail func(want, got string) bool + requireOriginWhenInvalid bool + matchValidationStabilityLevel bool + matchSource bool // normalizationRules holds the pre-compiled regex patterns for path normalization. normalizationRules []NormalizationRule } @@ -86,6 +88,14 @@ func (m ErrorMatcher) Matches(want, got *Error) bool { if m.matchDetail != nil && !m.matchDetail(want.Detail, got.Detail) { return false } + if m.matchValidationStabilityLevel && want.ValidationStabilityLevel != got.ValidationStabilityLevel { + return false + } + + if m.matchSource && want.FromImperative != got.FromImperative { + return false + } + return true } @@ -148,6 +158,14 @@ func (m ErrorMatcher) Render(e *Error) string { comma() buf.WriteString(fmt.Sprintf("Detail=%q", e.Detail)) } + if m.matchValidationStabilityLevel { + comma() + buf.WriteString(fmt.Sprintf("ValidationStabilityLevel=%s", e.ValidationStabilityLevel)) + } + if m.matchSource { + comma() + buf.WriteString(fmt.Sprintf("FromImperative=%t", e.FromImperative)) + } return "{" + buf.String() + "}" } @@ -224,6 +242,20 @@ func (m ErrorMatcher) RequireOriginWhenInvalid() ErrorMatcher { return m } +// BySource returns a derived ErrorMatcher which also matches by the error origination +// value of field errors. +func (m ErrorMatcher) BySource() ErrorMatcher { + m.matchSource = 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 { + m.matchValidationStabilityLevel = true + return m +} + // ByDetailExact returns a derived ErrorMatcher which also matches errors by // the exact detail string. func (m ErrorMatcher) ByDetailExact() ErrorMatcher { diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go b/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go index 950d83868..9357fb306 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go +++ b/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go @@ -42,7 +42,7 @@ type Error struct { // The value should be either: // - A simple camelCase identifier (e.g., "maximum", "maxItems") // - A structured format using "format=" for validation errors related to specific formats - // (e.g., "format=dns-label", "format=qualified-name") + // (e.g. "format=k8s-short-name") // // If the Origin corresponds to an existing declarative validation tag or JSON Schema keyword, // use that same name for consistency. @@ -55,10 +55,46 @@ type Error struct { // validation. This field is to identify errors from imperative validation // that should also be caught by declarative validation. CoveredByDeclarative bool + + // FromImperative denotes these errors are originating from the hand written validations. + FromImperative 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 +} + +// ValidationStabilityLevel denotes the stability level of a validation. +type ValidationStabilityLevel int + +const ( + stabilityLevelUnknown ValidationStabilityLevel = iota + stabilityLevelAlpha + stabilityLevelBeta +) + +func (v ValidationStabilityLevel) String() string { + switch v { + case stabilityLevelAlpha: + return "alpha" + case stabilityLevelBeta: + return "beta" + default: + return "unknown" + } } var _ error = &Error{} +// IsAlpha returns true if the error is an alpha validation error. +func (e *Error) IsAlpha() bool { + return e.ValidationStabilityLevel == stabilityLevelAlpha +} + +// IsBeta returns true if the error is a beta validation error. +func (e *Error) IsBeta() bool { + return e.ValidationStabilityLevel == stabilityLevelBeta +} + // Error implements the error interface. func (e *Error) Error() string { return fmt.Sprintf("%s: %s", e.Field, e.ErrorBody()) @@ -73,10 +109,10 @@ var omitValue = OmitValueType{} func (e *Error) ErrorBody() string { var s string switch e.Type { - case ErrorTypeRequired, ErrorTypeForbidden, ErrorTypeTooLong, ErrorTypeInternal: + case ErrorTypeRequired, ErrorTypeForbidden, ErrorTypeTooLong, ErrorTypeTooShort, ErrorTypeInternal: s = e.Type.String() case ErrorTypeInvalid, ErrorTypeTypeInvalid, ErrorTypeNotSupported, - ErrorTypeNotFound, ErrorTypeDuplicate, ErrorTypeTooMany: + ErrorTypeNotFound, ErrorTypeDuplicate, ErrorTypeTooMany, ErrorTypeTooFew: if e.BadValue == omitValue { s = e.Type.String() break @@ -113,6 +149,7 @@ func (e *Error) ErrorBody() string { if len(e.Detail) != 0 { s += fmt.Sprintf(": %s", e.Detail) } + return s } @@ -164,11 +201,18 @@ const ( // report that a given list has too many items. This is similar to FieldValueTooLong, // but the error indicates quantity instead of length. ErrorTypeTooMany ErrorType = "FieldValueTooMany" + // ErrorTypeTooFew is used to report "too few". This is used to + // report that a given list has too few items. This is similar to FieldValueTooLong, + // but the error indicates quantity instead of length. + ErrorTypeTooFew ErrorType = "FieldValueTooFew" // ErrorTypeInternal is used to report other errors that are not related // to user input. See InternalError(). ErrorTypeInternal ErrorType = "InternalError" // ErrorTypeTypeInvalid is for the value did not match the schema type for that field ErrorTypeTypeInvalid ErrorType = "FieldValueTypeInvalid" + // ErrorTypeTooShort is used to report that the given value is too short. + // This is similar to ErrorTypeInvalid. See TooShort(). + ErrorTypeTooShort ErrorType = "FieldValueTooShort" ) // String converts a ErrorType into its corresponding canonical error message. @@ -190,10 +234,14 @@ func (t ErrorType) String() string { return "Too long" case ErrorTypeTooMany: return "Too many" + case ErrorTypeTooFew: + return "Too few" case ErrorTypeInternal: return "Internal error" case ErrorTypeTypeInvalid: return "Invalid value" + case ErrorTypeTooShort: + return "Too short" default: return fmt.Sprintf("", string(t)) } @@ -201,32 +249,56 @@ func (t ErrorType) String() string { // TypeInvalid returns a *Error indicating "type is invalid" func TypeInvalid(field *Path, value interface{}, detail string) *Error { - return &Error{ErrorTypeTypeInvalid, field.String(), value, detail, "", false} + return &Error{ + Type: ErrorTypeTypeInvalid, + Field: field.String(), + BadValue: value, + Detail: detail, + } } // NotFound returns a *Error indicating "value not found". This is // used to report failure to find a requested value (e.g. looking up an ID). func NotFound(field *Path, value interface{}) *Error { - return &Error{ErrorTypeNotFound, field.String(), value, "", "", false} + return &Error{ + Type: ErrorTypeNotFound, + Field: field.String(), + BadValue: value, + } } // Required returns a *Error indicating "value required". This is used // to report required values that are not provided (e.g. empty strings, null // values, or empty arrays). func Required(field *Path, detail string) *Error { - return &Error{ErrorTypeRequired, field.String(), "", detail, "", false} + return &Error{ + Type: ErrorTypeRequired, + Field: field.String(), + Detail: detail, + BadValue: "", + } } // Duplicate returns a *Error indicating "duplicate value". This is // used to report collisions of values that must be unique (e.g. names or IDs). func Duplicate(field *Path, value interface{}) *Error { - return &Error{ErrorTypeDuplicate, field.String(), value, "", "", false} + return &Error{ + Type: ErrorTypeDuplicate, + Field: field.String(), + BadValue: value, + } } // Invalid returns a *Error indicating "invalid value". This is used // to report malformed values (e.g. failed regex match, too long, out of bounds). func Invalid(field *Path, value interface{}, detail string) *Error { - return &Error{ErrorTypeInvalid, field.String(), value, detail, "", false} + return &Error{ + Type: ErrorTypeInvalid, + Field: field.String(), + BadValue: value, + Detail: detail, + } + } // NotSupported returns a *Error indicating "unsupported value". @@ -241,7 +313,12 @@ func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *E } detail = "supported values: " + strings.Join(quotedValues, ", ") } - return &Error{ErrorTypeNotSupported, field.String(), value, detail, "", false} + return &Error{ + Type: ErrorTypeNotSupported, + Field: field.String(), + BadValue: value, + Detail: detail, + } } // Forbidden returns a *Error indicating "forbidden". This is used to @@ -249,7 +326,12 @@ func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *E // some conditions, but which are not permitted by current conditions (e.g. // security policy). func Forbidden(field *Path, detail string) *Error { - return &Error{ErrorTypeForbidden, field.String(), "", detail, "", false} + return &Error{ + Type: ErrorTypeForbidden, + Field: field.String(), + Detail: detail, + BadValue: "", + } } // TooLong returns a *Error indicating "too long". This is used to report that @@ -267,7 +349,35 @@ func TooLong(field *Path, _ interface{}, maxLength int) *Error { } else { msg = "value is too long" } - return &Error{ErrorTypeTooLong, field.String(), "", msg, "", false} + return &Error{ + Type: ErrorTypeTooLong, + Field: field.String(), + BadValue: "", + Detail: msg, + } +} + +// TooLongCharacters returns a *Error indicating "too long". This is used to report that +// the given value is too long in characters (including multi-byte characters). +// This is similar to Invalid, but the returned error will not include the too-long value. +// If maxLength is negative, it will be included in the message. The value argument is not used. +func TooLongCharacters[T ~string](field *Path, _ T, maxLength int) *Error { + var msg string + if maxLength >= 0 { + bs := "characters" + if maxLength == 1 { + bs = "character" + } + msg = fmt.Sprintf("may not be more than %d %s", maxLength, bs) + } else { + msg = "value is too long" + } + return &Error{ + Type: ErrorTypeTooLong, + Field: field.String(), + BadValue: "", + Detail: msg, + } } // TooLongMaxLength returns a *Error indicating "too long". @@ -299,14 +409,46 @@ func TooMany(field *Path, actualQuantity, maxQuantity int) *Error { actual = omitValue } - return &Error{ErrorTypeTooMany, field.String(), actual, msg, "", false} + return &Error{ + Type: ErrorTypeTooMany, + Field: field.String(), + BadValue: actual, + Detail: msg, + } } // InternalError returns a *Error indicating "internal error". This is used // to signal that an error was found that was not directly related to user // input. The err argument must be non-nil. func InternalError(field *Path, err error) *Error { - return &Error{ErrorTypeInternal, field.String(), nil, err.Error(), "", false} + return &Error{ + Type: ErrorTypeInternal, + Field: field.String(), + BadValue: err, + Detail: err.Error(), + } +} + +// TooShort returns a *Error indicating "too short". This is used to report that +// the given value is too short in characters. This is similar to Invalid. +// If minLength is non-negative, it will be included in the message. +func TooShort[T ~string](field *Path, value T, minLength int) *Error { + var msg string + if minLength >= 0 { + bs := "characters" + if minLength == 1 { + bs = "character" + } + msg = fmt.Sprintf("must be at least %d %s", minLength, bs) + } else { + msg = "value is too short" + } + return &Error{ + Type: ErrorTypeTooShort, + Field: field.String(), + BadValue: value, + Detail: msg, + } } // ErrorList holds a set of Errors. It is plausible that we might one day have @@ -397,6 +539,46 @@ func (list ErrorList) ExtractCoveredByDeclarative() ErrorList { return newList } +// MarkAlpha marks the error as an alpha validation error. +func (e *Error) MarkAlpha() *Error { + e.ValidationStabilityLevel = stabilityLevelAlpha + return e +} + +// MarkAlpha marks the errors as alpha validation errors. +func (list ErrorList) MarkAlpha() ErrorList { + for _, err := range list { + err.ValidationStabilityLevel = stabilityLevelAlpha + } + return list +} + +// MarkBeta marks the error as a beta validation error. +func (e *Error) MarkBeta() *Error { + e.ValidationStabilityLevel = stabilityLevelBeta + return e +} + +// MarkBeta marks the errors as beta validation errors. +func (list ErrorList) MarkBeta() ErrorList { + for _, err := range list { + err.ValidationStabilityLevel = stabilityLevelBeta + } + return list +} + +func (e *Error) MarkFromImperative() *Error { + e.FromImperative = true + return e +} + +func (list ErrorList) MarkFromImperative() ErrorList { + for _, err := range list { + err.FromImperative = 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{} @@ -407,3 +589,27 @@ func (list ErrorList) RemoveCoveredByDeclarative() ErrorList { } return newList } + +// TooFew returns a *Error indicating "too few". This is used to +// report that a given list has too few items. This is similar to TooLong, +// but the returned error indicates quantity instead of length. +func TooFew(field *Path, actualQuantity, minQuantity int) *Error { + var msg string + + if minQuantity >= 0 { + is := "items" + if minQuantity == 1 { + is = "item" + } + msg = fmt.Sprintf("must have at least %d %s", minQuantity, is) + } else { + msg = "has too few items" + } + + return &Error{ + Type: ErrorTypeTooFew, + Field: field.String(), + BadValue: actualQuantity, + Detail: msg, + } +} diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go b/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go index 6e947c74c..869fb0aad 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go +++ b/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go @@ -115,7 +115,7 @@ func GetWarningsForIP(fldPath *field.Path, value string) []string { // ParseAddr() doesn't) or IPv4-mapped IPv6 (.Is4In6()). Either way, // re-stringifying the net.IP value will give the preferred form. return []string{ - fmt.Sprintf("%s: non-standard IP address %q will be considered invalid in a future Kubernetes release: use %q", fldPath, value, ip.String()), + fmt.Sprintf("%s: non-standard IP address %q is invalid: use %q", fldPath, value, ip.String()), } } @@ -233,7 +233,7 @@ func GetWarningsForCIDR(fldPath *field.Path, value string) []string { // ParsePrefix() doesn't) or IPv4-mapped IPv6 (.Is4In6()). Either way, // re-stringifying the net.IPNet value will give the preferred form. warnings = append(warnings, - fmt.Sprintf("%s: non-standard CIDR value %q will be considered invalid in a future Kubernetes release: use %q", fldPath, value, ipnet.String()), + fmt.Sprintf("%s: non-standard CIDR value %q is invalid: use %q", fldPath, value, ipnet.String()), ) } diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go b/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go index 511e625b6..bb0fa55f2 100644 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go +++ b/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go @@ -178,7 +178,7 @@ func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, } // Two lists that are both empty and both non nil are equal - if v1.Len() == 0 || v2.Len() == 0 { + if v1.Len() == 0 && v2.Len() == 0 { return true } } @@ -229,7 +229,7 @@ func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, } // Two maps that are both empty and both non nil are equal - if v1.Len() == 0 || v2.Len() == 0 { + if v1.Len() == 0 && v2.Len() == 0 { return true } } diff --git a/vendor/k8s.io/klog/v2/internal/verbosity/verbosity.go b/vendor/k8s.io/klog/v2/internal/verbosity/verbosity.go new file mode 100644 index 000000000..40ec27d87 --- /dev/null +++ b/vendor/k8s.io/klog/v2/internal/verbosity/verbosity.go @@ -0,0 +1,303 @@ +/* +Copyright 2013 Google Inc. All Rights Reserved. +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 verbosity + +import ( + "bytes" + "errors" + "flag" + "fmt" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" +) + +// New returns a struct that implements -v and -vmodule support. Changing and +// checking these settings is thread-safe, with all concurrency issues handled +// internally. +func New() *VState { + vs := new(VState) + + // The two fields must have a pointer to the overal struct for their + // implementation of Set. + vs.vmodule.vs = vs + vs.verbosity.vs = vs + + return vs +} + +// Value is an extension that makes it possible to use the values in pflag. +type Value interface { + flag.Value + Type() string +} + +func (vs *VState) V() Value { + return &vs.verbosity +} + +func (vs *VState) VModule() Value { + return &vs.vmodule +} + +// VState contains settings and state. Some of its fields can be accessed +// through atomic read/writes, in other cases a mutex must be held. +type VState struct { + mu sync.Mutex + + // These flags are modified only under lock, although verbosity may be fetched + // safely using atomic.LoadInt32. + vmodule moduleSpec // The state of the -vmodule flag. + verbosity levelSpec // V logging level, the value of the -v flag/ + + // pcs is used in V to avoid an allocation when computing the caller's PC. + pcs [1]uintptr + // vmap is a cache of the V Level for each V() call site, identified by PC. + // It is wiped whenever the vmodule flag changes state. + vmap map[uintptr]Level + // filterLength stores the length of the vmodule filter chain. If greater + // than zero, it means vmodule is enabled. It may be read safely + // using sync.LoadInt32, but is only modified under mu. + filterLength int32 +} + +// Level must be an int32 to support atomic read/writes. +type Level int32 + +type levelSpec struct { + vs *VState + l Level +} + +// get returns the value of the level. +func (l *levelSpec) get() Level { + return Level(atomic.LoadInt32((*int32)(&l.l))) +} + +// set sets the value of the level. +func (l *levelSpec) set(val Level) { + atomic.StoreInt32((*int32)(&l.l), int32(val)) +} + +// String is part of the flag.Value interface. +func (l *levelSpec) String() string { + return strconv.FormatInt(int64(l.l), 10) +} + +// Get is part of the flag.Getter interface. It returns the +// verbosity level as int32. +func (l *levelSpec) Get() interface{} { + return int32(l.l) +} + +// Type is part of pflag.Value. +func (l *levelSpec) Type() string { + return "Level" +} + +// Set is part of the flag.Value interface. +func (l *levelSpec) Set(value string) error { + v, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return err + } + l.vs.mu.Lock() + defer l.vs.mu.Unlock() + l.vs.set(Level(v), l.vs.vmodule.filter, false) + return nil +} + +// moduleSpec represents the setting of the -vmodule flag. +type moduleSpec struct { + vs *VState + filter []modulePat +} + +// modulePat contains a filter for the -vmodule flag. +// It holds a verbosity level and a file pattern to match. +type modulePat struct { + pattern string + literal bool // The pattern is a literal string + level Level +} + +// match reports whether the file matches the pattern. It uses a string +// comparison if the pattern contains no metacharacters. +func (m *modulePat) match(file string) bool { + if m.literal { + return file == m.pattern + } + match, _ := filepath.Match(m.pattern, file) + return match +} + +func (m *moduleSpec) String() string { + // Lock because the type is not atomic. TODO: clean this up. + // Empty instances don't have and don't need a lock (can + // happen when flag uses introspection). + if m.vs != nil { + m.vs.mu.Lock() + defer m.vs.mu.Unlock() + } + var b bytes.Buffer + for i, f := range m.filter { + if i > 0 { + b.WriteRune(',') + } + fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) + } + return b.String() +} + +// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the +// struct is not exported. +func (m *moduleSpec) Get() interface{} { + return nil +} + +// Type is part of pflag.Value +func (m *moduleSpec) Type() string { + return "pattern=N,..." +} + +var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") + +// Set will sets module value +// Syntax: -vmodule=recordio=2,file=1,gfs*=3 +func (m *moduleSpec) Set(value string) error { + var filter []modulePat + for _, pat := range strings.Split(value, ",") { + if len(pat) == 0 { + // Empty strings such as from a trailing comma can be ignored. + continue + } + patLev := strings.Split(pat, "=") + if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { + return errVmoduleSyntax + } + pattern := patLev[0] + v, err := strconv.ParseInt(patLev[1], 10, 32) + if err != nil { + return errors.New("syntax error: expect comma-separated list of filename=N") + } + if v < 0 { + return errors.New("negative value for vmodule level") + } + if v == 0 { + continue // Ignore. It's harmless but no point in paying the overhead. + } + // TODO: check syntax of filter? + filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) + } + m.vs.mu.Lock() + defer m.vs.mu.Unlock() + m.vs.set(m.vs.verbosity.l, filter, true) + return nil +} + +// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters +// that require filepath.Match to be called to match the pattern. +func isLiteral(pattern string) bool { + return !strings.ContainsAny(pattern, `\*?[]`) +} + +// set sets a consistent state for V logging. +// The mutex must be held. +func (vs *VState) set(l Level, filter []modulePat, setFilter bool) { + // Turn verbosity off so V will not fire while we are in transition. + vs.verbosity.set(0) + // Ditto for filter length. + atomic.StoreInt32(&vs.filterLength, 0) + + // Set the new filters and wipe the pc->Level map if the filter has changed. + if setFilter { + vs.vmodule.filter = filter + vs.vmap = make(map[uintptr]Level) + } + + // Things are consistent now, so enable filtering and verbosity. + // They are enabled in order opposite to that in V. + atomic.StoreInt32(&vs.filterLength, int32(len(filter))) + vs.verbosity.set(l) +} + +// Enabled checks whether logging is enabled at the given level. This must be +// called with depth=0 when the caller of enabled will do the logging and +// higher values when more stack levels need to be skipped. +// +// The mutex will be locked only if needed. +func (vs *VState) Enabled(level Level, depth int) bool { + // This function tries hard to be cheap unless there's work to do. + // The fast path is two atomic loads and compares. + + // Here is a cheap but safe test to see if V logging is enabled globally. + if vs.verbosity.get() >= level { + return true + } + + // It's off globally but vmodule may still be set. + // Here is another cheap but safe test to see if vmodule is enabled. + if atomic.LoadInt32(&vs.filterLength) > 0 { + // Now we need a proper lock to use the logging structure. The pcs field + // is shared so we must lock before accessing it. This is fairly expensive, + // but if V logging is enabled we're slow anyway. + vs.mu.Lock() + defer vs.mu.Unlock() + if runtime.Callers(depth+2, vs.pcs[:]) == 0 { + return false + } + // runtime.Callers returns "return PCs", but we want + // to look up the symbolic information for the call, + // so subtract 1 from the PC. runtime.CallersFrames + // would be cleaner, but allocates. + pc := vs.pcs[0] - 1 + v, ok := vs.vmap[pc] + if !ok { + v = vs.setV(pc) + } + return v >= level + } + return false +} + +// setV computes and remembers the V level for a given PC +// when vmodule is enabled. +// File pattern matching takes the basename of the file, stripped +// of its .go suffix, and uses filepath.Match, which is a little more +// general than the *? matching used in C++. +// Mutex is held. +func (vs *VState) setV(pc uintptr) Level { + fn := runtime.FuncForPC(pc) + file, _ := fn.FileLine(pc) + // The file is something like /a/b/c/d.go. We want just the d. + file = strings.TrimSuffix(file, ".go") + if slash := strings.LastIndex(file, "/"); slash >= 0 { + file = file[slash+1:] + } + for _, filter := range vs.vmodule.filter { + if filter.match(file) { + vs.vmap[pc] = filter.level + return filter.level + } + } + vs.vmap[pc] = 0 + return 0 +} diff --git a/vendor/k8s.io/klog/v2/textlogger/options.go b/vendor/k8s.io/klog/v2/textlogger/options.go new file mode 100644 index 000000000..ed834ca68 --- /dev/null +++ b/vendor/k8s.io/klog/v2/textlogger/options.go @@ -0,0 +1,172 @@ +/* +Copyright 2021 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package textlogger + +import ( + "flag" + "io" + "os" + "strconv" + "time" + + "k8s.io/klog/v2/internal/verbosity" +) + +// Config influences logging in a text logger. To make this configurable via +// command line flags, instantiate this once per program and use AddFlags to +// bind command line flags to the instance before passing it to NewTestContext. +// +// Must be constructed with NewConfig. +type Config struct { + vstate *verbosity.VState + co configOptions +} + +// Verbosity returns a value instance that can be used to query (via String) or +// modify (via Set) the verbosity threshold. This is thread-safe and can be +// done at runtime. +func (c *Config) Verbosity() flag.Value { + return c.vstate.V() +} + +// VModule returns a value instance that can be used to query (via String) or +// modify (via Set) the vmodule settings. This is thread-safe and can be done +// at runtime. +func (c *Config) VModule() flag.Value { + return c.vstate.VModule() +} + +// ConfigOption implements functional parameters for NewConfig. +type ConfigOption func(co *configOptions) + +type configOptions struct { + verbosityFlagName string + vmoduleFlagName string + verbosityDefault int + fixedTime *time.Time + unwind func(int) (string, int) + withHeader bool + output io.Writer +} + +// VerbosityFlagName overrides the default -v for the verbosity level. +func VerbosityFlagName(name string) ConfigOption { + return func(co *configOptions) { + + co.verbosityFlagName = name + } +} + +// VModulFlagName overrides the default -vmodule for the per-module +// verbosity levels. +func VModuleFlagName(name string) ConfigOption { + return func(co *configOptions) { + co.vmoduleFlagName = name + } +} + +// Verbosity overrides the default verbosity level of 0. +// See https://github.com/kubernetes/community/blob/9406b4352fe2d5810cb21cc3cb059ce5886de157/contributors/devel/sig-instrumentation/logging.md#logging-conventions +// for log level conventions in Kubernetes. +func Verbosity(level int) ConfigOption { + return func(co *configOptions) { + co.verbosityDefault = level + } +} + +// Output overrides stderr as the output stream. +func Output(output io.Writer) ConfigOption { + return func(co *configOptions) { + co.output = output + } +} + +// FixedTime overrides the actual time with a fixed time. Useful only for testing. +// +// # Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func FixedTime(ts time.Time) ConfigOption { + return func(co *configOptions) { + co.fixedTime = &ts + } +} + +// WithHeader controls whether the header (time, source code location, etc.) +// is included in the output. The default is to include it. +// +// This can be useful in combination with redirection to a buffer to +// turn structured log parameters into a string (see example). +// +// # Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func WithHeader(enabled bool) ConfigOption { + return func(co *configOptions) { + co.withHeader = enabled + } +} + +// Backtrace overrides the default mechanism for determining the call site. +// The callback is invoked with the number of function calls between itself +// and the call site. It must return the file name and line number. An empty +// file name indicates that the information is unknown. +// +// # Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func Backtrace(unwind func(skip int) (filename string, line int)) ConfigOption { + return func(co *configOptions) { + co.unwind = unwind + } +} + +// NewConfig returns a configuration with recommended defaults and optional +// modifications. Command line flags are not bound to any FlagSet yet. +func NewConfig(opts ...ConfigOption) *Config { + c := &Config{ + vstate: verbosity.New(), + co: configOptions{ + verbosityFlagName: "v", + vmoduleFlagName: "vmodule", + verbosityDefault: 0, + unwind: runtimeBacktrace, + withHeader: true, + output: os.Stderr, + }, + } + for _, opt := range opts { + opt(&c.co) + } + + // Cannot fail for this input. + _ = c.Verbosity().Set(strconv.FormatInt(int64(c.co.verbosityDefault), 10)) + return c +} + +// AddFlags registers the command line flags that control the configuration. +// +// The default flag names are the same as in klog, so unless those defaults +// are changed, either klog.InitFlags or Config.AddFlags can be used for the +// same flag set, but not both. +func (c *Config) AddFlags(fs *flag.FlagSet) { + fs.Var(c.Verbosity(), c.co.verbosityFlagName, "number for the log level verbosity of the testing logger") + fs.Var(c.VModule(), c.co.vmoduleFlagName, "comma-separated list of pattern=N log level settings for files matching the patterns") +} diff --git a/vendor/k8s.io/klog/v2/textlogger/textlogger.go b/vendor/k8s.io/klog/v2/textlogger/textlogger.go new file mode 100644 index 000000000..813cba1d4 --- /dev/null +++ b/vendor/k8s.io/klog/v2/textlogger/textlogger.go @@ -0,0 +1,200 @@ +/* +Copyright 2019 The Kubernetes Authors. +Copyright 2020 Intel Corporation. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package textlogger contains an implementation of the logr interface which is +// producing the exact same output as klog. It does not route output through +// klog (i.e. ignores [k8s.io/klog/v2.InitFlags]). Instead, all settings must be +// configured through its own [NewConfig] and [Config.AddFlags]. +package textlogger + +import ( + "runtime" + "strconv" + "strings" + "time" + + "github.com/go-logr/logr" + + "k8s.io/klog/v2/internal/buffer" + "k8s.io/klog/v2/internal/serialize" + "k8s.io/klog/v2/internal/severity" + "k8s.io/klog/v2/internal/verbosity" +) + +var ( + // TimeNow is used to retrieve the current time. May be changed for testing. + TimeNow = time.Now +) + +const ( + // nameKey is used to log the `WithName` values as an additional attribute. + nameKey = "logger" +) + +// NewLogger constructs a new logger. +// +// Verbosity can be modified at any time through the Config.V and +// Config.VModule API. +func NewLogger(c *Config) logr.Logger { + return logr.New(&tlogger{ + values: nil, + config: c, + }) +} + +type tlogger struct { + callDepth int + + // hasPrefix is true if the first entry in values is the special + // nameKey key/value. Such an entry gets added and later updated in + // WithName. + hasPrefix bool + + values []interface{} + groups string + config *Config +} + +func (l *tlogger) Init(info logr.RuntimeInfo) { + l.callDepth = info.CallDepth +} + +func (l *tlogger) WithCallDepth(depth int) logr.LogSink { + newLogger := *l + newLogger.callDepth += depth + return &newLogger +} + +func (l *tlogger) Enabled(level int) bool { + return l.config.vstate.Enabled(verbosity.Level(level), 1+l.callDepth) +} + +func (l *tlogger) Info(_ int, msg string, kvList ...interface{}) { + l.print(nil, severity.InfoLog, msg, kvList) +} + +func (l *tlogger) Error(err error, msg string, kvList ...interface{}) { + l.print(err, severity.ErrorLog, msg, kvList) +} + +func (l *tlogger) print(err error, s severity.Severity, msg string, kvList []interface{}) { + var file string + var line int + var now time.Time + if l.config.co.withHeader { + // Determine caller. + // +1 for this frame, +1 for Info/Error. + skip := l.callDepth + 2 + file, line = l.config.co.unwind(skip) + if file == "" { + file = "???" + line = 1 + } else if slash := strings.LastIndex(file, "/"); slash >= 0 { + file = file[slash+1:] + } + now = time.Now() + } + l.printWithInfos(file, line, now, err, s, msg, kvList) +} + +func runtimeBacktrace(skip int) (string, int) { + _, file, line, ok := runtime.Caller(skip + 1) + if !ok { + return "", 0 + } + return file, line +} + +func (l *tlogger) printWithInfos(file string, line int, now time.Time, err error, s severity.Severity, msg string, kvList []interface{}) { + // The message is always quoted, even if it contains line breaks. + // If developers want multi-line output, they should use a small, fixed + // message and put the multi-line output into a value. + qMsg := make([]byte, 0, 1024) + qMsg = strconv.AppendQuote(qMsg, msg) + + // Only create a new buffer if we don't have one cached. + b := buffer.GetBuffer() + defer buffer.PutBuffer(b) + + if l.config.co.withHeader { + // Format header. + if l.config.co.fixedTime != nil { + now = *l.config.co.fixedTime + } + b.FormatHeader(s, file, line, now) + } + + b.Write(qMsg) + + var errKV []interface{} + if err != nil { + errKV = []interface{}{"err", err} + } + serialize.FormatKVs(&b.Buffer, errKV, l.values, kvList) + if b.Len() == 0 || b.Bytes()[b.Len()-1] != '\n' { + b.WriteByte('\n') + } + _, _ = l.config.co.output.Write(b.Bytes()) +} + +func (l *tlogger) WriteKlogBuffer(data []byte) { + _, _ = l.config.co.output.Write(data) +} + +// WithName returns a new logr.Logger with the specified name appended. klogr +// uses '/' characters to separate name elements. Callers should not pass '/' +// in the provided name string, but this library does not actually enforce that. +func (l *tlogger) WithName(name string) logr.LogSink { + clone := *l + if l.hasPrefix { + // Copy slice and modify value. No length checks and type + // assertions are needed because hasPrefix is only true if the + // first two elements exist and are key/value strings. + v := make([]interface{}, 0, len(l.values)) + v = append(v, l.values...) + prefix, _ := v[1].(string) + v[1] = prefix + "." + name + clone.values = v + } else { + // Preprend new key/value pair. + v := make([]interface{}, 0, 2+len(l.values)) + v = append(v, nameKey, name) + v = append(v, l.values...) + clone.values = v + clone.hasPrefix = true + } + return &clone +} + +func (l *tlogger) WithValues(kvList ...interface{}) logr.LogSink { + clone := *l + clone.values = serialize.WithValues(l.values, kvList) + return &clone +} + +// KlogBufferWriter is implemented by the textlogger LogSink. +type KlogBufferWriter interface { + // WriteKlogBuffer takes a pre-formatted buffer prepared by klog and + // writes it unchanged to the output stream. Can be used with + // klog.WriteKlogBuffer when setting a logger through + // klog.SetLoggerWithOptions. + WriteKlogBuffer([]byte) +} + +var _ logr.LogSink = &tlogger{} +var _ logr.CallDepthLogSink = &tlogger{} +var _ KlogBufferWriter = &tlogger{} diff --git a/vendor/k8s.io/klog/v2/textlogger/textlogger_slog.go b/vendor/k8s.io/klog/v2/textlogger/textlogger_slog.go new file mode 100644 index 000000000..c888ef8a6 --- /dev/null +++ b/vendor/k8s.io/klog/v2/textlogger/textlogger_slog.go @@ -0,0 +1,52 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package textlogger + +import ( + "context" + "log/slog" + + "github.com/go-logr/logr" + + "k8s.io/klog/v2/internal/serialize" + "k8s.io/klog/v2/internal/sloghandler" +) + +func (l *tlogger) Handle(ctx context.Context, record slog.Record) error { + return sloghandler.Handle(ctx, record, l.groups, l.printWithInfos) +} + +func (l *tlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink { + clone := *l + clone.values = serialize.WithValues(l.values, sloghandler.Attrs2KVList(l.groups, attrs)) + return &clone +} + +func (l *tlogger) WithGroup(name string) logr.SlogSink { + clone := *l + if clone.groups != "" { + clone.groups += "." + name + } else { + clone.groups = name + } + return &clone +} + +var _ logr.SlogSink = &tlogger{} diff --git a/vendor/k8s.io/utils/dump/dump.go b/vendor/k8s.io/utils/dump/dump.go new file mode 100644 index 000000000..cf61ef76a --- /dev/null +++ b/vendor/k8s.io/utils/dump/dump.go @@ -0,0 +1,54 @@ +/* +Copyright 2021 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package dump + +import ( + "github.com/davecgh/go-spew/spew" +) + +var prettyPrintConfig = &spew.ConfigState{ + Indent: " ", + DisableMethods: true, + DisablePointerAddresses: true, + DisableCapacities: true, +} + +// The config MUST NOT be changed because that could change the result of a hash operation +var prettyPrintConfigForHash = &spew.ConfigState{ + Indent: " ", + SortKeys: true, + DisableMethods: true, + SpewKeys: true, + DisablePointerAddresses: true, + DisableCapacities: true, +} + +// Pretty wrap the spew.Sdump with Indent, and disabled methods like error() and String() +// The output may change over time, so for guaranteed output please take more direct control +func Pretty(a interface{}) string { + return prettyPrintConfig.Sdump(a) +} + +// ForHash keeps the original Spew.Sprintf format to ensure the same checksum +func ForHash(a interface{}) string { + return prettyPrintConfigForHash.Sprintf("%#v", a) +} + +// OneLine outputs the object in one line +func OneLine(a interface{}) string { + return prettyPrintConfig.Sprintf("%#v", a) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index c0e6088e3..1ef0d7781 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -511,7 +511,7 @@ golang.org/x/tools/internal/versions # gomodules.xyz/jsonpatch/v2 v2.4.0 ## explicit; go 1.20 gomodules.xyz/jsonpatch/v2 -# google.golang.org/protobuf v1.36.11 +# google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af ## explicit; go 1.23 google.golang.org/protobuf/encoding/protodelim google.golang.org/protobuf/encoding/prototext @@ -626,8 +626,8 @@ 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/apimachinery v0.35.3 -## explicit; go 1.25.0 +# k8s.io/apimachinery v0.36.0 +## explicit; go 1.26.0 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors k8s.io/apimachinery/pkg/api/meta @@ -1007,6 +1007,8 @@ k8s.io/klog/v2/internal/dbg k8s.io/klog/v2/internal/serialize k8s.io/klog/v2/internal/severity k8s.io/klog/v2/internal/sloghandler +k8s.io/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/pkg/cached @@ -1035,6 +1037,7 @@ k8s.io/kubectl/pkg/validation ## explicit; go 1.23 k8s.io/utils/buffer k8s.io/utils/clock +k8s.io/utils/dump k8s.io/utils/exec k8s.io/utils/internal/third_party/forked/golang/golang-lru k8s.io/utils/internal/third_party/forked/golang/net