repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "math" "strconv" ) // NOTE: Token is analogous to v1 json.Token. const ( maxInt64 = math.MaxInt64 minInt64 = math.MinInt64 maxUint64 = math.MaxUint64 minUint64 = 0 // for consistency and readability purposes invalidTokenPanic = "invalid json.Token; it has been voided by a subsequent json.Decoder call" ) // Token represents a lexical JSON token, which may be one of the following: // - a JSON literal (i.e., null, true, or false) // - a JSON string (e.g., "hello, world!") // - a JSON number (e.g., 123.456) // - a start or end delimiter for a JSON object (i.e., { or } ) // - a start or end delimiter for a JSON array (i.e., [ or ] ) // // A Token cannot represent entire array or object values, while a RawValue can. // There is no Token to represent commas and colons since // these structural tokens can be inferred from the surrounding context. type Token struct { nonComparable // Tokens can exist in either a "raw" or an "exact" form. // Tokens produced by the Decoder are in the "raw" form. // Tokens returned by constructors are usually in the "exact" form. // The Encoder accepts Tokens in either the "raw" or "exact" form. // // The following chart shows the possible values for each Token type: // ╔═════════════════╦════════════╀════════════╀════════════╗ // β•‘ Token type β•‘ raw field β”‚ str field β”‚ num field β•‘ // ╠═════════════════╬════════════β•ͺ════════════β•ͺ════════════╣ // β•‘ null (raw) β•‘ "null" β”‚ "" β”‚ 0 β•‘ // β•‘ false (raw) β•‘ "false" β”‚ "" β”‚ 0 β•‘ // β•‘ true (raw) β•‘ "true" β”‚ "" β”‚ 0 β•‘ // β•‘ string (raw) β•‘ non-empty β”‚ "" β”‚ offset β•‘ // β•‘ string (string) β•‘ nil β”‚ non-empty β”‚ 0 β•‘ // β•‘ number (raw) β•‘ non-empty β”‚ "" β”‚ offset β•‘ // β•‘ number (float) β•‘ nil β”‚ "f" β”‚ non-zero β•‘ // β•‘ number (int64) β•‘ nil β”‚ "i" β”‚ non-zero β•‘ // β•‘ number (uint64) β•‘ nil β”‚ "u" β”‚ non-zero β•‘ // β•‘ object (delim) β•‘ "{" or "}" β”‚ "" β”‚ 0 β•‘ // β•‘ array (delim) β•‘ "[" or "]" β”‚ "" β”‚ 0 β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•§β•β•β•β•β•β•β•β•β•β•β•β•β•§β•β•β•β•β•β•β•β•β•β•β•β•β• // // Notes: // - For tokens stored in "raw" form, the num field contains the // absolute offset determined by raw.previousOffsetStart(). // The buffer itself is stored in raw.previousBuffer(). // - JSON literals and structural characters are always in the "raw" form. // - JSON strings and numbers can be in either "raw" or "exact" forms. // - The exact zero value of JSON strings and numbers in the "exact" forms // have ambiguous representation. Thus, they are always represented // in the "raw" form. // raw contains a reference to the raw decode buffer. // If non-nil, then its value takes precedence over str and num. // It is only valid if num == raw.previousOffsetStart(). raw *decodeBuffer // str is the unescaped JSON string if num is zero. // Otherwise, it is "f", "i", or "u" if num should be interpreted // as a float64, int64, or uint64, respectively. str string // num is a float64, int64, or uint64 stored as a uint64 value. // It is non-zero for any JSON number in the "exact" form. num uint64 } // TODO: Does representing 1-byte delimiters as *decodeBuffer cause performance issues? var ( Null Token = rawToken("null") False Token = rawToken("false") True Token = rawToken("true") ObjectStart Token = rawToken("{") ObjectEnd Token = rawToken("}") ArrayStart Token = rawToken("[") ArrayEnd Token = rawToken("]") zeroString Token = rawToken(`""`) zeroNumber Token = rawToken(`0`) nanString Token = String("NaN") pinfString Token = String("Infinity") ninfString Token = String("-Infinity") ) func rawToken(s string) Token { return Token{raw: &decodeBuffer{buf: []byte(s), prevStart: 0, prevEnd: len(s)}} } // Bool constructs a Token representing a JSON boolean. func Bool(b bool) Token { if b { return True } return False } // String constructs a Token representing a JSON string. // The provided string should contain valid UTF-8, otherwise invalid characters // may be mangled as the Unicode replacement character. func String(s string) Token { if len(s) == 0 { return zeroString } return Token{str: s} } // Float constructs a Token representing a JSON number. // The values NaN, +Inf, and -Inf will be represented // as a JSON string with the values "NaN", "Infinity", and "-Infinity". func Float(n float64) Token { switch { case math.Float64bits(n) == 0: return zeroNumber case math.IsNaN(n): return nanString case math.IsInf(n, +1): return pinfString case math.IsInf(n, -1): return ninfString } return Token{str: "f", num: math.Float64bits(n)} } // Int constructs a Token representing a JSON number from an int64. func Int(n int64) Token { if n == 0 { return zeroNumber } return Token{str: "i", num: uint64(n)} } // Uint constructs a Token representing a JSON number from a uint64. func Uint(n uint64) Token { if n == 0 { return zeroNumber } return Token{str: "u", num: uint64(n)} } // Clone makes a copy of the Token such that its value remains valid // even after a subsequent Decoder.Read call. func (t Token) Clone() Token { // TODO: Allow caller to avoid any allocations? if raw := t.raw; raw != nil { // Avoid copying globals. if t.raw.prevStart == 0 { switch t.raw { case Null.raw: return Null case False.raw: return False case True.raw: return True case ObjectStart.raw: return ObjectStart case ObjectEnd.raw: return ObjectEnd case ArrayStart.raw: return ArrayStart case ArrayEnd.raw: return ArrayEnd } } if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } // TODO(https://go.dev/issue/45038): Use bytes.Clone. buf := append([]byte(nil), raw.previousBuffer()...) return Token{raw: &decodeBuffer{buf: buf, prevStart: 0, prevEnd: len(buf)}} } return t } // Bool returns the value for a JSON boolean. // It panics if the token kind is not a JSON boolean. func (t Token) Bool() bool { switch t.raw { case True.raw: return true case False.raw: return false default: panic("invalid JSON token kind: " + t.Kind().String()) } } // appendString appends a JSON string to dst and returns it. // It panics if t is not a JSON string. func (t Token) appendString(dst []byte, validateUTF8, preserveRaw bool, escapeRune func(rune) bool) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw string value. buf := raw.previousBuffer() if Kind(buf[0]) == '"' { if escapeRune == nil && consumeSimpleString(buf) == len(buf) { return append(dst, buf...), nil } dst, _, err := reformatString(dst, buf, validateUTF8, preserveRaw, escapeRune) return dst, err } } else if len(t.str) != 0 && t.num == 0 { // Handle exact string value. return appendString(dst, t.str, validateUTF8, escapeRune) } panic("invalid JSON token kind: " + t.Kind().String()) } // String returns the unescaped string value for a JSON string. // For other JSON kinds, this returns the raw JSON representation. func (t Token) String() string { // This is inlinable to take advantage of "function outlining". // This avoids an allocation for the string(b) conversion // if the caller does not use the string in an escaping manner. // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/ s, b := t.string() if len(b) > 0 { return string(b) } return s } func (t Token) string() (string, []byte) { if raw := t.raw; raw != nil { if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } buf := raw.previousBuffer() if buf[0] == '"' { // TODO: Preserve valueFlags in Token? isVerbatim := consumeSimpleString(buf) == len(buf) return "", unescapeStringMayCopy(buf, isVerbatim) } // Handle tokens that are not JSON strings for fmt.Stringer. return "", buf } if len(t.str) != 0 && t.num == 0 { return t.str, nil } // Handle tokens that are not JSON strings for fmt.Stringer. if t.num > 0 { switch t.str[0] { case 'f': return string(appendNumber(nil, math.Float64frombits(t.num), 64)), nil case 'i': return strconv.FormatInt(int64(t.num), 10), nil case 'u': return strconv.FormatUint(uint64(t.num), 10), nil } } return "<invalid json.Token>", nil } // appendNumber appends a JSON number to dst and returns it. // It panics if t is not a JSON number. func (t Token) appendNumber(dst []byte, canonicalize bool) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw number value. buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { if !canonicalize { return append(dst, buf...), nil } dst, _, err := reformatNumber(dst, buf, canonicalize) return dst, err } } else if t.num != 0 { // Handle exact number value. switch t.str[0] { case 'f': return appendNumber(dst, math.Float64frombits(t.num), 64), nil case 'i': return strconv.AppendInt(dst, int64(t.num), 10), nil case 'u': return strconv.AppendUint(dst, uint64(t.num), 10), nil } } panic("invalid JSON token kind: " + t.Kind().String()) } // Float returns the floating-point value for a JSON number. // It returns a NaN, +Inf, or -Inf value for any JSON string // with the values "NaN", "Infinity", or "-Infinity". // It panics for all other cases. func (t Token) Float() float64 { if raw := t.raw; raw != nil { // Handle raw number value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { fv, _ := parseFloat(buf, 64) return fv } } else if t.num != 0 { // Handle exact number value. switch t.str[0] { case 'f': return math.Float64frombits(t.num) case 'i': return float64(int64(t.num)) case 'u': return float64(uint64(t.num)) } } // Handle string values with "NaN", "Infinity", or "-Infinity". if t.Kind() == '"' { switch t.String() { case "NaN": return math.NaN() case "Infinity": return math.Inf(+1) case "-Infinity": return math.Inf(-1) } } panic("invalid JSON token kind: " + t.Kind().String()) } // Int returns the signed integer value for a JSON number. // The fractional component of any number is ignored (truncation toward zero). // Any number beyond the representation of an int64 will be saturated // to the closest representable value. // It panics if the token kind is not a JSON number. func (t Token) Int() int64 { if raw := t.raw; raw != nil { // Handle raw integer value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } neg := false buf := raw.previousBuffer() if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } if numAbs, ok := parseDecUint(buf); ok { if neg { if numAbs > -minInt64 { return minInt64 } return -1 * int64(numAbs) } else { if numAbs > +maxInt64 { return maxInt64 } return +1 * int64(numAbs) } } } else if t.num != 0 { // Handle exact integer value. switch t.str[0] { case 'i': return int64(t.num) case 'u': if t.num > maxInt64 { return maxInt64 } return int64(t.num) } } // Handle JSON number that is a floating-point value. if t.Kind() == '0' { switch fv := t.Float(); { case fv >= maxInt64: return maxInt64 case fv <= minInt64: return minInt64 default: return int64(fv) // truncation toward zero } } panic("invalid JSON token kind: " + t.Kind().String()) } // Uint returns the unsigned integer value for a JSON number. // The fractional component of any number is ignored (truncation toward zero). // Any number beyond the representation of an uint64 will be saturated // to the closest representable value. // It panics if the token kind is not a JSON number. func (t Token) Uint() uint64 { // NOTE: This accessor returns 0 for any negative JSON number, // which might be surprising, but is at least consistent with the behavior // of saturating out-of-bounds numbers to the closest representable number. if raw := t.raw; raw != nil { // Handle raw integer value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } neg := false buf := raw.previousBuffer() if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } if num, ok := parseDecUint(buf); ok { if neg { return minUint64 } return num } } else if t.num != 0 { // Handle exact integer value. switch t.str[0] { case 'u': return t.num case 'i': if int64(t.num) < minUint64 { return minUint64 } return uint64(int64(t.num)) } } // Handle JSON number that is a floating-point value. if t.Kind() == '0' { switch fv := t.Float(); { case fv >= maxUint64: return maxUint64 case fv <= minUint64: return minUint64 default: return uint64(fv) // truncation toward zero } } panic("invalid JSON token kind: " + t.Kind().String()) } // Kind returns the token kind. func (t Token) Kind() Kind { switch { case t.raw != nil: raw := t.raw if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } return Kind(t.raw.buf[raw.prevStart]).normalize() case t.num != 0: return '0' case len(t.str) != 0: return '"' default: return invalidKind } } // Kind represents each possible JSON token kind with a single byte, // which is conveniently the first byte of that kind's grammar // with the restriction that numbers always be represented with '0': // // - 'n': null // - 'f': false // - 't': true // - '"': string // - '0': number // - '{': object start // - '}': object end // - '[': array start // - ']': array end // // An invalid kind is usually represented using 0, // but may be non-zero due to invalid JSON data. type Kind byte const invalidKind Kind = 0 // String prints the kind in a humanly readable fashion. func (k Kind) String() string { switch k { case 'n': return "null" case 'f': return "false" case 't': return "true" case '"': return "string" case '0': return "number" case '{': return "{" case '}': return "}" case '[': return "[" case ']': return "]" default: return "<invalid json.Kind: " + quoteRune([]byte{byte(k)}) + ">" } } // normalize coalesces all possible starting characters of a number as just '0'. func (k Kind) normalize() Kind { if k == '-' || ('0' <= k && k <= '9') { return '0' } return k }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import "reflect" // This files contains an optimized marshal and unmarshal implementation // for the any type. This type is often used when the Go program has // no knowledge of the JSON schema. This is a common enough occurrence // to justify the complexity of adding logic for this. func marshalValueAny(mo MarshalOptions, enc *Encoder, val any) error { switch val := val.(type) { case nil: return enc.WriteToken(Null) case bool: return enc.WriteToken(Bool(val)) case string: return enc.WriteToken(String(val)) case float64: return enc.WriteToken(Float(val)) case map[string]any: return marshalObjectAny(mo, enc, val) case []any: return marshalArrayAny(mo, enc, val) default: v := newAddressableValue(reflect.TypeOf(val)) v.Set(reflect.ValueOf(val)) marshal := lookupArshaler(v.Type()).marshal if mo.Marshalers != nil { marshal, _ = mo.Marshalers.lookup(marshal, v.Type()) } return marshal(mo, enc, v) } } func unmarshalValueAny(uo UnmarshalOptions, dec *Decoder) (any, error) { switch k := dec.PeekKind(); k { case '{': return unmarshalObjectAny(uo, dec) case '[': return unmarshalArrayAny(uo, dec) default: var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return nil, err } switch val.Kind() { case 'n': return nil, nil case 'f': return false, nil case 't': return true, nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) if dec.stringCache == nil { dec.stringCache = new(stringCache) } return dec.stringCache.make(val), nil case '0': fv, _ := parseFloat(val, 64) // ignore error since readValue guarantees val is valid return fv, nil default: panic("BUG: invalid kind: " + k.String()) } } } func marshalObjectAny(mo MarshalOptions, enc *Encoder, obj map[string]any) error { // Check for cycles. if enc.tokens.depth() > startDetectingCyclesAfter { v := reflect.ValueOf(obj) if err := enc.seenPointers.visit(v); err != nil { return err } defer enc.seenPointers.leave(v) } // Optimize for marshaling an empty map without any preceding whitespace. if len(obj) == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '{') enc.buf = append(enc.buf, "{}"...) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } if err := enc.WriteToken(ObjectStart); err != nil { return err } // A Go map guarantees that each entry has a unique key // The only possibility of duplicates is due to invalid UTF-8. if !enc.options.AllowInvalidUTF8 { enc.tokens.last.disableNamespace() } if !mo.Deterministic || len(obj) <= 1 { for name, val := range obj { if err := enc.WriteToken(String(name)); err != nil { return err } if err := marshalValueAny(mo, enc, val); err != nil { return err } } } else { names := getStrings(len(obj)) var i int for name := range obj { (*names)[i] = name i++ } names.Sort() for _, name := range *names { if err := enc.WriteToken(String(name)); err != nil { return err } if err := marshalValueAny(mo, enc, obj[name]); err != nil { return err } } putStrings(names) } if err := enc.WriteToken(ObjectEnd); err != nil { return err } return nil } func unmarshalObjectAny(uo UnmarshalOptions, dec *Decoder) (map[string]any, error) { tok, err := dec.ReadToken() if err != nil { return nil, err } k := tok.Kind() switch k { case 'n': return nil, nil case '{': obj := make(map[string]any) // A Go map guarantees that each entry has a unique key // The only possibility of duplicates is due to invalid UTF-8. if !dec.options.AllowInvalidUTF8 { dec.tokens.last.disableNamespace() } for dec.PeekKind() != '}' { tok, err := dec.ReadToken() if err != nil { return obj, err } name := tok.String() // Manually check for duplicate names. if _, ok := obj[name]; ok { name := dec.previousBuffer() err := &SyntacticError{str: "duplicate name " + string(name) + " in object"} return obj, err.withOffset(dec.InputOffset() - int64(len(name))) } val, err := unmarshalValueAny(uo, dec) obj[name] = val if err != nil { return obj, err } } if _, err := dec.ReadToken(); err != nil { return obj, err } return obj, nil } return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: mapStringAnyType} } func marshalArrayAny(mo MarshalOptions, enc *Encoder, arr []any) error { // Check for cycles. if enc.tokens.depth() > startDetectingCyclesAfter { v := reflect.ValueOf(arr) if err := enc.seenPointers.visit(v); err != nil { return err } defer enc.seenPointers.leave(v) } // Optimize for marshaling an empty slice without any preceding whitespace. if len(arr) == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '[') enc.buf = append(enc.buf, "[]"...) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } if err := enc.WriteToken(ArrayStart); err != nil { return err } for _, val := range arr { if err := marshalValueAny(mo, enc, val); err != nil { return err } } if err := enc.WriteToken(ArrayEnd); err != nil { return err } return nil } func unmarshalArrayAny(uo UnmarshalOptions, dec *Decoder) ([]any, error) { tok, err := dec.ReadToken() if err != nil { return nil, err } k := tok.Kind() switch k { case 'n': return nil, nil case '[': arr := []any{} for dec.PeekKind() != ']' { val, err := unmarshalValueAny(uo, dec) arr = append(arr, val) if err != nil { return arr, err } } if _, err := dec.ReadToken(); err != nil { return arr, err } return arr, nil } return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: sliceAnyType} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "math" "strconv" ) var ( errMissingName = &SyntacticError{str: "missing string for object name"} errMissingColon = &SyntacticError{str: "missing character ':' after object name"} errMissingValue = &SyntacticError{str: "missing value after object name"} errMissingComma = &SyntacticError{str: "missing character ',' after object or array value"} errMismatchDelim = &SyntacticError{str: "mismatching structural token for object or array"} ) const errInvalidNamespace = jsonError("object namespace is in an invalid state") type state struct { // tokens validates whether the next token kind is valid. tokens stateMachine // names is a stack of object names. // Not used if AllowDuplicateNames is true. names objectNameStack // namespaces is a stack of object namespaces. // For performance reasons, Encoder or Decoder may not update this // if Marshal or Unmarshal is able to track names in a more efficient way. // See makeMapArshaler and makeStructArshaler. // Not used if AllowDuplicateNames is true. namespaces objectNamespaceStack } func (s *state) reset() { s.tokens.reset() s.names.reset() s.namespaces.reset() } // appendStackPointer appends a JSON Pointer (RFC 6901) to the current value. // The returned pointer is only accurate if s.names is populated, // otherwise it uses the numeric index as the object member name. // // Invariant: Must call s.names.copyQuotedBuffer beforehand. func (s state) appendStackPointer(b []byte) []byte { var objectDepth int for i := 1; i < s.tokens.depth(); i++ { e := s.tokens.index(i) if e.length() == 0 { break // empty object or array } b = append(b, '/') switch { case e.isObject(): if objectDepth < s.names.length() { for _, c := range s.names.getUnquoted(objectDepth) { // Per RFC 6901, section 3, escape '~' and '/' characters. switch c { case '~': b = append(b, "~0"...) case '/': b = append(b, "~1"...) default: b = append(b, c) } } } else { // Since the names stack is unpopulated, the name is unknown. // As a best-effort replacement, use the numeric member index. // While inaccurate, it produces a syntactically valid pointer. b = strconv.AppendUint(b, uint64((e.length()-1)/2), 10) } objectDepth++ case e.isArray(): b = strconv.AppendUint(b, uint64(e.length()-1), 10) } } return b } // stateMachine is a push-down automaton that validates whether // a sequence of tokens is valid or not according to the JSON grammar. // It is useful for both encoding and decoding. // // It is a stack where each entry represents a nested JSON object or array. // The stack has a minimum depth of 1 where the first level is a // virtual JSON array to handle a stream of top-level JSON values. // The top-level virtual JSON array is special in that it doesn't require commas // between each JSON value. // // For performance, most methods are carefully written to be inlineable. // The zero value is a valid state machine ready for use. type stateMachine struct { stack []stateEntry last stateEntry } // reset resets the state machine. // The machine always starts with a minimum depth of 1. func (m *stateMachine) reset() { m.stack = m.stack[:0] if cap(m.stack) > 1<<10 { m.stack = nil } m.last = stateTypeArray } // depth is the current nested depth of JSON objects and arrays. // It is one-indexed (i.e., top-level values have a depth of 1). func (m stateMachine) depth() int { return len(m.stack) + 1 } // index returns a reference to the ith entry. // It is only valid until the next push method call. func (m *stateMachine) index(i int) *stateEntry { if i == len(m.stack) { return &m.last } return &m.stack[i] } // depthLength reports the current nested depth and // the length of the last JSON object or array. func (m stateMachine) depthLength() (int, int) { return m.depth(), m.last.length() } // appendLiteral appends a JSON literal as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendLiteral() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() return nil } } // appendString appends a JSON string as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendString() error { switch { case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() return nil } } // appendNumber appends a JSON number as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendNumber() error { return m.appendLiteral() } // pushObject appends a JSON start object token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushObject() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() m.stack = append(m.stack, m.last) m.last = stateTypeObject return nil } } // popObject appends a JSON end object token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) popObject() error { switch { case !m.last.isObject(): return errMismatchDelim case m.last.needObjectValue(): return errMissingValue case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last = m.stack[len(m.stack)-1] m.stack = m.stack[:len(m.stack)-1] return nil } } // pushArray appends a JSON start array token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushArray() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() m.stack = append(m.stack, m.last) m.last = stateTypeArray return nil } } // popArray appends a JSON end array token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) popArray() error { switch { case !m.last.isArray() || len(m.stack) == 0: // forbid popping top-level virtual JSON array return errMismatchDelim case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last = m.stack[len(m.stack)-1] m.stack = m.stack[:len(m.stack)-1] return nil } } // needIndent reports whether indent whitespace should be injected. // A zero value means that no whitespace should be injected. // A positive value means '\n', indentPrefix, and (n-1) copies of indentBody // should be appended to the output immediately before the next token. func (m stateMachine) needIndent(next Kind) (n int) { willEnd := next == '}' || next == ']' switch { case m.depth() == 1: return 0 // top-level values are never indented case m.last.length() == 0 && willEnd: return 0 // an empty object or array is never indented case m.last.length() == 0 || m.last.needImplicitComma(next): return m.depth() case willEnd: return m.depth() - 1 default: return 0 } } // mayAppendDelim appends a colon or comma that may precede the next token. func (m stateMachine) mayAppendDelim(b []byte, next Kind) []byte { switch { case m.last.needImplicitColon(): return append(b, ':') case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values return append(b, ',') default: return b } } // needDelim reports whether a colon or comma token should be implicitly emitted // before the next token of the specified kind. // A zero value means no delimiter should be emitted. func (m stateMachine) needDelim(next Kind) (delim byte) { switch { case m.last.needImplicitColon(): return ':' case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values return ',' default: return 0 } } // checkDelim reports whether the specified delimiter should be there given // the kind of the next token that appears immediately afterwards. func (m stateMachine) checkDelim(delim byte, next Kind) error { switch needDelim := m.needDelim(next); { case needDelim == delim: return nil case needDelim == ':': return errMissingColon case needDelim == ',': return errMissingComma default: return newInvalidCharacterError([]byte{delim}, "before next token") } } // invalidateDisabledNamespaces marks all disabled namespaces as invalid. // // For efficiency, Marshal and Unmarshal may disable namespaces since there are // more efficient ways to track duplicate names. However, if an error occurs, // the namespaces in Encoder or Decoder will be left in an inconsistent state. // Mark the namespaces as invalid so that future method calls on // Encoder or Decoder will return an error. func (m *stateMachine) invalidateDisabledNamespaces() { for i := 0; i < m.depth(); i++ { e := m.index(i) if !e.isActiveNamespace() { e.invalidateNamespace() } } } // stateEntry encodes several artifacts within a single unsigned integer: // - whether this represents a JSON object or array, // - whether this object should check for duplicate names, and // - how many elements are in this JSON object or array. type stateEntry uint64 const ( // The type mask (1 bit) records whether this is a JSON object or array. stateTypeMask stateEntry = 0x8000_0000_0000_0000 stateTypeObject stateEntry = 0x8000_0000_0000_0000 stateTypeArray stateEntry = 0x0000_0000_0000_0000 // The name check mask (2 bit) records whether to update // the namespaces for the current JSON object and // whether the namespace is valid. stateNamespaceMask stateEntry = 0x6000_0000_0000_0000 stateDisableNamespace stateEntry = 0x4000_0000_0000_0000 stateInvalidNamespace stateEntry = 0x2000_0000_0000_0000 // The count mask (61 bits) records the number of elements. stateCountMask stateEntry = 0x1fff_ffff_ffff_ffff stateCountLSBMask stateEntry = 0x0000_0000_0000_0001 stateCountOdd stateEntry = 0x0000_0000_0000_0001 stateCountEven stateEntry = 0x0000_0000_0000_0000 ) // length reports the number of elements in the JSON object or array. // Each name and value in an object entry is treated as a separate element. func (e stateEntry) length() int { return int(e & stateCountMask) } // isObject reports whether this is a JSON object. func (e stateEntry) isObject() bool { return e&stateTypeMask == stateTypeObject } // isArray reports whether this is a JSON array. func (e stateEntry) isArray() bool { return e&stateTypeMask == stateTypeArray } // needObjectName reports whether the next token must be a JSON string, // which is necessary for JSON object names. func (e stateEntry) needObjectName() bool { return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountEven } // needImplicitColon reports whether an colon should occur next, // which always occurs after JSON object names. func (e stateEntry) needImplicitColon() bool { return e.needObjectValue() } // needObjectValue reports whether the next token must be a JSON value, // which is necessary after every JSON object name. func (e stateEntry) needObjectValue() bool { return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountOdd } // needImplicitComma reports whether an comma should occur next, // which always occurs after a value in a JSON object or array // before the next value (or name). func (e stateEntry) needImplicitComma(next Kind) bool { return !e.needObjectValue() && e.length() > 0 && next != '}' && next != ']' } // increment increments the number of elements for the current object or array. // This assumes that overflow won't practically be an issue since // 1<<bits.OnesCount(stateCountMask) is sufficiently large. func (e *stateEntry) increment() { (*e)++ } // decrement decrements the number of elements for the current object or array. // It is the callers responsibility to ensure that e.length > 0. func (e *stateEntry) decrement() { (*e)-- } // disableNamespace disables the JSON object namespace such that the // Encoder or Decoder no longer updates the namespace. func (e *stateEntry) disableNamespace() { *e |= stateDisableNamespace } // isActiveNamespace reports whether the JSON object namespace is actively // being updated and used for duplicate name checks. func (e stateEntry) isActiveNamespace() bool { return e&(stateDisableNamespace) == 0 } // invalidateNamespace marks the JSON object namespace as being invalid. func (e *stateEntry) invalidateNamespace() { *e |= stateInvalidNamespace } // isValidNamespace reports whether the JSON object namespace is valid. func (e stateEntry) isValidNamespace() bool { return e&(stateInvalidNamespace) == 0 } // objectNameStack is a stack of names when descending into a JSON object. // In contrast to objectNamespaceStack, this only has to remember a single name // per JSON object. // // This data structure may contain offsets to encodeBuffer or decodeBuffer. // It violates clean abstraction of layers, but is significantly more efficient. // This ensures that popping and pushing in the common case is a trivial // push/pop of an offset integer. // // The zero value is an empty names stack ready for use. type objectNameStack struct { // offsets is a stack of offsets for each name. // A non-negative offset is the ending offset into the local names buffer. // A negative offset is the bit-wise inverse of a starting offset into // a remote buffer (e.g., encodeBuffer or decodeBuffer). // A math.MinInt offset at the end implies that the last object is empty. // Invariant: Positive offsets always occur before negative offsets. offsets []int // unquotedNames is a back-to-back concatenation of names. unquotedNames []byte } func (ns *objectNameStack) reset() { ns.offsets = ns.offsets[:0] ns.unquotedNames = ns.unquotedNames[:0] if cap(ns.offsets) > 1<<6 { ns.offsets = nil // avoid pinning arbitrarily large amounts of memory } if cap(ns.unquotedNames) > 1<<10 { ns.unquotedNames = nil // avoid pinning arbitrarily large amounts of memory } } func (ns *objectNameStack) length() int { return len(ns.offsets) } // getUnquoted retrieves the ith unquoted name in the namespace. // It returns an empty string if the last object is empty. // // Invariant: Must call copyQuotedBuffer beforehand. func (ns *objectNameStack) getUnquoted(i int) []byte { ns.ensureCopiedBuffer() if i == 0 { return ns.unquotedNames[:ns.offsets[0]] } else { return ns.unquotedNames[ns.offsets[i-1]:ns.offsets[i-0]] } } // invalidOffset indicates that the last JSON object currently has no name. const invalidOffset = math.MinInt // push descends into a nested JSON object. func (ns *objectNameStack) push() { ns.offsets = append(ns.offsets, invalidOffset) } // replaceLastQuotedOffset replaces the last name with the starting offset // to the quoted name in some remote buffer. All offsets provided must be // relative to the same buffer until copyQuotedBuffer is called. func (ns *objectNameStack) replaceLastQuotedOffset(i int) { // Use bit-wise inversion instead of naive multiplication by -1 to avoid // ambiguity regarding zero (which is a valid offset into the names field). // Bit-wise inversion is mathematically equivalent to -i-1, // such that 0 becomes -1, 1 becomes -2, and so forth. // This ensures that remote offsets are always negative. ns.offsets[len(ns.offsets)-1] = ^i } // replaceLastUnquotedName replaces the last name with the provided name. // // Invariant: Must call copyQuotedBuffer beforehand. func (ns *objectNameStack) replaceLastUnquotedName(s string) { ns.ensureCopiedBuffer() var startOffset int if len(ns.offsets) > 1 { startOffset = ns.offsets[len(ns.offsets)-2] } ns.unquotedNames = append(ns.unquotedNames[:startOffset], s...) ns.offsets[len(ns.offsets)-1] = len(ns.unquotedNames) } // clearLast removes any name in the last JSON object. // It is semantically equivalent to ns.push followed by ns.pop. func (ns *objectNameStack) clearLast() { ns.offsets[len(ns.offsets)-1] = invalidOffset } // pop ascends out of a nested JSON object. func (ns *objectNameStack) pop() { ns.offsets = ns.offsets[:len(ns.offsets)-1] } // copyQuotedBuffer copies names from the remote buffer into the local names // buffer so that there are no more offset references into the remote buffer. // This allows the remote buffer to change contents without affecting // the names that this data structure is trying to remember. func (ns *objectNameStack) copyQuotedBuffer(b []byte) { // Find the first negative offset. var i int for i = len(ns.offsets) - 1; i >= 0 && ns.offsets[i] < 0; i-- { continue } // Copy each name from the remote buffer into the local buffer. for i = i + 1; i < len(ns.offsets); i++ { if i == len(ns.offsets)-1 && ns.offsets[i] == invalidOffset { if i == 0 { ns.offsets[i] = 0 } else { ns.offsets[i] = ns.offsets[i-1] } break // last JSON object had a push without any names } // As a form of Hyrum proofing, we write an invalid character into the // buffer to make misuse of Decoder.ReadToken more obvious. // We need to undo that mutation here. quotedName := b[^ns.offsets[i]:] if quotedName[0] == invalidateBufferByte { quotedName[0] = '"' } // Append the unquoted name to the local buffer. var startOffset int if i > 0 { startOffset = ns.offsets[i-1] } if n := consumeSimpleString(quotedName); n > 0 { ns.unquotedNames = append(ns.unquotedNames[:startOffset], quotedName[len(`"`):n-len(`"`)]...) } else { ns.unquotedNames, _ = unescapeString(ns.unquotedNames[:startOffset], quotedName) } ns.offsets[i] = len(ns.unquotedNames) } } func (ns *objectNameStack) ensureCopiedBuffer() { if len(ns.offsets) > 0 && ns.offsets[len(ns.offsets)-1] < 0 { panic("BUG: copyQuotedBuffer not called beforehand") } } // objectNamespaceStack is a stack of object namespaces. // This data structure assists in detecting duplicate names. type objectNamespaceStack []objectNamespace // reset resets the object namespace stack. func (nss *objectNamespaceStack) reset() { if cap(*nss) > 1<<10 { *nss = nil } *nss = (*nss)[:0] } // push starts a new namespace for a nested JSON object. func (nss *objectNamespaceStack) push() { if cap(*nss) > len(*nss) { *nss = (*nss)[:len(*nss)+1] nss.last().reset() } else { *nss = append(*nss, objectNamespace{}) } } // last returns a pointer to the last JSON object namespace. func (nss objectNamespaceStack) last() *objectNamespace { return &nss[len(nss)-1] } // pop terminates the namespace for a nested JSON object. func (nss *objectNamespaceStack) pop() { *nss = (*nss)[:len(*nss)-1] } // objectNamespace is the namespace for a JSON object. // In contrast to objectNameStack, this needs to remember a all names // per JSON object. // // The zero value is an empty namespace ready for use. type objectNamespace struct { // It relies on a linear search over all the names before switching // to use a Go map for direct lookup. // endOffsets is a list of offsets to the end of each name in buffers. // The length of offsets is the number of names in the namespace. endOffsets []uint // allUnquotedNames is a back-to-back concatenation of every name in the namespace. allUnquotedNames []byte // mapNames is a Go map containing every name in the namespace. // Only valid if non-nil. mapNames map[string]struct{} } // reset resets the namespace to be empty. func (ns *objectNamespace) reset() { ns.endOffsets = ns.endOffsets[:0] ns.allUnquotedNames = ns.allUnquotedNames[:0] ns.mapNames = nil if cap(ns.endOffsets) > 1<<6 { ns.endOffsets = nil // avoid pinning arbitrarily large amounts of memory } if cap(ns.allUnquotedNames) > 1<<10 { ns.allUnquotedNames = nil // avoid pinning arbitrarily large amounts of memory } } // length reports the number of names in the namespace. func (ns *objectNamespace) length() int { return len(ns.endOffsets) } // getUnquoted retrieves the ith unquoted name in the namespace. func (ns *objectNamespace) getUnquoted(i int) []byte { if i == 0 { return ns.allUnquotedNames[:ns.endOffsets[0]] } else { return ns.allUnquotedNames[ns.endOffsets[i-1]:ns.endOffsets[i-0]] } } // lastUnquoted retrieves the last name in the namespace. func (ns *objectNamespace) lastUnquoted() []byte { return ns.getUnquoted(ns.length() - 1) } // insertQuoted inserts a name and reports whether it was inserted, // which only occurs if name is not already in the namespace. // The provided name must be a valid JSON string. func (ns *objectNamespace) insertQuoted(name []byte, isVerbatim bool) bool { if isVerbatim { name = name[len(`"`) : len(name)-len(`"`)] } return ns.insert(name, !isVerbatim) } func (ns *objectNamespace) insertUnquoted(name []byte) bool { return ns.insert(name, false) } func (ns *objectNamespace) insert(name []byte, quoted bool) bool { var allNames []byte if quoted { allNames, _ = unescapeString(ns.allUnquotedNames, name) } else { allNames = append(ns.allUnquotedNames, name...) } name = allNames[len(ns.allUnquotedNames):] // Switch to a map if the buffer is too large for linear search. // This does not add the current name to the map. if ns.mapNames == nil && (ns.length() > 64 || len(ns.allUnquotedNames) > 1024) { ns.mapNames = make(map[string]struct{}) var startOffset uint for _, endOffset := range ns.endOffsets { name := ns.allUnquotedNames[startOffset:endOffset] ns.mapNames[string(name)] = struct{}{} // allocates a new string startOffset = endOffset } } if ns.mapNames == nil { // Perform linear search over the buffer to find matching names. // It provides O(n) lookup, but does not require any allocations. var startOffset uint for _, endOffset := range ns.endOffsets { if string(ns.allUnquotedNames[startOffset:endOffset]) == string(name) { return false } startOffset = endOffset } } else { // Use the map if it is populated. // It provides O(1) lookup, but requires a string allocation per name. if _, ok := ns.mapNames[string(name)]; ok { return false } ns.mapNames[string(name)] = struct{}{} // allocates a new string } ns.allUnquotedNames = allNames ns.endOffsets = append(ns.endOffsets, uint(len(ns.allUnquotedNames))) return true } // removeLast removes the last name in the namespace. func (ns *objectNamespace) removeLast() { if ns.mapNames != nil { delete(ns.mapNames, string(ns.lastUnquoted())) } if ns.length()-1 == 0 { ns.endOffsets = ns.endOffsets[:0] ns.allUnquotedNames = ns.allUnquotedNames[:0] } else { ns.endOffsets = ns.endOffsets[:ns.length()-1] ns.allUnquotedNames = ns.allUnquotedNames[:ns.endOffsets[ns.length()-1]] } } type uintSet64 uint64 func (s uintSet64) has(i uint) bool { return s&(1<<i) > 0 } func (s *uintSet64) set(i uint) { *s |= 1 << i } // uintSet is a set of unsigned integers. // It is optimized for most integers being close to zero. type uintSet struct { lo uintSet64 hi []uintSet64 } // has reports whether i is in the set. func (s *uintSet) has(i uint) bool { if i < 64 { return s.lo.has(i) } else { i -= 64 iHi, iLo := int(i/64), i%64 return iHi < len(s.hi) && s.hi[iHi].has(iLo) } } // insert inserts i into the set and reports whether it was the first insertion. func (s *uintSet) insert(i uint) bool { // TODO: Make this inlineable at least for the lower 64-bit case. if i < 64 { has := s.lo.has(i) s.lo.set(i) return !has } else { i -= 64 iHi, iLo := int(i/64), i%64 if iHi >= len(s.hi) { s.hi = append(s.hi, make([]uintSet64, iHi+1-len(s.hi))...) s.hi = s.hi[:cap(s.hi)] } has := s.hi[iHi].has(iLo) s.hi[iHi].set(iLo) return !has } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "errors" "fmt" "reflect" "sync" ) // SkipFunc may be returned by MarshalFuncV2 and UnmarshalFuncV2 functions. // // Any function that returns SkipFunc must not cause observable side effects // on the provided Encoder or Decoder. For example, it is permissible to call // Decoder.PeekKind, but not permissible to call Decoder.ReadToken or // Encoder.WriteToken since such methods mutate the state. const SkipFunc = jsonError("skip function") // Marshalers is a list of functions that may override the marshal behavior // of specific types. Populate MarshalOptions.Marshalers to use it. // A nil *Marshalers is equivalent to an empty list. type Marshalers = typedMarshalers // NewMarshalers constructs a flattened list of marshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. // If a function returns SkipFunc, then the next applicable function is called, // otherwise the default marshaling behavior is used. // // For example: // // m1 := NewMarshalers(f1, f2) // m2 := NewMarshalers(f0, m1, f3) // equivalent to m3 // m3 := NewMarshalers(f0, f1, f2, f3) // equivalent to m2 func NewMarshalers(ms ...*Marshalers) *Marshalers { return newMarshalers(ms...) } // Unmarshalers is a list of functions that may override the unmarshal behavior // of specific types. Populate UnmarshalOptions.Unmarshalers to use it. // A nil *Unmarshalers is equivalent to an empty list. type Unmarshalers = typedUnmarshalers // NewUnmarshalers constructs a flattened list of unmarshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. // If a function returns SkipFunc, then the next applicable function is called, // otherwise the default unmarshaling behavior is used. // // For example: // // u1 := NewUnmarshalers(f1, f2) // u2 := NewUnmarshalers(f0, u1, f3) // equivalent to u3 // u3 := NewUnmarshalers(f0, f1, f2, f3) // equivalent to u2 func NewUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newUnmarshalers(us...) } type typedMarshalers = typedArshalers[MarshalOptions, Encoder] type typedUnmarshalers = typedArshalers[UnmarshalOptions, Decoder] type typedArshalers[Options, Coder any] struct { nonComparable fncVals []typedArshaler[Options, Coder] fncCache sync.Map // map[reflect.Type]arshaler // fromAny reports whether any of Go types used to represent arbitrary JSON // (i.e., any, bool, string, float64, map[string]any, or []any) matches // any of the provided type-specific arshalers. // // This bit of information is needed in arshal_default.go to determine // whether to use the specialized logic in arshal_any.go to handle // the any interface type. The logic in arshal_any.go does not support // type-specific arshal functions, so we must avoid using that logic // if this is true. fromAny bool } type typedMarshaler = typedArshaler[MarshalOptions, Encoder] type typedUnmarshaler = typedArshaler[UnmarshalOptions, Decoder] type typedArshaler[Options, Coder any] struct { typ reflect.Type fnc func(Options, *Coder, addressableValue) error maySkip bool } func newMarshalers(ms ...*Marshalers) *Marshalers { return newTypedArshalers(ms...) } func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) } func newTypedArshalers[Options, Coder any](as ...*typedArshalers[Options, Coder]) *typedArshalers[Options, Coder] { var a typedArshalers[Options, Coder] for _, a2 := range as { if a2 != nil { a.fncVals = append(a.fncVals, a2.fncVals...) a.fromAny = a.fromAny || a2.fromAny } } if len(a.fncVals) == 0 { return nil } return &a } func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addressableValue) error, t reflect.Type) (func(Options, *Coder, addressableValue) error, bool) { if a == nil { return fnc, false } if v, ok := a.fncCache.Load(t); ok { if v == nil { return fnc, false } return v.(func(Options, *Coder, addressableValue) error), true } // Collect a list of arshalers that can be called for this type. // This list may be longer than 1 since some arshalers can be skipped. var fncs []func(Options, *Coder, addressableValue) error for _, fncVal := range a.fncVals { if !castableTo(t, fncVal.typ) { continue } fncs = append(fncs, fncVal.fnc) if !fncVal.maySkip { break // subsequent arshalers will never be called } } if len(fncs) == 0 { a.fncCache.Store(t, nil) // nil to indicate that no funcs found return fnc, false } // Construct an arshaler that may call every applicable arshaler. fncDefault := fnc fnc = func(o Options, c *Coder, v addressableValue) error { for _, fnc := range fncs { if err := fnc(o, c, v); err != SkipFunc { return err // may be nil or non-nil } } return fncDefault(o, c, v) } // Use the first stored so duplicate work can be garbage collected. v, _ := a.fncCache.LoadOrStore(t, fnc) return v.(func(Options, *Coder, addressableValue) error), true } // MarshalFuncV1 constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value // if T is an interface or pointer type. // // The function must marshal exactly one JSON value. // The value of T must not be retained outside the function call. // It may not return SkipFunc. func MarshalFuncV1[T any](fn func(T) ([]byte, error)) *Marshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { val, err := fn(va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "marshal function of type func(T) ([]byte, error)") // TODO: Avoid wrapping semantic errors. return &SemanticError{action: "marshal", GoType: t, Err: err} } if err := enc.WriteValue(val); err != nil { // TODO: Avoid wrapping semantic or I/O errors. return &SemanticError{action: "marshal", JSONKind: RawValue(val).Kind(), GoType: t, Err: err} } return nil }, } return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } // MarshalFuncV2 constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value // if T is an interface or pointer type. // // The function must marshal exactly one JSON value by calling write methods // on the provided encoder. It may return SkipFunc such that marshaling can // move on to the next marshal function. However, no mutable method calls may // be called on the encoder if SkipFunc is returned. // The pointer to Encoder and the value of T must not be retained // outside the function call. func MarshalFuncV2[T any](fn func(MarshalOptions, *Encoder, T) error) *Marshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { prevDepth, prevLength := enc.tokens.depthLength() err := fn(mo, enc, va.castTo(t).Interface().(T)) currDepth, currLength := enc.tokens.depthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { err = errors.New("must write exactly one JSON value") } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } err = errors.New("must not write any JSON tokens when skipping") } // TODO: Avoid wrapping semantic or I/O errors. return &SemanticError{action: "marshal", GoType: t, Err: err} } return nil }, maySkip: true, } return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } // UnmarshalFuncV1 constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. // // The function must unmarshal exactly one JSON value. // The input []byte must not be mutated. // The input []byte and value T must not be retained outside the function call. // It may not return SkipFunc. func UnmarshalFuncV1[T any](fn func([]byte, T) error) *Unmarshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, fnc: func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { val, err := dec.ReadValue() if err != nil { return err // must be a syntactic or I/O error } err = fn(val, va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "unmarshal function of type func([]byte, T) error") // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} } return nil }, } return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)} } // UnmarshalFuncV2 constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. // // The function must unmarshal exactly one JSON value by calling read methods // on the provided decoder. It may return SkipFunc such that unmarshaling can // move on to the next unmarshal function. However, no mutable method calls may // be called on the decoder if SkipFunc is returned. // The pointer to Decoder and the value of T must not be retained // outside the function call. func UnmarshalFuncV2[T any](fn func(UnmarshalOptions, *Decoder, T) error) *Unmarshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, fnc: func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { prevDepth, prevLength := dec.tokens.depthLength() err := fn(uo, dec, va.castTo(t).Interface().(T)) currDepth, currLength := dec.tokens.depthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { err = errors.New("must read exactly one JSON value") } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } err = errors.New("must not read any JSON tokens when skipping") } // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", GoType: t, Err: err} } return nil }, maySkip: true, } return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)} } // assertCastableTo asserts that "to" is a valid type to be casted to. // These are the Go types that type-specific arshalers may operate upon. // // Let AllTypes be the universal set of all possible Go types. // This function generally asserts that: // // len([from for from in AllTypes if castableTo(from, to)]) > 0 // // otherwise it panics. // // As a special-case if marshal is false, then we forbid any non-pointer or // non-interface type since it is almost always a bug trying to unmarshal // into something where the end-user caller did not pass in an addressable value // since they will not observe the mutations. func assertCastableTo(to reflect.Type, marshal bool) { switch to.Kind() { case reflect.Interface: return case reflect.Pointer: // Only allow unnamed pointers to be consistent with the fact that // taking the address of a value produces an unnamed pointer type. if to.Name() == "" { return } default: // Technically, non-pointer types are permissible for unmarshal. // However, they are often a bug since the receiver would be immutable. // Thus, only allow them for marshaling. if marshal { return } } if marshal { panic(fmt.Sprintf("input type %v must be an interface type, an unnamed pointer type, or a non-pointer type", to)) } else { panic(fmt.Sprintf("input type %v must be an interface type or an unnamed pointer type", to)) } } // castableTo checks whether values of type "from" can be casted to type "to". // Nil pointer or interface "from" values are never considered castable. // // This function must be kept in sync with addressableValue.castTo. func castableTo(from, to reflect.Type) bool { switch to.Kind() { case reflect.Interface: // TODO: This breaks when ordinary interfaces can have type sets // since interfaces now exist where only the value form of a type (T) // implements the interface, but not the pointer variant (*T). // See https://go.dev/issue/45346. return reflect.PointerTo(from).Implements(to) case reflect.Pointer: // Common case for unmarshaling. // From must be a concrete or interface type. return reflect.PointerTo(from) == to default: // Common case for marshaling. // From must be a concrete type. return from == to } } // castTo casts va to the specified type. // If the type is an interface, then the underlying type will always // be a non-nil pointer to a concrete type. // // Requirement: castableTo(va.Type(), to) must hold. func (va addressableValue) castTo(to reflect.Type) reflect.Value { switch to.Kind() { case reflect.Interface: return va.Addr().Convert(to) case reflect.Pointer: return va.Addr() default: return va.Value } } // castableToFromAny reports whether "to" can be casted to from any // of the dynamic types used to represent arbitrary JSON. func castableToFromAny(to reflect.Type) bool { for _, from := range []reflect.Type{anyType, boolType, stringType, float64Type, mapStringAnyType, sliceAnyType} { if castableTo(from, to) { return true } } return false } func wrapSkipFunc(err error, what string) error { if err == SkipFunc { return errors.New(what + " cannot be skipped") } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "errors" "fmt" "reflect" "strings" "time" ) var ( timeDurationType = reflect.TypeOf((*time.Duration)(nil)).Elem() timeTimeType = reflect.TypeOf((*time.Time)(nil)).Elem() ) func makeTimeArshaler(fncs *arshaler, t reflect.Type) *arshaler { // Ideally, time types would implement MarshalerV2 and UnmarshalerV2, // but that would incur a dependency on package json from package time. // Given how widely used time is, it is more acceptable that we incur a // dependency on time from json. // // Injecting the arshaling functionality like this will not be identical // to actually declaring methods on the time types since embedding of the // time types will not be able to forward this functionality. switch t { case timeDurationType: fncs.nonDefault = true marshalNanos := fncs.marshal fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { if mo.format == "nanos" { mo.format = "" return marshalNanos(mo, enc, va) } else { return newInvalidFormatError("marshal", t, mo.format) } } td := va.Interface().(time.Duration) b := enc.UnusedBuffer() b = append(b, '"') b = append(b, td.String()...) // never contains special characters b = append(b, '"') return enc.WriteValue(b) } unmarshalNanos := fncs.unmarshal fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { // TODO: Should there be a flag that specifies that we can unmarshal // from either form since there would be no ambiguity? if uo.format != "" && uo.formatDepth == dec.tokens.depth() { if uo.format == "nanos" { uo.format = "" return unmarshalNanos(uo, dec, va) } else { return newInvalidFormatError("unmarshal", t, uo.format) } } var flags valueFlags td := va.Addr().Interface().(*time.Duration) val, err := dec.readValue(&flags) if err != nil { return err } switch k := val.Kind(); k { case 'n': *td = time.Duration(0) return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) td2, err := time.ParseDuration(string(val)) if err != nil { return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } *td = td2 return nil default: return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } } case timeTimeType: fncs.nonDefault = true fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { format := time.RFC3339Nano isRFC3339 := true if mo.format != "" && mo.formatDepth == enc.tokens.depth() { var err error format, isRFC3339, err = checkTimeFormat(mo.format) if err != nil { return &SemanticError{action: "marshal", GoType: t, Err: err} } } tt := va.Interface().(time.Time) b := enc.UnusedBuffer() b = append(b, '"') b = tt.AppendFormat(b, format) b = append(b, '"') if isRFC3339 { // Not all Go timestamps can be represented as valid RFC 3339. // Explicitly check for these edge cases. // See https://go.dev/issue/4556 and https://go.dev/issue/54580. var err error switch b := b[len(`"`) : len(b)-len(`"`)]; { case b[len("9999")] != '-': // year must be exactly 4 digits wide err = errors.New("year outside of range [0,9999]") case b[len(b)-1] != 'Z': c := b[len(b)-len("Z07:00")] if ('0' <= c && c <= '9') || parseDec2(b[len(b)-len("07:00"):]) >= 24 { err = errors.New("timezone hour outside of range [0,23]") } } if err != nil { return &SemanticError{action: "marshal", GoType: t, Err: err} } return enc.WriteValue(b) // RFC 3339 never needs JSON escaping } // The format may contain special characters that need escaping. // Verify that the result is a valid JSON string (common case), // otherwise escape the string correctly (slower case). if consumeSimpleString(b) != len(b) { b, _ = appendString(nil, string(b[len(`"`):len(b)-len(`"`)]), true, nil) } return enc.WriteValue(b) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { format := time.RFC3339 isRFC3339 := true if uo.format != "" && uo.formatDepth == dec.tokens.depth() { var err error format, isRFC3339, err = checkTimeFormat(uo.format) if err != nil { return &SemanticError{action: "unmarshal", GoType: t, Err: err} } } var flags valueFlags tt := va.Addr().Interface().(*time.Time) val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': *tt = time.Time{} return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) tt2, err := time.Parse(format, string(val)) if isRFC3339 && err == nil { // TODO(https://go.dev/issue/54580): RFC 3339 specifies // the exact grammar of a valid timestamp. However, // the parsing functionality in "time" is too loose and // incorrectly accepts invalid timestamps as valid. // Remove these manual checks when "time" checks it for us. newParseError := func(layout, value, layoutElem, valueElem, message string) error { return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message} } switch { case val[len("2006-01-02T")+1] == ':': // hour must be two digits err = newParseError(format, string(val), "15", string(val[len("2006-01-02T"):][:1]), "") case val[len("2006-01-02T15:04:05")] == ',': // sub-second separator must be a period err = newParseError(format, string(val), ".", ",", "") case val[len(val)-1] != 'Z': switch { case parseDec2(val[len(val)-len("07:00"):]) >= 24: // timezone hour must be in range err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone hour out of range") case parseDec2(val[len(val)-len("00"):]) >= 60: // timezone minute must be in range err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone minute out of range") } } } if err != nil { return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } *tt = tt2 return nil default: return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } } } return fncs } func checkTimeFormat(format string) (string, bool, error) { // We assume that an exported constant in the time package will // always start with an uppercase ASCII letter. if len(format) > 0 && 'A' <= format[0] && format[0] <= 'Z' { switch format { case "ANSIC": return time.ANSIC, false, nil case "UnixDate": return time.UnixDate, false, nil case "RubyDate": return time.RubyDate, false, nil case "RFC822": return time.RFC822, false, nil case "RFC822Z": return time.RFC822Z, false, nil case "RFC850": return time.RFC850, false, nil case "RFC1123": return time.RFC1123, false, nil case "RFC1123Z": return time.RFC1123Z, false, nil case "RFC3339": return time.RFC3339, true, nil case "RFC3339Nano": return time.RFC3339Nano, true, nil case "Kitchen": return time.Kitchen, false, nil case "Stamp": return time.Stamp, false, nil case "StampMilli": return time.StampMilli, false, nil case "StampMicro": return time.StampMicro, false, nil case "StampNano": return time.StampNano, false, nil default: // Reject any format that is an exported Go identifier in case // new format constants are added to the time package. if strings.TrimFunc(format, isLetterOrDigit) == "" { return "", false, fmt.Errorf("undefined format layout: %v", format) } } } return format, false, nil } // parseDec2 parses b as an unsigned, base-10, 2-digit number. // It panics if len(b) < 2. The result is undefined if digits are not base-10. func parseDec2(b []byte) byte { return 10*(b[0]-'0') + (b[1] - '0') }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "io" "math" "math/bits" "strconv" "unicode/utf16" "unicode/utf8" ) // EncodeOptions configures how JSON encoding operates. // The zero value is equivalent to the default settings, // which is compliant with both RFC 7493 and RFC 8259. type EncodeOptions struct { requireKeyedLiterals nonComparable // multiline specifies whether the encoder should emit multiline output. multiline bool // omitTopLevelNewline specifies whether to omit the newline // that is appended after every top-level JSON value when streaming. omitTopLevelNewline bool // AllowDuplicateNames specifies that JSON objects may contain // duplicate member names. Disabling the duplicate name check may provide // performance benefits, but breaks compliance with RFC 7493, section 2.3. // The output will still be compliant with RFC 8259, // which leaves the handling of duplicate names as unspecified behavior. AllowDuplicateNames bool // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, // which will be mangled as the Unicode replacement character, U+FFFD. // This causes the encoder to break compliance with // RFC 7493, section 2.1, and RFC 8259, section 8.1. AllowInvalidUTF8 bool // preserveRawStrings specifies that WriteToken and WriteValue should not // reformat any JSON string, but keep the formatting verbatim. preserveRawStrings bool // canonicalizeNumbers specifies that WriteToken and WriteValue should // reformat any JSON numbers according to RFC 8785, section 3.2.2.3. canonicalizeNumbers bool // EscapeRune reports whether the provided character should be escaped // as a hexadecimal Unicode codepoint (e.g., \ufffd). // If nil, the shortest and simplest encoding will be used, // which is also the formatting specified by RFC 8785, section 3.2.2.2. EscapeRune func(rune) bool // Indent (if non-empty) specifies that the encoder should emit multiline // output where each element in a JSON object or array begins on a new, // indented line beginning with the indent prefix followed by one or more // copies of indent according to the indentation nesting. // It may only be composed of space or tab characters. Indent string // IndentPrefix is prepended to each line within a JSON object or array. // The purpose of the indent prefix is to encode data that can more easily // be embedded inside other formatted JSON data. // It may only be composed of space or tab characters. // It is ignored if Indent is empty. IndentPrefix string } // Encoder is a streaming encoder from raw JSON tokens and values. // It is used to write a stream of top-level JSON values, // each terminated with a newline character. // // WriteToken and WriteValue calls may be interleaved. // For example, the following JSON value: // // {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} // // can be composed with the following calls (ignoring errors for brevity): // // e.WriteToken(ObjectStart) // { // e.WriteToken(String("name")) // "name" // e.WriteToken(String("value")) // "value" // e.WriteValue(RawValue(`"array"`)) // "array" // e.WriteToken(ArrayStart) // [ // e.WriteToken(Null) // null // e.WriteToken(False) // false // e.WriteValue(RawValue("true")) // true // e.WriteToken(Float(3.14159)) // 3.14159 // e.WriteToken(ArrayEnd) // ] // e.WriteValue(RawValue(`"object"`)) // "object" // e.WriteValue(RawValue(`{"k":"v"}`)) // {"k":"v"} // e.WriteToken(ObjectEnd) // } // // The above is one of many possible sequence of calls and // may not represent the most sensible method to call for any given token/value. // For example, it is probably more common to call WriteToken with a string // for object names. type Encoder struct { state encodeBuffer options EncodeOptions seenPointers seenPointers // only used when marshaling } // encodeBuffer is a buffer split into 2 segments: // // - buf[0:len(buf)] // written (but unflushed) portion of the buffer // - buf[len(buf):cap(buf)] // unused portion of the buffer type encodeBuffer struct { buf []byte // may alias wr if it is a bytes.Buffer // baseOffset is added to len(buf) to obtain the absolute offset // relative to the start of io.Writer stream. baseOffset int64 wr io.Writer // maxValue is the approximate maximum RawValue size passed to WriteValue. maxValue int // unusedCache is the buffer returned by the UnusedBuffer method. unusedCache []byte // bufStats is statistics about buffer utilization. // It is only used with pooled encoders in pools.go. bufStats bufferStatistics } // NewEncoder constructs a new streaming encoder writing to w. func NewEncoder(w io.Writer) *Encoder { return EncodeOptions{}.NewEncoder(w) } // NewEncoder constructs a new streaming encoder writing to w // configured with the provided options. // It flushes the internal buffer when the buffer is sufficiently full or // when a top-level value has been written. // // If w is a bytes.Buffer, then the encoder appends directly into the buffer // without copying the contents from an intermediate buffer. func (o EncodeOptions) NewEncoder(w io.Writer) *Encoder { e := new(Encoder) o.ResetEncoder(e, w) return e } // ResetEncoder resets an encoder such that it is writing afresh to w and // configured with the provided options. func (o EncodeOptions) ResetEncoder(e *Encoder, w io.Writer) { if e == nil { panic("json: invalid nil Encoder") } if w == nil { panic("json: invalid nil io.Writer") } e.reset(nil, w, o) } func (e *Encoder) reset(b []byte, w io.Writer, o EncodeOptions) { if len(o.Indent) > 0 { o.multiline = true if s := trimLeftSpaceTab(o.IndentPrefix); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") } if s := trimLeftSpaceTab(o.Indent); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") } } e.state.reset() e.encodeBuffer = encodeBuffer{buf: b, wr: w, bufStats: e.bufStats} e.options = o if bb, ok := w.(*bytes.Buffer); ok && bb != nil { e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb } } // Reset resets an encoder such that it is writing afresh to w but // keeps any pre-existing encoder options. func (e *Encoder) Reset(w io.Writer) { e.options.ResetEncoder(e, w) } // needFlush determines whether to flush at this point. func (e *Encoder) needFlush() bool { // NOTE: This function is carefully written to be inlineable. // Avoid flushing if e.wr is nil since there is no underlying writer. // Flush if less than 25% of the capacity remains. // Flushing at some constant fraction ensures that the buffer stops growing // so long as the largest Token or Value fits within that unused capacity. return e.wr != nil && (e.tokens.depth() == 1 || len(e.buf) > 3*cap(e.buf)/4) } // flush flushes the buffer to the underlying io.Writer. // It may append a trailing newline after the top-level value. func (e *Encoder) flush() error { if e.wr == nil || e.avoidFlush() { return nil } // In streaming mode, always emit a newline after the top-level value. if e.tokens.depth() == 1 && !e.options.omitTopLevelNewline { e.buf = append(e.buf, '\n') } // Inform objectNameStack that we are about to flush the buffer content. e.names.copyQuotedBuffer(e.buf) // Specialize bytes.Buffer for better performance. if bb, ok := e.wr.(*bytes.Buffer); ok { // If e.buf already aliases the internal buffer of bb, // then the Write call simply increments the internal offset, // otherwise Write operates as expected. // See https://go.dev/issue/42986. n, _ := bb.Write(e.buf) // never fails unless bb is nil e.baseOffset += int64(n) // If the internal buffer of bytes.Buffer is too small, // append operations elsewhere in the Encoder may grow the buffer. // This would be semantically correct, but hurts performance. // As such, ensure 25% of the current length is always available // to reduce the probability that other appends must allocate. if avail := bb.Cap() - bb.Len(); avail < bb.Len()/4 { bb.Grow(avail + 1) } e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb return nil } // Flush the internal buffer to the underlying io.Writer. n, err := e.wr.Write(e.buf) e.baseOffset += int64(n) if err != nil { // In the event of an error, preserve the unflushed portion. // Thus, write errors aren't fatal so long as the io.Writer // maintains consistent state after errors. if n > 0 { e.buf = e.buf[:copy(e.buf, e.buf[n:])] } return &ioError{action: "write", err: err} } e.buf = e.buf[:0] // Check whether to grow the buffer. // Note that cap(e.buf) may already exceed maxBufferSize since // an append elsewhere already grew it to store a large token. const maxBufferSize = 4 << 10 const growthSizeFactor = 2 // higher value is faster const growthRateFactor = 2 // higher value is slower // By default, grow if below the maximum buffer size. grow := cap(e.buf) <= maxBufferSize/growthSizeFactor // Growing can be expensive, so only grow // if a sufficient number of bytes have been processed. grow = grow && int64(cap(e.buf)) < e.previousOffsetEnd()/growthRateFactor if grow { e.buf = make([]byte, 0, cap(e.buf)*growthSizeFactor) } return nil } func (e *encodeBuffer) previousOffsetEnd() int64 { return e.baseOffset + int64(len(e.buf)) } func (e *encodeBuffer) unflushedBuffer() []byte { return e.buf } // avoidFlush indicates whether to avoid flushing to ensure there is always // enough in the buffer to unwrite the last object member if it were empty. func (e *Encoder) avoidFlush() bool { switch { case e.tokens.last.length() == 0: // Never flush after ObjectStart or ArrayStart since we don't know yet // if the object or array will end up being empty. return true case e.tokens.last.needObjectValue(): // Never flush before the object value since we don't know yet // if the object value will end up being empty. return true case e.tokens.last.needObjectName() && len(e.buf) >= 2: // Never flush after the object value if it does turn out to be empty. switch string(e.buf[len(e.buf)-2:]) { case `ll`, `""`, `{}`, `[]`: // last two bytes of every empty value return true } } return false } // unwriteEmptyObjectMember unwrites the last object member if it is empty // and reports whether it performed an unwrite operation. func (e *Encoder) unwriteEmptyObjectMember(prevName *string) bool { if last := e.tokens.last; !last.isObject() || !last.needObjectName() || last.length() == 0 { panic("BUG: must be called on an object after writing a value") } // The flushing logic is modified to never flush a trailing empty value. // The encoder never writes trailing whitespace eagerly. b := e.unflushedBuffer() // Detect whether the last value was empty. var n int if len(b) >= 3 { switch string(b[len(b)-2:]) { case "ll": // last two bytes of `null` n = len(`null`) case `""`: // It is possible for a non-empty string to have `""` as a suffix // if the second to the last quote was escaped. if b[len(b)-3] == '\\' { return false // e.g., `"\""` is not empty } n = len(`""`) case `{}`: n = len(`{}`) case `[]`: n = len(`[]`) } } if n == 0 { return false } // Unwrite the value, whitespace, colon, name, whitespace, and comma. b = b[:len(b)-n] b = trimSuffixWhitespace(b) b = trimSuffixByte(b, ':') b = trimSuffixString(b) b = trimSuffixWhitespace(b) b = trimSuffixByte(b, ',') e.buf = b // store back truncated unflushed buffer // Undo state changes. e.tokens.last.decrement() // for object member value e.tokens.last.decrement() // for object member name if !e.options.AllowDuplicateNames { if e.tokens.last.isActiveNamespace() { e.namespaces.last().removeLast() } e.names.clearLast() if prevName != nil { e.names.copyQuotedBuffer(e.buf) // required by objectNameStack.replaceLastUnquotedName e.names.replaceLastUnquotedName(*prevName) } } return true } // unwriteOnlyObjectMemberName unwrites the only object member name // and returns the unquoted name. func (e *Encoder) unwriteOnlyObjectMemberName() string { if last := e.tokens.last; !last.isObject() || last.length() != 1 { panic("BUG: must be called on an object after writing first name") } // Unwrite the name and whitespace. b := trimSuffixString(e.buf) isVerbatim := bytes.IndexByte(e.buf[len(b):], '\\') < 0 name := string(unescapeStringMayCopy(e.buf[len(b):], isVerbatim)) e.buf = trimSuffixWhitespace(b) // Undo state changes. e.tokens.last.decrement() if !e.options.AllowDuplicateNames { if e.tokens.last.isActiveNamespace() { e.namespaces.last().removeLast() } e.names.clearLast() } return name } func trimSuffixWhitespace(b []byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. n := len(b) - 1 for n >= 0 && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { n-- } return b[:n+1] } func trimSuffixString(b []byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. if len(b) > 0 && b[len(b)-1] == '"' { b = b[:len(b)-1] } for len(b) >= 2 && !(b[len(b)-1] == '"' && b[len(b)-2] != '\\') { b = b[:len(b)-1] // trim all characters except an unescaped quote } if len(b) > 0 && b[len(b)-1] == '"' { b = b[:len(b)-1] } return b } func hasSuffixByte(b []byte, c byte) bool { // NOTE: The arguments and logic are kept simple to keep this inlineable. return len(b) > 0 && b[len(b)-1] == c } func trimSuffixByte(b []byte, c byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. if len(b) > 0 && b[len(b)-1] == c { return b[:len(b)-1] } return b } // WriteToken writes the next token and advances the internal write offset. // // The provided token kind must be consistent with the JSON grammar. // For example, it is an error to provide a number when the encoder // is expecting an object name (which is always a string), or // to provide an end object delimiter when the encoder is finishing an array. // If the provided token is invalid, then it reports a SyntacticError and // the internal state remains unchanged. func (e *Encoder) WriteToken(t Token) error { k := t.Kind() b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, k) if e.options.multiline { b = e.appendWhitespace(b, k) } // Append the token to the output and to the state machine. var err error switch k { case 'n': b = append(b, "null"...) err = e.tokens.appendLiteral() case 'f': b = append(b, "false"...) err = e.tokens.appendLiteral() case 't': b = append(b, "true"...) err = e.tokens.appendLiteral() case '"': n0 := len(b) // offset before calling t.appendString if b, err = t.appendString(b, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune); err != nil { break } if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} break } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } err = e.tokens.appendString() case '0': if b, err = t.appendNumber(b, e.options.canonicalizeNumbers); err != nil { break } err = e.tokens.appendNumber() case '{': b = append(b, '{') if err = e.tokens.pushObject(); err != nil { break } if !e.options.AllowDuplicateNames { e.names.push() e.namespaces.push() } case '}': b = append(b, '}') if err = e.tokens.popObject(); err != nil { break } if !e.options.AllowDuplicateNames { e.names.pop() e.namespaces.pop() } case '[': b = append(b, '[') err = e.tokens.pushArray() case ']': b = append(b, ']') err = e.tokens.popArray() default: return &SyntacticError{str: "invalid json.Token"} } if err != nil { return err } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } const ( rawIntNumber = -1 rawUintNumber = -2 ) // writeNumber is specialized version of WriteToken, but optimized for numbers. // As a special-case, if bits is -1 or -2, it will treat v as // the raw-encoded bits of an int64 or uint64, respectively. // It is only called from arshal_default.go. func (e *Encoder) writeNumber(v float64, bits int, quote bool) error { b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, '0') if e.options.multiline { b = e.appendWhitespace(b, '0') } if quote { // Append the value to the output. n0 := len(b) // offset before appending the number b = append(b, '"') switch bits { case rawIntNumber: b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) case rawUintNumber: b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) default: b = appendNumber(b, v, bits) } b = append(b, '"') // Escape the string if necessary. if e.options.EscapeRune != nil { b2 := append(e.unusedCache, b[n0+len(`"`):len(b)-len(`"`)]...) b, _ = appendString(b[:n0], string(b2), false, e.options.EscapeRune) e.unusedCache = b2[:0] } // Update the state machine. if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { return errInvalidNamespace } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { return &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } if err := e.tokens.appendString(); err != nil { return err } } else { switch bits { case rawIntNumber: b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) case rawUintNumber: b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) default: b = appendNumber(b, v, bits) } if err := e.tokens.appendNumber(); err != nil { return err } } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } // WriteValue writes the next raw value and advances the internal write offset. // The Encoder does not simply copy the provided value verbatim, but // parses it to ensure that it is syntactically valid and reformats it // according to how the Encoder is configured to format whitespace and strings. // // The provided value kind must be consistent with the JSON grammar // (see examples on Encoder.WriteToken). If the provided value is invalid, // then it reports a SyntacticError and the internal state remains unchanged. func (e *Encoder) WriteValue(v RawValue) error { e.maxValue |= len(v) // bitwise OR is a fast approximation of max k := v.Kind() b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, k) if e.options.multiline { b = e.appendWhitespace(b, k) } // Append the value the output. var err error v = v[consumeWhitespace(v):] n0 := len(b) // offset before calling e.reformatValue b, v, err = e.reformatValue(b, v, e.tokens.depth()) if err != nil { return err } v = v[consumeWhitespace(v):] if len(v) > 0 { return newInvalidCharacterError(v[0:], "after top-level value") } // Append the kind to the state machine. switch k { case 'n', 'f', 't': err = e.tokens.appendLiteral() case '"': if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} break } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } err = e.tokens.appendString() case '0': err = e.tokens.appendNumber() case '{': if err = e.tokens.pushObject(); err != nil { break } if err = e.tokens.popObject(); err != nil { panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) } case '[': if err = e.tokens.pushArray(); err != nil { break } if err = e.tokens.popArray(); err != nil { panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) } } if err != nil { return err } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } // appendWhitespace appends whitespace that immediately precedes the next token. func (e *Encoder) appendWhitespace(b []byte, next Kind) []byte { if e.tokens.needDelim(next) == ':' { return append(b, ' ') } else { return e.appendIndent(b, e.tokens.needIndent(next)) } } // appendIndent appends the appropriate number of indentation characters // for the current nested level, n. func (e *Encoder) appendIndent(b []byte, n int) []byte { if n == 0 { return b } b = append(b, '\n') b = append(b, e.options.IndentPrefix...) for ; n > 1; n-- { b = append(b, e.options.Indent...) } return b } // reformatValue parses a JSON value from the start of src and // appends it to the end of dst, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatValue(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // TODO: Should this update valueFlags as input? if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } var n int var err error switch k := Kind(src[0]).normalize(); k { case 'n': if n = consumeNull(src); n == 0 { n, err = consumeLiteral(src, "null") } case 'f': if n = consumeFalse(src); n == 0 { n, err = consumeLiteral(src, "false") } case 't': if n = consumeTrue(src); n == 0 { n, err = consumeLiteral(src, "true") } case '"': if n := consumeSimpleString(src); n > 0 && e.options.EscapeRune == nil { dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim return dst, src, nil } return reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) case '0': if n := consumeSimpleNumber(src); n > 0 && !e.options.canonicalizeNumbers { dst, src = append(dst, src[:n]...), src[n:] // copy simple numbers verbatim return dst, src, nil } return reformatNumber(dst, src, e.options.canonicalizeNumbers) case '{': return e.reformatObject(dst, src, depth) case '[': return e.reformatArray(dst, src, depth) default: return dst, src, newInvalidCharacterError(src, "at start of value") } if err != nil { return dst, src, err } dst, src = append(dst, src[:n]...), src[n:] return dst, src, nil } // reformatObject parses a JSON object from the start of src and // appends it to the end of src, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatObject(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // Append object start. if src[0] != '{' { panic("BUG: reformatObject must be called with a buffer that starts with '{'") } dst, src = append(dst, '{'), src[1:] // Append (possible) object end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] == '}' { dst, src = append(dst, '}'), src[1:] return dst, src, nil } var err error var names *objectNamespace if !e.options.AllowDuplicateNames { e.namespaces.push() defer e.namespaces.pop() names = e.namespaces.last() } depth++ for { // Append optional newline and indentation. if e.options.multiline { dst = e.appendIndent(dst, depth) } // Append object name. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } n0 := len(dst) // offset before calling reformatString n := consumeSimpleString(src) if n > 0 && e.options.EscapeRune == nil { dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim } else { dst, src, err = reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) } if err != nil { return dst, src, err } if !e.options.AllowDuplicateNames && !names.insertQuoted(dst[n0:], false) { return dst, src, &SyntacticError{str: "duplicate name " + string(dst[n0:]) + " in object"} } // Append colon. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] != ':' { return dst, src, newInvalidCharacterError(src, "after object name (expecting ':')") } dst, src = append(dst, ':'), src[1:] if e.options.multiline { dst = append(dst, ' ') } // Append object value. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } dst, src, err = e.reformatValue(dst, src, depth) if err != nil { return dst, src, err } // Append comma or object end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } switch src[0] { case ',': dst, src = append(dst, ','), src[1:] continue case '}': if e.options.multiline { dst = e.appendIndent(dst, depth-1) } dst, src = append(dst, '}'), src[1:] return dst, src, nil default: return dst, src, newInvalidCharacterError(src, "after object value (expecting ',' or '}')") } } } // reformatArray parses a JSON array from the start of src and // appends it to the end of dst, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatArray(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // Append array start. if src[0] != '[' { panic("BUG: reformatArray must be called with a buffer that starts with '['") } dst, src = append(dst, '['), src[1:] // Append (possible) array end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] == ']' { dst, src = append(dst, ']'), src[1:] return dst, src, nil } var err error depth++ for { // Append optional newline and indentation. if e.options.multiline { dst = e.appendIndent(dst, depth) } // Append array value. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } dst, src, err = e.reformatValue(dst, src, depth) if err != nil { return dst, src, err } // Append comma or array end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } switch src[0] { case ',': dst, src = append(dst, ','), src[1:] continue case ']': if e.options.multiline { dst = e.appendIndent(dst, depth-1) } dst, src = append(dst, ']'), src[1:] return dst, src, nil default: return dst, src, newInvalidCharacterError(src, "after array value (expecting ',' or ']')") } } } // OutputOffset returns the current output byte offset. It gives the location // of the next byte immediately after the most recently written token or value. // The number of bytes actually written to the underlying io.Writer may be less // than this offset due to internal buffering effects. func (e *Encoder) OutputOffset() int64 { return e.previousOffsetEnd() } // UnusedBuffer returns a zero-length buffer with a possible non-zero capacity. // This buffer is intended to be used to populate a RawValue // being passed to an immediately succeeding WriteValue call. // // Example usage: // // b := d.UnusedBuffer() // b = append(b, '"') // b = appendString(b, v) // append the string formatting of v // b = append(b, '"') // ... := d.WriteValue(b) // // It is the user's responsibility to ensure that the value is valid JSON. func (e *Encoder) UnusedBuffer() []byte { // NOTE: We don't return e.buf[len(e.buf):cap(e.buf)] since WriteValue would // need to take special care to avoid mangling the data while reformatting. // WriteValue can't easily identify whether the input RawValue aliases e.buf // without using unsafe.Pointer. Thus, we just return a different buffer. // Should this ever alias e.buf, we need to consider how it operates with // the specialized performance optimization for bytes.Buffer. n := 1 << bits.Len(uint(e.maxValue|63)) // fast approximation for max length if cap(e.unusedCache) < n { e.unusedCache = make([]byte, 0, n) } return e.unusedCache } // StackDepth returns the depth of the state machine for written JSON data. // Each level on the stack represents a nested JSON object or array. // It is incremented whenever an ObjectStart or ArrayStart token is encountered // and decremented whenever an ObjectEnd or ArrayEnd token is encountered. // The depth is zero-indexed, where zero represents the top-level JSON value. func (e *Encoder) StackDepth() int { // NOTE: Keep in sync with Decoder.StackDepth. return e.tokens.depth() - 1 } // StackIndex returns information about the specified stack level. // It must be a number between 0 and StackDepth, inclusive. // For each level, it reports the kind: // // - 0 for a level of zero, // - '{' for a level representing a JSON object, and // - '[' for a level representing a JSON array. // // It also reports the length of that JSON object or array. // Each name and value in a JSON object is counted separately, // so the effective number of members would be half the length. // A complete JSON object must have an even length. func (e *Encoder) StackIndex(i int) (Kind, int) { // NOTE: Keep in sync with Decoder.StackIndex. switch s := e.tokens.index(i); { case i > 0 && s.isObject(): return '{', s.length() case i > 0 && s.isArray(): return '[', s.length() default: return 0, s.length() } } // StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value. // Object names are only present if AllowDuplicateNames is false, otherwise // object members are represented using their index within the object. func (e *Encoder) StackPointer() string { e.names.copyQuotedBuffer(e.buf) return string(e.appendStackPointer(nil)) } // appendString appends src to dst as a JSON string per RFC 7159, section 7. // // If validateUTF8 is specified, this rejects input that contains invalid UTF-8 // otherwise invalid bytes are replaced with the Unicode replacement character. // If escapeRune is provided, it specifies which runes to escape using // hexadecimal sequences. If nil, the shortest representable form is used, // which is also the canonical form for strings (RFC 8785, section 3.2.2.2). // // Note that this API allows full control over the formatting of strings // except for whether a forward solidus '/' may be formatted as '\/' and // the casing of hexadecimal Unicode escape sequences. func appendString(dst []byte, src string, validateUTF8 bool, escapeRune func(rune) bool) ([]byte, error) { appendEscapedASCII := func(dst []byte, c byte) []byte { switch c { case '"', '\\': dst = append(dst, '\\', c) case '\b': dst = append(dst, "\\b"...) case '\f': dst = append(dst, "\\f"...) case '\n': dst = append(dst, "\\n"...) case '\r': dst = append(dst, "\\r"...) case '\t': dst = append(dst, "\\t"...) default: dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(c)) } return dst } appendEscapedUnicode := func(dst []byte, r rune) []byte { if r1, r2 := utf16.EncodeRune(r); r1 != '\ufffd' && r2 != '\ufffd' { dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r1)) dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r2)) } else { dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r)) } return dst } // Optimize for when escapeRune is nil. if escapeRune == nil { var i, n int dst = append(dst, '"') for uint(len(src)) > uint(n) { // Handle single-byte ASCII. if c := src[n]; c < utf8.RuneSelf { n++ if c < ' ' || c == '"' || c == '\\' { dst = append(dst, src[i:n-1]...) dst = appendEscapedASCII(dst, c) i = n } continue } // Handle multi-byte Unicode. _, rn := utf8.DecodeRuneInString(src[n:])
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "errors" "reflect" ) // This package supports "inlining" a Go struct field, where the contents // of the serialized field (which must be a JSON object) are treated as if // they are part of the parent Go struct (which represents a JSON object). // // Generally, inlined fields are of a Go struct type, where the fields of the // nested struct are virtually hoisted up to the parent struct using rules // similar to how Go embedding works (but operating within the JSON namespace). // // However, inlined fields may also be of a Go map type with a string key // or a RawValue. Such inlined fields are called "fallback" fields since they // represent any arbitrary JSON object member. Explicitly named fields take // precedence over the inlined fallback. Only one inlined fallback is allowed. var rawValueType = reflect.TypeOf((*RawValue)(nil)).Elem() // marshalInlinedFallbackAll marshals all the members in an inlined fallback. func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableValue, f *structField, insertUnquotedName func([]byte) bool) error { v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable if len(f.index) > 1 { v = v.fieldByIndex(f.index[1:], false) if !v.IsValid() { return nil // implies a nil inlined field } } v = v.indirect(false) if !v.IsValid() { return nil } if v.Type() == rawValueType { b := v.Interface().(RawValue) if len(b) == 0 { // TODO: Should this be nil? What if it were all whitespace? return nil } dec := getBufferedDecoder(b, DecodeOptions{AllowDuplicateNames: true, AllowInvalidUTF8: true}) defer putBufferedDecoder(dec) tok, err := dec.ReadToken() if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if tok.Kind() != '{' { err := errors.New("inlined raw value must be a JSON object") return &SemanticError{action: "marshal", JSONKind: tok.Kind(), GoType: rawValueType, Err: err} } for dec.PeekKind() != '}' { // Parse the JSON object name. var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if insertUnquotedName != nil { name := unescapeStringMayCopy(val, flags.isVerbatim()) if !insertUnquotedName(name) { return &SyntacticError{str: "duplicate name " + string(val) + " in object"} } } if err := enc.WriteValue(val); err != nil { return err } // Parse the JSON object value. val, err = dec.readValue(&flags) if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if err := enc.WriteValue(val); err != nil { return err } } if _, err := dec.ReadToken(); err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if err := dec.checkEOF(); err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } return nil } else { m := v // must be a map[string]V n := m.Len() if n == 0 { return nil } mk := newAddressableValue(stringType) mv := newAddressableValue(m.Type().Elem()) marshalKey := func(mk addressableValue) error { b, err := appendString(enc.UnusedBuffer(), mk.String(), !enc.options.AllowInvalidUTF8, nil) if err != nil { return err } if insertUnquotedName != nil { isVerbatim := bytes.IndexByte(b, '\\') < 0 name := unescapeStringMayCopy(b, isVerbatim) if !insertUnquotedName(name) { return &SyntacticError{str: "duplicate name " + string(b) + " in object"} } } return enc.WriteValue(b) } marshalVal := f.fncs.marshal if mo.Marshalers != nil { marshalVal, _ = mo.Marshalers.lookup(marshalVal, mv.Type()) } if !mo.Deterministic || n <= 1 { for iter := m.MapRange(); iter.Next(); { mk.SetIterKey(iter) if err := marshalKey(mk); err != nil { return err } mv.Set(iter.Value()) if err := marshalVal(mo, enc, mv); err != nil { return err } } } else { names := getStrings(n) for i, iter := 0, m.Value.MapRange(); i < n && iter.Next(); i++ { mk.SetIterKey(iter) (*names)[i] = mk.String() } names.Sort() for _, name := range *names { mk.SetString(name) if err := marshalKey(mk); err != nil { return err } // TODO(https://go.dev/issue/57061): Use mv.SetMapIndexOf. mv.Set(m.MapIndex(mk.Value)) if err := marshalVal(mo, enc, mv); err != nil { return err } } putStrings(names) } return nil } } // unmarshalInlinedFallbackNext unmarshals only the next member in an inlined fallback. func unmarshalInlinedFallbackNext(uo UnmarshalOptions, dec *Decoder, va addressableValue, f *structField, quotedName, unquotedName []byte) error { v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable if len(f.index) > 1 { v = v.fieldByIndex(f.index[1:], true) } v = v.indirect(true) if v.Type() == rawValueType { b := v.Addr().Interface().(*RawValue) if len(*b) == 0 { // TODO: Should this be nil? What if it were all whitespace? *b = append(*b, '{') } else { *b = trimSuffixWhitespace(*b) if hasSuffixByte(*b, '}') { // TODO: When merging into an object for the first time, // should we verify that it is valid? *b = trimSuffixByte(*b, '}') *b = trimSuffixWhitespace(*b) if !hasSuffixByte(*b, ',') && !hasSuffixByte(*b, '{') { *b = append(*b, ',') } } else { err := errors.New("inlined raw value must be a JSON object") return &SemanticError{action: "unmarshal", GoType: rawValueType, Err: err} } } *b = append(*b, quotedName...) *b = append(*b, ':') rawValue, err := dec.ReadValue() if err != nil { return err } *b = append(*b, rawValue...) *b = append(*b, '}') return nil } else { name := string(unquotedName) // TODO: Intern this? m := v // must be a map[string]V if m.IsNil() { m.Set(reflect.MakeMap(m.Type())) } mk := reflect.ValueOf(name) mv := newAddressableValue(v.Type().Elem()) // TODO: Cache across calls? if v2 := m.MapIndex(mk); v2.IsValid() { mv.Set(v2) } unmarshal := f.fncs.unmarshal if uo.Unmarshalers != nil { unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, mv.Type()) } err := unmarshal(uo, dec, mv) m.SetMapIndex(mk, mv.Value) if err != nil { return err } return nil } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "errors" "io" "sort" "sync" "unicode/utf16" "unicode/utf8" ) // NOTE: RawValue is analogous to v1 json.RawMessage. // RawValue represents a single raw JSON value, which may be one of the following: // - a JSON literal (i.e., null, true, or false) // - a JSON string (e.g., "hello, world!") // - a JSON number (e.g., 123.456) // - an entire JSON object (e.g., {"fizz":"buzz"} ) // - an entire JSON array (e.g., [1,2,3] ) // // RawValue can represent entire array or object values, while Token cannot. // RawValue may contain leading and/or trailing whitespace. type RawValue []byte // Clone returns a copy of v. func (v RawValue) Clone() RawValue { if v == nil { return nil } return append(RawValue{}, v...) } // String returns the string formatting of v. func (v RawValue) String() string { if v == nil { return "null" } return string(v) } // IsValid reports whether the raw JSON value is syntactically valid // according to RFC 7493. // // It verifies whether the input is properly encoded as UTF-8, // that escape sequences within strings decode to valid Unicode codepoints, and // that all names in each object are unique. // It does not verify whether numbers are representable within the limits // of any common numeric type (e.g., float64, int64, or uint64). func (v RawValue) IsValid() bool { d := getBufferedDecoder(v, DecodeOptions{}) defer putBufferedDecoder(d) _, errVal := d.ReadValue() _, errEOF := d.ReadToken() return errVal == nil && errEOF == io.EOF } // Compact removes all whitespace from the raw JSON value. // // It does not reformat JSON strings to use any other representation. // It is guaranteed to succeed if the input is valid. // If the value is already compacted, then the buffer is not mutated. func (v *RawValue) Compact() error { return v.reformat(false, false, "", "") } // Indent reformats the whitespace in the raw JSON value so that each element // in a JSON object or array begins on a new, indented line beginning with // prefix followed by one or more copies of indent according to the nesting. // The value does not begin with the prefix nor any indention, // to make it easier to embed inside other formatted JSON data. // // It does not reformat JSON strings to use any other representation. // It is guaranteed to succeed if the input is valid. // If the value is already indented properly, then the buffer is not mutated. func (v *RawValue) Indent(prefix, indent string) error { return v.reformat(false, true, prefix, indent) } // Canonicalize canonicalizes the raw JSON value according to the // JSON Canonicalization Scheme (JCS) as defined by RFC 8785 // where it produces a stable representation of a JSON value. // // The output stability is dependent on the stability of the application data // (see RFC 8785, Appendix E). It cannot produce stable output from // fundamentally unstable input. For example, if the JSON value // contains ephemeral data (e.g., a frequently changing timestamp), // then the value is still unstable regardless of whether this is called. // // Note that JCS treats all JSON numbers as IEEE 754 double precision numbers. // Any numbers with precision beyond what is representable by that form // will lose their precision when canonicalized. For example, integer values // beyond ±2⁡³ will lose their precision. It is recommended that // int64 and uint64 data types be represented as a JSON string. // // It is guaranteed to succeed if the input is valid. // If the value is already canonicalized, then the buffer is not mutated. func (v *RawValue) Canonicalize() error { return v.reformat(true, false, "", "") } // TODO: Instead of implementing the v1 Marshaler/Unmarshaler, // consider implementing the v2 versions instead. // MarshalJSON returns v as the JSON encoding of v. // It returns the stored value as the raw JSON output without any validation. // If v is nil, then this returns a JSON null. func (v RawValue) MarshalJSON() ([]byte, error) { // NOTE: This matches the behavior of v1 json.RawMessage.MarshalJSON. if v == nil { return []byte("null"), nil } return v, nil } // UnmarshalJSON sets v as the JSON encoding of b. // It stores a copy of the provided raw JSON input without any validation. func (v *RawValue) UnmarshalJSON(b []byte) error { // NOTE: This matches the behavior of v1 json.RawMessage.UnmarshalJSON. if v == nil { return errors.New("json.RawValue: UnmarshalJSON on nil pointer") } *v = append((*v)[:0], b...) return nil } // Kind returns the starting token kind. // For a valid value, this will never include '}' or ']'. func (v RawValue) Kind() Kind { if v := v[consumeWhitespace(v):]; len(v) > 0 { return Kind(v[0]).normalize() } return invalidKind } func (v *RawValue) reformat(canonical, multiline bool, prefix, indent string) error { var eo EncodeOptions if canonical { eo.AllowInvalidUTF8 = false // per RFC 8785, section 3.2.4 eo.AllowDuplicateNames = false // per RFC 8785, section 3.1 eo.canonicalizeNumbers = true // per RFC 8785, section 3.2.2.3 eo.EscapeRune = nil // per RFC 8785, section 3.2.2.2 eo.multiline = false // per RFC 8785, section 3.2.1 } else { if s := trimLeftSpaceTab(prefix); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") } if s := trimLeftSpaceTab(indent); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") } eo.AllowInvalidUTF8 = true eo.AllowDuplicateNames = true eo.preserveRawStrings = true eo.multiline = multiline // in case indent is empty eo.IndentPrefix = prefix eo.Indent = indent } eo.omitTopLevelNewline = true // Write the entire value to reformat all tokens and whitespace. e := getBufferedEncoder(eo) defer putBufferedEncoder(e) if err := e.WriteValue(*v); err != nil { return err } // For canonical output, we may need to reorder object members. if canonical { // Obtain a buffered encoder just to use its internal buffer as // a scratch buffer in reorderObjects for reordering object members. e2 := getBufferedEncoder(EncodeOptions{}) defer putBufferedEncoder(e2) // Disable redundant checks performed earlier during encoding. d := getBufferedDecoder(e.buf, DecodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true}) defer putBufferedDecoder(d) reorderObjects(d, &e2.buf) // per RFC 8785, section 3.2.3 } // Store the result back into the value if different. if !bytes.Equal(*v, e.buf) { *v = append((*v)[:0], e.buf...) } return nil } func trimLeftSpaceTab(s string) string { for i, r := range s { switch r { case ' ', '\t': default: return s[i:] } } return "" } type memberName struct { // name is the unescaped name. name []byte // before and after are byte offsets into Decoder.buf that represents // the entire name/value pair. It may contain leading commas. before, after int64 } var memberNamePool = sync.Pool{New: func() any { return new(memberNames) }} func getMemberNames() *memberNames { ns := memberNamePool.Get().(*memberNames) *ns = (*ns)[:0] return ns } func putMemberNames(ns *memberNames) { if cap(*ns) < 1<<10 { for i := range *ns { (*ns)[i] = memberName{} // avoid pinning name } memberNamePool.Put(ns) } } type memberNames []memberName func (m *memberNames) Len() int { return len(*m) } func (m *memberNames) Less(i, j int) bool { return lessUTF16((*m)[i].name, (*m)[j].name) } func (m *memberNames) Swap(i, j int) { (*m)[i], (*m)[j] = (*m)[j], (*m)[i] } // reorderObjects recursively reorders all object members in place // according to the ordering specified in RFC 8785, section 3.2.3. // // Pre-conditions: // - The value is valid (i.e., no decoder errors should ever occur). // - The value is compact (i.e., no whitespace is present). // - Initial call is provided a Decoder reading from the start of v. // // Post-conditions: // - Exactly one JSON value is read from the Decoder. // - All fully-parsed JSON objects are reordered by directly moving // the members in the value buffer. // // The runtime is approximately O(n·log(n)) + O(m·log(m)), // where n is len(v) and m is the total number of object members. func reorderObjects(d *Decoder, scratch *[]byte) { switch tok, _ := d.ReadToken(); tok.Kind() { case '{': // Iterate and collect the name and offsets for every object member. members := getMemberNames() defer putMemberNames(members) var prevName []byte isSorted := true beforeBody := d.InputOffset() // offset after '{' for d.PeekKind() != '}' { beforeName := d.InputOffset() var flags valueFlags name, _ := d.readValue(&flags) name = unescapeStringMayCopy(name, flags.isVerbatim()) reorderObjects(d, scratch) afterValue := d.InputOffset() if isSorted && len(*members) > 0 { isSorted = lessUTF16(prevName, []byte(name)) } *members = append(*members, memberName{name, beforeName, afterValue}) prevName = name } afterBody := d.InputOffset() // offset before '}' d.ReadToken() // Sort the members; return early if it's already sorted. if isSorted { return } // TODO(https://go.dev/issue/47619): Use slices.Sort. sort.Sort(members) // Append the reordered members to a new buffer, // then copy the reordered members back over the original members. // Avoid swapping in place since each member may be a different size // where moving a member over a smaller member may corrupt the data // for subsequent members before they have been moved. // // The following invariant must hold: // sum([m.after-m.before for m in members]) == afterBody-beforeBody sorted := (*scratch)[:0] for i, member := range *members { if d.buf[member.before] == ',' { member.before++ // trim leading comma } sorted = append(sorted, d.buf[member.before:member.after]...) if i < len(*members)-1 { sorted = append(sorted, ',') // append trailing comma } } if int(afterBody-beforeBody) != len(sorted) { panic("BUG: length invariant violated") } copy(d.buf[beforeBody:afterBody], sorted) // Update scratch buffer to the largest amount ever used. if len(sorted) > len(*scratch) { *scratch = sorted } case '[': for d.PeekKind() != ']' { reorderObjects(d, scratch) } d.ReadToken() } } // lessUTF16 reports whether x is lexicographically less than y according // to the UTF-16 codepoints of the UTF-8 encoded input strings. // This implements the ordering specified in RFC 8785, section 3.2.3. // The inputs must be valid UTF-8, otherwise this may panic. func lessUTF16[Bytes []byte | string](x, y Bytes) bool { // NOTE: This is an optimized, allocation-free implementation // of lessUTF16Simple in fuzz_test.go. FuzzLessUTF16 verifies that the // two implementations agree on the result of comparing any two strings. isUTF16Self := func(r rune) bool { return ('\u0000' <= r && r <= '\uD7FF') || ('\uE000' <= r && r <= '\uFFFF') } var invalidUTF8 bool x0, y0 := x, y for { if len(x) == 0 || len(y) == 0 { if len(x) == len(y) && invalidUTF8 { return string(x0) < string(y0) } return len(x) < len(y) } // ASCII fast-path. if x[0] < utf8.RuneSelf || y[0] < utf8.RuneSelf { if x[0] != y[0] { return x[0] < y[0] } x, y = x[1:], y[1:] continue } // Decode next pair of runes as UTF-8. // TODO(https://go.dev/issue/56948): Use a generic implementation // of utf8.DecodeRune, or rely on a compiler optimization to statically // hide the cost of a type switch (https://go.dev/issue/57072). var rx, ry rune var nx, ny int switch any(x).(type) { case string: rx, nx = utf8.DecodeRuneInString(string(x)) ry, ny = utf8.DecodeRuneInString(string(y)) case []byte: rx, nx = utf8.DecodeRune([]byte(x)) ry, ny = utf8.DecodeRune([]byte(y)) } selfx := isUTF16Self(rx) selfy := isUTF16Self(ry) switch { // The x rune is a single UTF-16 codepoint, while // the y rune is a surrogate pair of UTF-16 codepoints. case selfx && !selfy: ry, _ = utf16.EncodeRune(ry) // The y rune is a single UTF-16 codepoint, while // the x rune is a surrogate pair of UTF-16 codepoints. case selfy && !selfx: rx, _ = utf16.EncodeRune(rx) } if rx != ry { return rx < ry } invalidUTF8 = invalidUTF8 || (rx == utf8.RuneError && nx == 1) || (ry == utf8.RuneError && ny == 1) x, y = x[nx:], y[ny:] } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "io" "math/bits" "sort" "sync" ) // TODO(https://go.dev/issue/47657): Use sync.PoolOf. var ( // This owns the internal buffer since there is no io.Writer to output to. // Since the buffer can get arbitrarily large in normal usage, // there is statistical tracking logic to determine whether to recycle // the internal buffer or not based on a history of utilization. bufferedEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} // This owns the internal buffer, but it is only used to temporarily store // buffered JSON before flushing it to the underlying io.Writer. // In a sufficiently efficient streaming mode, we do not expect the buffer // to grow arbitrarily large. Thus, we avoid recycling large buffers. streamingEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} // This does not own the internal buffer since // it is taken directly from the provided bytes.Buffer. bytesBufferEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} ) // bufferStatistics is statistics to track buffer utilization. // It is used to determine whether to recycle a buffer or not // to avoid https://go.dev/issue/23199. type bufferStatistics struct { strikes int // number of times the buffer was under-utilized prevLen int // length of previous buffer } func getBufferedEncoder(o EncodeOptions) *Encoder { e := bufferedEncoderPool.Get().(*Encoder) if e.buf == nil { // Round up to nearest 2ⁿ to make best use of malloc size classes. // See runtime/sizeclasses.go on Go1.15. // Logical OR with 63 to ensure 64 as the minimum buffer size. n := 1 << bits.Len(uint(e.bufStats.prevLen|63)) e.buf = make([]byte, 0, n) } e.reset(e.buf[:0], nil, o) return e } func putBufferedEncoder(e *Encoder) { // Recycle large buffers only if sufficiently utilized. // If a buffer is under-utilized enough times sequentially, // then it is discarded, ensuring that a single large buffer // won't be kept alive by a continuous stream of small usages. // // The worst case utilization is computed as: // MIN_UTILIZATION_THRESHOLD / (1 + MAX_NUM_STRIKES) // // For the constants chosen below, this is (25%)/(1+4) β‡’ 5%. // This may seem low, but it ensures a lower bound on // the absolute worst-case utilization. Without this check, // this would be theoretically 0%, which is infinitely worse. // // See https://go.dev/issue/27735. switch { case cap(e.buf) <= 4<<10: // always recycle buffers smaller than 4KiB e.bufStats.strikes = 0 case cap(e.buf)/4 <= len(e.buf): // at least 25% utilization e.bufStats.strikes = 0 case e.bufStats.strikes < 4: // at most 4 strikes e.bufStats.strikes++ default: // discard the buffer; too large and too often under-utilized e.bufStats.strikes = 0 e.bufStats.prevLen = len(e.buf) // heuristic for size to allocate next time e.buf = nil } bufferedEncoderPool.Put(e) } func getStreamingEncoder(w io.Writer, o EncodeOptions) *Encoder { if _, ok := w.(*bytes.Buffer); ok { e := bytesBufferEncoderPool.Get().(*Encoder) e.reset(nil, w, o) // buffer taken from bytes.Buffer return e } else { e := streamingEncoderPool.Get().(*Encoder) e.reset(e.buf[:0], w, o) // preserve existing buffer return e } } func putStreamingEncoder(e *Encoder) { if _, ok := e.wr.(*bytes.Buffer); ok { bytesBufferEncoderPool.Put(e) } else { if cap(e.buf) > 64<<10 { e.buf = nil // avoid pinning arbitrarily large amounts of memory } streamingEncoderPool.Put(e) } } var ( // This does not own the internal buffer since it is externally provided. bufferedDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }} // This owns the internal buffer, but it is only used to temporarily store // buffered JSON fetched from the underlying io.Reader. // In a sufficiently efficient streaming mode, we do not expect the buffer // to grow arbitrarily large. Thus, we avoid recycling large buffers. streamingDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }} // This does not own the internal buffer since // it is taken directly from the provided bytes.Buffer. bytesBufferDecoderPool = bufferedDecoderPool ) func getBufferedDecoder(b []byte, o DecodeOptions) *Decoder { d := bufferedDecoderPool.Get().(*Decoder) d.reset(b, nil, o) return d } func putBufferedDecoder(d *Decoder) { bufferedDecoderPool.Put(d) } func getStreamingDecoder(r io.Reader, o DecodeOptions) *Decoder { if _, ok := r.(*bytes.Buffer); ok { d := bytesBufferDecoderPool.Get().(*Decoder) d.reset(nil, r, o) // buffer taken from bytes.Buffer return d } else { d := streamingDecoderPool.Get().(*Decoder) d.reset(d.buf[:0], r, o) // preserve existing buffer return d } } func putStreamingDecoder(d *Decoder) { if _, ok := d.rd.(*bytes.Buffer); ok { bytesBufferDecoderPool.Put(d) } else { if cap(d.buf) > 64<<10 { d.buf = nil // avoid pinning arbitrarily large amounts of memory } streamingDecoderPool.Put(d) } } var stringsPools = &sync.Pool{New: func() any { return new(stringSlice) }} type stringSlice []string // getStrings returns a non-nil pointer to a slice with length n. func getStrings(n int) *stringSlice { s := stringsPools.Get().(*stringSlice) if cap(*s) < n { *s = make([]string, n) } *s = (*s)[:n] return s } func putStrings(s *stringSlice) { if cap(*s) > 1<<10 { *s = nil // avoid pinning arbitrarily large amounts of memory } stringsPools.Put(s) } // Sort sorts the string slice according to RFC 8785, section 3.2.3. func (ss *stringSlice) Sort() { // TODO(https://go.dev/issue/47619): Use slices.SortFunc instead. sort.Sort(ss) } func (ss *stringSlice) Len() int { return len(*ss) } func (ss *stringSlice) Less(i, j int) bool { return lessUTF16((*ss)[i], (*ss)[j]) } func (ss *stringSlice) Swap(i, j int) { (*ss)[i], (*ss)[j] = (*ss)[j], (*ss)[i] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package json implements serialization of JSON // as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. // JSON is a simple data interchange format that can represent // primitive data types such as booleans, strings, and numbers, // in addition to structured data types such as objects and arrays. // // # Terminology // // This package uses the terms "encode" and "decode" for syntactic functionality // that is concerned with processing JSON based on its grammar, and // uses the terms "marshal" and "unmarshal" for semantic functionality // that determines the meaning of JSON values as Go values and vice-versa. // It aims to provide a clear distinction between functionality that // is purely concerned with encoding versus that of marshaling. // For example, one can directly encode a stream of JSON tokens without // needing to marshal a concrete Go value representing them. // Similarly, one can decode a stream of JSON tokens without // needing to unmarshal them into a concrete Go value. // // This package uses JSON terminology when discussing JSON, which may differ // from related concepts in Go or elsewhere in computing literature. // // - A JSON "object" refers to an unordered collection of name/value members. // - A JSON "array" refers to an ordered sequence of elements. // - A JSON "value" refers to either a literal (i.e., null, false, or true), // string, number, object, or array. // // See RFC 8259 for more information. // // # Specifications // // Relevant specifications include RFC 4627, RFC 7159, RFC 7493, RFC 8259, // and RFC 8785. Each RFC is generally a stricter subset of another RFC. // In increasing order of strictness: // // - RFC 4627 and RFC 7159 do not require (but recommend) the use of UTF-8 // and also do not require (but recommend) that object names be unique. // - RFC 8259 requires the use of UTF-8, // but does not require (but recommends) that object names be unique. // - RFC 7493 requires the use of UTF-8 // and also requires that object names be unique. // - RFC 8785 defines a canonical representation. It requires the use of UTF-8 // and also requires that object names be unique and in a specific ordering. // It specifies exactly how strings and numbers must be formatted. // // The primary difference between RFC 4627 and RFC 7159 is that the former // restricted top-level values to only JSON objects and arrays, while // RFC 7159 and subsequent RFCs permit top-level values to additionally be // JSON nulls, booleans, strings, or numbers. // // By default, this package operates on RFC 7493, but can be configured // to operate according to the other RFC specifications. // RFC 7493 is a stricter subset of RFC 8259 and fully compliant with it. // In particular, it makes specific choices about behavior that RFC 8259 // leaves as undefined in order to ensure greater interoperability. // // # JSON Representation of Go structs // // A Go struct is naturally represented as a JSON object, // where each Go struct field corresponds with a JSON object member. // When marshaling, all Go struct fields are recursively encoded in depth-first // order as JSON object members except those that are ignored or omitted. // When unmarshaling, JSON object members are recursively decoded // into the corresponding Go struct fields. // Object members that do not match any struct fields, // also known as β€œunknown members”, are ignored by default or rejected // if UnmarshalOptions.RejectUnknownMembers is specified. // // The representation of each struct field can be customized in the // "json" struct field tag, where the tag is a comma separated list of options. // As a special case, if the entire tag is `json:"-"`, // then the field is ignored with regard to its JSON representation. // // The first option is the JSON object name override for the Go struct field. // If the name is not specified, then the Go struct field name // is used as the JSON object name. JSON names containing commas or quotes, // or names identical to "" or "-", can be specified using // a single-quoted string literal, where the syntax is identical to // the Go grammar for a double-quoted string literal, // but instead uses single quotes as the delimiters. // By default, unmarshaling uses case-sensitive matching to identify // the Go struct field associated with a JSON object name. // // After the name, the following tag options are supported: // // - omitzero: When marshaling, the "omitzero" option specifies that // the struct field should be omitted if the field value is zero // as determined by the "IsZero() bool" method if present, // otherwise based on whether the field is the zero Go value. // This option has no effect when unmarshaling. // // - omitempty: When marshaling, the "omitempty" option specifies that // the struct field should be omitted if the field value would have been // encoded as a JSON null, empty string, empty object, or empty array. // This option has no effect when unmarshaling. // // - string: The "string" option specifies that // MarshalOptions.StringifyNumbers and UnmarshalOptions.StringifyNumbers // be set when marshaling or unmarshaling a struct field value. // This causes numeric types to be encoded as a JSON number // within a JSON string, and to be decoded from either a JSON number or // a JSON string containing a JSON number. // This extra level of encoding is often necessary since // many JSON parsers cannot precisely represent 64-bit integers. // // - nocase: When unmarshaling, the "nocase" option specifies that // if the JSON object name does not exactly match the JSON name // for any of the struct fields, then it attempts to match the struct field // using a case-insensitive match that also ignores dashes and underscores. // If multiple fields match, the first declared field in breadth-first order // takes precedence. This option has no effect when marshaling. // // - inline: The "inline" option specifies that // the JSON representable content of this field type is to be promoted // as if they were specified in the parent struct. // It is the JSON equivalent of Go struct embedding. // A Go embedded field is implicitly inlined unless an explicit JSON name // is specified. The inlined field must be a Go struct // (that does not implement any JSON methods), RawValue, map[string]T, // or an unnamed pointer to such types. When marshaling, // inlined fields from a pointer type are omitted if it is nil. // Inlined fields of type RawValue and map[string]T are called // β€œinlined fallbacks” as they can represent all possible // JSON object members not directly handled by the parent struct. // Only one inlined fallback field may be specified in a struct, // while many non-fallback fields may be specified. This option // must not be specified with any other option (including the JSON name). // // - unknown: The "unknown" option is a specialized variant // of the inlined fallback to indicate that this Go struct field // contains any number of unknown JSON object members. The field type // must be a RawValue, map[string]T, or an unnamed pointer to such types. // If MarshalOptions.DiscardUnknownMembers is specified when marshaling, // the contents of this field are ignored. // If UnmarshalOptions.RejectUnknownMembers is specified when unmarshaling, // any unknown object members are rejected regardless of whether // an inlined fallback with the "unknown" option exists. This option // must not be specified with any other option (including the JSON name). // // - format: The "format" option specifies a format flag // used to specialize the formatting of the field value. // The option is a key-value pair specified as "format:value" where // the value must be either a literal consisting of letters and numbers // (e.g., "format:RFC3339") or a single-quoted string literal // (e.g., "format:'2006-01-02'"). The interpretation of the format flag // is determined by the struct field type. // // The "omitzero" and "omitempty" options are mostly semantically identical. // The former is defined in terms of the Go type system, // while the latter in terms of the JSON type system. // Consequently they behave differently in some circumstances. // For example, only a nil slice or map is omitted under "omitzero", while // an empty slice or map is omitted under "omitempty" regardless of nilness. // The "omitzero" option is useful for types with a well-defined zero value // (e.g., netip.Addr) or have an IsZero method (e.g., time.Time). // // Every Go struct corresponds to a list of JSON representable fields // which is constructed by performing a breadth-first search over // all struct fields (excluding unexported or ignored fields), // where the search recursively descends into inlined structs. // The set of non-inlined fields in a struct must have unique JSON names. // If multiple fields all have the same JSON name, then the one // at shallowest depth takes precedence and the other fields at deeper depths // are excluded from the list of JSON representable fields. // If multiple fields at the shallowest depth have the same JSON name, // then all of those fields are excluded from the list. This is analogous to // Go visibility rules for struct field selection with embedded struct types. // // Marshaling or unmarshaling a non-empty struct // without any JSON representable fields results in a SemanticError. // Unexported fields must not have any `json` tags except for `json:"-"`. package json // requireKeyedLiterals can be embedded in a struct to require keyed literals. type requireKeyedLiterals struct{} // nonComparable can be embedded in a struct to prevent comparability. type nonComparable [0]func()
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "errors" "io" "math" "strconv" "unicode/utf16" "unicode/utf8" ) // NOTE: The logic for decoding is complicated by the fact that reading from // an io.Reader into a temporary buffer means that the buffer may contain a // truncated portion of some valid input, requiring the need to fetch more data. // // This file is structured in the following way: // // - consumeXXX functions parse an exact JSON token from a []byte. // If the buffer appears truncated, then it returns io.ErrUnexpectedEOF. // The consumeSimpleXXX functions are so named because they only handle // a subset of the grammar for the JSON token being parsed. // They do not handle the full grammar to keep these functions inlineable. // // - Decoder.consumeXXX methods parse the next JSON token from Decoder.buf, // automatically fetching more input if necessary. These methods take // a position relative to the start of Decoder.buf as an argument and // return the end of the consumed JSON token as a position, // also relative to the start of Decoder.buf. // // - In the event of an I/O errors or state machine violations, // the implementation avoids mutating the state of Decoder // (aside from the book-keeping needed to implement Decoder.fetch). // For this reason, only Decoder.ReadToken and Decoder.ReadValue are // responsible for updated Decoder.prevStart and Decoder.prevEnd. // // - For performance, much of the implementation uses the pattern of calling // the inlineable consumeXXX functions first, and if more work is necessary, // then it calls the slower Decoder.consumeXXX methods. // TODO: Revisit this pattern if the Go compiler provides finer control // over exactly which calls are inlined or not. // DecodeOptions configures how JSON decoding operates. // The zero value is equivalent to the default settings, // which is compliant with both RFC 7493 and RFC 8259. type DecodeOptions struct { requireKeyedLiterals nonComparable // AllowDuplicateNames specifies that JSON objects may contain // duplicate member names. Disabling the duplicate name check may provide // computational and performance benefits, but breaks compliance with // RFC 7493, section 2.3. The input will still be compliant with RFC 8259, // which leaves the handling of duplicate names as unspecified behavior. AllowDuplicateNames bool // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, // which will be mangled as the Unicode replacement character, U+FFFD. // This causes the decoder to break compliance with // RFC 7493, section 2.1, and RFC 8259, section 8.1. AllowInvalidUTF8 bool } // Decoder is a streaming decoder for raw JSON tokens and values. // It is used to read a stream of top-level JSON values, // each separated by optional whitespace characters. // // ReadToken and ReadValue calls may be interleaved. // For example, the following JSON value: // // {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} // // can be parsed with the following calls (ignoring errors for brevity): // // d.ReadToken() // { // d.ReadToken() // "name" // d.ReadToken() // "value" // d.ReadValue() // "array" // d.ReadToken() // [ // d.ReadToken() // null // d.ReadToken() // false // d.ReadValue() // true // d.ReadToken() // 3.14159 // d.ReadToken() // ] // d.ReadValue() // "object" // d.ReadValue() // {"k":"v"} // d.ReadToken() // } // // The above is one of many possible sequence of calls and // may not represent the most sensible method to call for any given token/value. // For example, it is probably more common to call ReadToken to obtain a // string token for object names. type Decoder struct { state decodeBuffer options DecodeOptions stringCache *stringCache // only used when unmarshaling } // decodeBuffer is a buffer split into 4 segments: // // - buf[0:prevEnd] // already read portion of the buffer // - buf[prevStart:prevEnd] // previously read value // - buf[prevEnd:len(buf)] // unread portion of the buffer // - buf[len(buf):cap(buf)] // unused portion of the buffer // // Invariants: // // 0 ≀ prevStart ≀ prevEnd ≀ len(buf) ≀ cap(buf) type decodeBuffer struct { peekPos int // non-zero if valid offset into buf for start of next token peekErr error // implies peekPos is -1 buf []byte // may alias rd if it is a bytes.Buffer prevStart int prevEnd int // baseOffset is added to prevStart and prevEnd to obtain // the absolute offset relative to the start of io.Reader stream. baseOffset int64 rd io.Reader } // NewDecoder constructs a new streaming decoder reading from r. // // If r is a bytes.Buffer, then the decoder parses directly from the buffer // without first copying the contents to an intermediate buffer. // Additional writes to the buffer must not occur while the decoder is in use. func NewDecoder(r io.Reader) *Decoder { return DecodeOptions{}.NewDecoder(r) } // NewDecoder constructs a new streaming decoder reading from r // configured with the provided options. func (o DecodeOptions) NewDecoder(r io.Reader) *Decoder { d := new(Decoder) o.ResetDecoder(d, r) return d } // ResetDecoder resets a decoder such that it is reading afresh from r and // configured with the provided options. func (o DecodeOptions) ResetDecoder(d *Decoder, r io.Reader) { if d == nil { panic("json: invalid nil Decoder") } if r == nil { panic("json: invalid nil io.Reader") } d.reset(nil, r, o) } func (d *Decoder) reset(b []byte, r io.Reader, o DecodeOptions) { d.state.reset() d.decodeBuffer = decodeBuffer{buf: b, rd: r} d.options = o } // Reset resets a decoder such that it is reading afresh from r but // keep any pre-existing decoder options. func (d *Decoder) Reset(r io.Reader) { d.options.ResetDecoder(d, r) } var errBufferWriteAfterNext = errors.New("invalid bytes.Buffer.Write call after calling bytes.Buffer.Next") // fetch reads at least 1 byte from the underlying io.Reader. // It returns io.ErrUnexpectedEOF if zero bytes were read and io.EOF was seen. func (d *Decoder) fetch() error { if d.rd == nil { return io.ErrUnexpectedEOF } // Inform objectNameStack that we are about to fetch new buffer content. d.names.copyQuotedBuffer(d.buf) // Specialize bytes.Buffer for better performance. if bb, ok := d.rd.(*bytes.Buffer); ok { switch { case bb.Len() == 0: return io.ErrUnexpectedEOF case len(d.buf) == 0: d.buf = bb.Next(bb.Len()) // "read" all data in the buffer return nil default: // This only occurs if a partially filled bytes.Buffer was provided // and more data is written to it while Decoder is reading from it. // This practice will lead to data corruption since future writes // may overwrite the contents of the current buffer. // // The user is trying to use a bytes.Buffer as a pipe, // but a bytes.Buffer is poor implementation of a pipe, // the purpose-built io.Pipe should be used instead. return &ioError{action: "read", err: errBufferWriteAfterNext} } } // Allocate initial buffer if empty. if cap(d.buf) == 0 { d.buf = make([]byte, 0, 64) } // Check whether to grow the buffer. const maxBufferSize = 4 << 10 const growthSizeFactor = 2 // higher value is faster const growthRateFactor = 2 // higher value is slower // By default, grow if below the maximum buffer size. grow := cap(d.buf) <= maxBufferSize/growthSizeFactor // Growing can be expensive, so only grow // if a sufficient number of bytes have been processed. grow = grow && int64(cap(d.buf)) < d.previousOffsetEnd()/growthRateFactor // If prevStart==0, then fetch was called in order to fetch more data // to finish consuming a large JSON value contiguously. // Grow if less than 25% of the remaining capacity is available. // Note that this may cause the input buffer to exceed maxBufferSize. grow = grow || (d.prevStart == 0 && len(d.buf) >= 3*cap(d.buf)/4) if grow { // Allocate a new buffer and copy the contents of the old buffer over. // TODO: Provide a hard limit on the maximum internal buffer size? buf := make([]byte, 0, cap(d.buf)*growthSizeFactor) d.buf = append(buf, d.buf[d.prevStart:]...) } else { // Move unread portion of the data to the front. n := copy(d.buf[:cap(d.buf)], d.buf[d.prevStart:]) d.buf = d.buf[:n] } d.baseOffset += int64(d.prevStart) d.prevEnd -= d.prevStart d.prevStart = 0 // Read more data into the internal buffer. for { n, err := d.rd.Read(d.buf[len(d.buf):cap(d.buf)]) switch { case n > 0: d.buf = d.buf[:len(d.buf)+n] return nil // ignore errors if any bytes are read case err == io.EOF: return io.ErrUnexpectedEOF case err != nil: return &ioError{action: "read", err: err} default: continue // Read returned (0, nil) } } } const invalidateBufferByte = '#' // invalid starting character for JSON grammar // invalidatePreviousRead invalidates buffers returned by Peek and Read calls // so that the first byte is an invalid character. // This Hyrum-proofs the API against faulty application code that assumes // values returned by ReadValue remain valid past subsequent Read calls. func (d *decodeBuffer) invalidatePreviousRead() { // Avoid mutating the buffer if d.rd is nil which implies that d.buf // is provided by the user code and may not expect mutations. isBytesBuffer := func(r io.Reader) bool { _, ok := r.(*bytes.Buffer) return ok } if d.rd != nil && !isBytesBuffer(d.rd) && d.prevStart < d.prevEnd && uint(d.prevStart) < uint(len(d.buf)) { d.buf[d.prevStart] = invalidateBufferByte d.prevStart = d.prevEnd } } // needMore reports whether there are no more unread bytes. func (d *decodeBuffer) needMore(pos int) bool { // NOTE: The arguments and logic are kept simple to keep this inlineable. return pos == len(d.buf) } // injectSyntacticErrorWithPosition wraps a SyntacticError with the position, // otherwise it returns the error as is. // It takes a position relative to the start of the start of d.buf. func (d *decodeBuffer) injectSyntacticErrorWithPosition(err error, pos int) error { if serr, ok := err.(*SyntacticError); ok { return serr.withOffset(d.baseOffset + int64(pos)) } return err } func (d *decodeBuffer) previousOffsetStart() int64 { return d.baseOffset + int64(d.prevStart) } func (d *decodeBuffer) previousOffsetEnd() int64 { return d.baseOffset + int64(d.prevEnd) } func (d *decodeBuffer) previousBuffer() []byte { return d.buf[d.prevStart:d.prevEnd] } func (d *decodeBuffer) unreadBuffer() []byte { return d.buf[d.prevEnd:len(d.buf)] } // PeekKind retrieves the next token kind, but does not advance the read offset. // It returns 0 if there are no more tokens. func (d *Decoder) PeekKind() Kind { // Check whether we have a cached peek result. if d.peekPos > 0 { return Kind(d.buf[d.peekPos]).normalize() } var err error d.invalidatePreviousRead() pos := d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } d.peekPos, d.peekErr = -1, err return invalidKind } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { d.peekPos, d.peekErr = -1, err return invalidKind } } } next := Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) err = d.injectSyntacticErrorWithPosition(err, pos) d.peekPos, d.peekErr = -1, err return invalidKind } // This may set peekPos to zero, which is indistinguishable from // the uninitialized state. While a small hit to performance, it is correct // since ReadValue and ReadToken will disregard the cached result and // recompute the next kind. d.peekPos, d.peekErr = pos, nil return next } // SkipValue is semantically equivalent to calling ReadValue and discarding // the result except that memory is not wasted trying to hold the entire result. func (d *Decoder) SkipValue() error { switch d.PeekKind() { case '{', '[': // For JSON objects and arrays, keep skipping all tokens // until the depth matches the starting depth. depth := d.tokens.depth() for { if _, err := d.ReadToken(); err != nil { return err } if depth >= d.tokens.depth() { return nil } } default: // Trying to skip a value when the next token is a '}' or ']' // will result in an error being returned here. if _, err := d.ReadValue(); err != nil { return err } return nil } } // ReadToken reads the next Token, advancing the read offset. // The returned token is only valid until the next Peek, Read, or Skip call. // It returns io.EOF if there are no more tokens. func (d *Decoder) ReadToken() (Token, error) { // Determine the next kind. var err error var next Kind pos := d.peekPos if pos != 0 { // Use cached peek result. if d.peekErr != nil { err := d.peekErr d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error return Token{}, err } next = Kind(d.buf[pos]).normalize() d.peekPos = 0 // reset cache } else { d.invalidatePreviousRead() pos = d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } return Token{}, err } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return Token{}, err } } } next = Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } // Handle the next token. var n int switch next { case 'n': if consumeNull(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "null") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("null") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("null")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return Null, nil case 'f': if consumeFalse(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "false") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("false") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("false")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return False, nil case 't': if consumeTrue(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "true") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("true") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("true")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return True, nil case '"': var flags valueFlags // TODO: Preserve this in Token? if n = consumeSimpleString(d.buf[pos:]); n == 0 { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeString(&flags, pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += n } if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { if !d.tokens.last.isValidNamespace() { return Token{}, errInvalidNamespace } if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string } d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds } if err = d.tokens.appendString(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string } d.prevStart, d.prevEnd = pos-n, pos return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil case '0': // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeNumber(pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += n } if err = d.tokens.appendNumber(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of number } d.prevStart, d.prevEnd = pos-n, pos return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil case '{': if err = d.tokens.pushObject(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } if !d.options.AllowDuplicateNames { d.names.push() d.namespaces.push() } pos += 1 d.prevStart, d.prevEnd = pos, pos return ObjectStart, nil case '}': if err = d.tokens.popObject(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } if !d.options.AllowDuplicateNames { d.names.pop() d.namespaces.pop() } pos += 1 d.prevStart, d.prevEnd = pos, pos return ObjectEnd, nil case '[': if err = d.tokens.pushArray(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } pos += 1 d.prevStart, d.prevEnd = pos, pos return ArrayStart, nil case ']': if err = d.tokens.popArray(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } pos += 1 d.prevStart, d.prevEnd = pos, pos return ArrayEnd, nil default: err = newInvalidCharacterError(d.buf[pos:], "at start of token") return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } type valueFlags uint const ( _ valueFlags = (1 << iota) / 2 // powers of two starting with zero stringNonVerbatim // string cannot be naively treated as valid UTF-8 stringNonCanonical // string not formatted according to RFC 8785, section 3.2.2.2. // TODO: Track whether a number is a non-integer? ) func (f *valueFlags) set(f2 valueFlags) { *f |= f2 } func (f valueFlags) isVerbatim() bool { return f&stringNonVerbatim == 0 } func (f valueFlags) isCanonical() bool { return f&stringNonCanonical == 0 } // ReadValue returns the next raw JSON value, advancing the read offset. // The value is stripped of any leading or trailing whitespace. // The returned value is only valid until the next Peek, Read, or Skip call and // may not be mutated while the Decoder remains in use. // If the decoder is currently at the end token for an object or array, // then it reports a SyntacticError and the internal state remains unchanged. // It returns io.EOF if there are no more values. func (d *Decoder) ReadValue() (RawValue, error) { var flags valueFlags return d.readValue(&flags) } func (d *Decoder) readValue(flags *valueFlags) (RawValue, error) { // Determine the next kind. var err error var next Kind pos := d.peekPos if pos != 0 { // Use cached peek result. if d.peekErr != nil { err := d.peekErr d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error return nil, err } next = Kind(d.buf[pos]).normalize() d.peekPos = 0 // reset cache } else { d.invalidatePreviousRead() pos = d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } return nil, err } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return nil, err } } } next = Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) return nil, d.injectSyntacticErrorWithPosition(err, pos) } } // Handle the next value. oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeValue(flags, pos) newAbsPos := d.baseOffset + int64(pos) n := int(newAbsPos - oldAbsPos) if err != nil { return nil, d.injectSyntacticErrorWithPosition(err, pos) } switch next { case 'n', 't', 'f': err = d.tokens.appendLiteral() case '"': if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { if !d.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} break } d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds } err = d.tokens.appendString() case '0': err = d.tokens.appendNumber() case '{': if err = d.tokens.pushObject(); err != nil { break } if err = d.tokens.popObject(); err != nil { panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) } case '[': if err = d.tokens.pushArray(); err != nil { break } if err = d.tokens.popArray(); err != nil { panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) } } if err != nil { return nil, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of value } d.prevEnd = pos d.prevStart = pos - n return d.buf[pos-n : pos : pos], nil } // checkEOF verifies that the input has no more data. func (d *Decoder) checkEOF() error { switch pos, err := d.consumeWhitespace(d.prevEnd); err { case nil: return newInvalidCharacterError(d.buf[pos:], "after top-level value") case io.ErrUnexpectedEOF: return nil default: return err } } // consumeWhitespace consumes all whitespace starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the last whitespace. // If it returns nil, there is guaranteed to at least be one unread byte. // // The following pattern is common in this implementation: // // pos += consumeWhitespace(d.buf[pos:]) // if d.needMore(pos) { // if pos, err = d.consumeWhitespace(pos); err != nil { // return ... // } // } // // It is difficult to simplify this without sacrificing performance since // consumeWhitespace must be inlined. The body of the if statement is // executed only in rare situations where we need to fetch more data. // Since fetching may return an error, we also need to check the error. func (d *Decoder) consumeWhitespace(pos int) (newPos int, err error) { for { pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos, nil } } // consumeValue consumes a single JSON value starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the value. func (d *Decoder) consumeValue(flags *valueFlags, pos int) (newPos int, err error) { for { var n int var err error switch next := Kind(d.buf[pos]).normalize(); next { case 'n': if n = consumeNull(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "null") } case 'f': if n = consumeFalse(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "false") } case 't': if n = consumeTrue(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "true") } case '"': if n = consumeSimpleString(d.buf[pos:]); n == 0 { return d.consumeString(flags, pos) } case '0': // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { return d.consumeNumber(pos) } case '{': return d.consumeObject(flags, pos) case '[': return d.consumeArray(flags, pos) default: return pos, newInvalidCharacterError(d.buf[pos:], "at start of value") } if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeLiteral consumes a single JSON literal starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the literal. func (d *Decoder) consumeLiteral(pos int, lit string) (newPos int, err error) { for { n, err := consumeLiteral(d.buf[pos:], lit) if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeString consumes a single JSON string starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the string. func (d *Decoder) consumeString(flags *valueFlags, pos int) (newPos int, err error) { var n int for { n, err = consumeStringResumable(flags, d.buf[pos:], n, !d.options.AllowInvalidUTF8) if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeNumber consumes a single JSON number starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the number. func (d *Decoder) consumeNumber(pos int) (newPos int, err error) { var n int var state consumeNumberState for { n, state, err = consumeNumberResumable(d.buf[pos:], n, state) // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if err == io.ErrUnexpectedEOF || d.needMore(pos+n) { mayTerminate := err == nil absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { if mayTerminate && err == io.ErrUnexpectedEOF { return pos + n, nil } return pos, err } continue } return pos + n, err } } // consumeObject consumes a single JSON object starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the object. func (d *Decoder) consumeObject(flags *valueFlags, pos int) (newPos int, err error) { var n int var names *objectNamespace if !d.options.AllowDuplicateNames { d.namespaces.push() defer d.namespaces.pop() names = d.namespaces.last() } // Handle before start. if d.buf[pos] != '{' { panic("BUG: consumeObject must be called with a buffer that starts with '{'") } pos++ // Handle after start. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] == '}' { pos++ return pos, nil } for { // Handle before name. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } var flags2 valueFlags if n = consumeSimpleString(d.buf[pos:]); n == 0 { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeString(&flags2, pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) flags.set(flags2) if err != nil { return pos, err } } else { pos += n } if !d.options.AllowDuplicateNames && !names.insertQuoted(d.buf[pos-n:pos], flags2.isVerbatim()) { return pos - n, &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} } // Handle after name. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] != ':' { return pos, newInvalidCharacterError(d.buf[pos:], "after object name (expecting ':')") } pos++ // Handle before value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } pos, err = d.consumeValue(flags, pos) if err != nil { return pos, err } // Handle after value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } switch d.buf[pos] { case ',': pos++ continue case '}': pos++ return pos, nil default: return pos, newInvalidCharacterError(d.buf[pos:], "after object value (expecting ',' or '}')") } } } // consumeArray consumes a single JSON array starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the array. func (d *Decoder) consumeArray(flags *valueFlags, pos int) (newPos int, err error) { // Handle before start. if d.buf[pos] != '[' { panic("BUG: consumeArray must be called with a buffer that starts with '['") } pos++ // Handle after start. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] == ']' { pos++ return pos, nil } for { // Handle before value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } pos, err = d.consumeValue(flags, pos) if err != nil { return pos, err } // Handle after value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } switch d.buf[pos] { case ',': pos++ continue case ']': pos++ return pos, nil default: return pos, newInvalidCharacterError(d.buf[pos:], "after array value (expecting ',' or ']')") } } } // InputOffset returns the current input byte offset. It gives the location // of the next byte immediately after the most recently returned token or value. // The number of bytes actually read from the underlying io.Reader may be more // than this offset due to internal buffering effects. func (d *Decoder) InputOffset() int64 { return d.previousOffsetEnd() } // UnreadBuffer returns the data remaining in the unread buffer, // which may contain zero or more bytes. // The returned buffer must not be mutated while Decoder continues to be used. // The buffer contents are valid until the next Peek, Read, or Skip call. func (d *Decoder) UnreadBuffer() []byte { return d.unreadBuffer() } // StackDepth returns the depth of the state machine for read JSON data. // Each level on the stack represents a nested JSON object or array. // It is incremented whenever an ObjectStart or ArrayStart token is encountered // and decremented whenever an ObjectEnd or ArrayEnd token is encountered. // The depth is zero-indexed, where zero represents the top-level JSON value. func (d *Decoder) StackDepth() int { // NOTE: Keep in sync with Encoder.StackDepth. return d.tokens.depth() - 1 } // StackIndex returns information about the specified stack level.
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "encoding/binary" "math/bits" ) // stringCache is a cache for strings converted from a []byte. type stringCache [256]string // 256*unsafe.Sizeof(string("")) => 4KiB // make returns the string form of b. // It returns a pre-allocated string from c if present, otherwise // it allocates a new string, inserts it into the cache, and returns it. func (c *stringCache) make(b []byte) string { const ( minCachedLen = 2 // single byte strings are already interned by the runtime maxCachedLen = 256 // large enough for UUIDs, IPv6 addresses, SHA-256 checksums, etc. ) if c == nil || len(b) < minCachedLen || len(b) > maxCachedLen { return string(b) } // Compute a hash from the fixed-width prefix and suffix of the string. // This ensures hashing a string is a constant time operation. var h uint32 switch { case len(b) >= 8: lo := binary.LittleEndian.Uint64(b[:8]) hi := binary.LittleEndian.Uint64(b[len(b)-8:]) h = hash64(uint32(lo), uint32(lo>>32)) ^ hash64(uint32(hi), uint32(hi>>32)) case len(b) >= 4: lo := binary.LittleEndian.Uint32(b[:4]) hi := binary.LittleEndian.Uint32(b[len(b)-4:]) h = hash64(lo, hi) case len(b) >= 2: lo := binary.LittleEndian.Uint16(b[:2]) hi := binary.LittleEndian.Uint16(b[len(b)-2:]) h = hash64(uint32(lo), uint32(hi)) } // Check the cache for the string. i := h % uint32(len(*c)) if s := (*c)[i]; s == string(b) { return s } s := string(b) (*c)[i] = s return s } // hash64 returns the hash of two uint32s as a single uint32. func hash64(lo, hi uint32) uint32 { // If avalanche=true, this is identical to XXH32 hash on a 8B string: // var b [8]byte // binary.LittleEndian.PutUint32(b[:4], lo) // binary.LittleEndian.PutUint32(b[4:], hi) // return xxhash.Sum32(b[:]) const ( prime1 = 0x9e3779b1 prime2 = 0x85ebca77 prime3 = 0xc2b2ae3d prime4 = 0x27d4eb2f prime5 = 0x165667b1 ) h := prime5 + uint32(8) h += lo * prime3 h = bits.RotateLeft32(h, 17) * prime4 h += hi * prime3 h = bits.RotateLeft32(h, 17) * prime4 // Skip final mix (avalanche) step of XXH32 for performance reasons. // Empirical testing shows that the improvements in unbiased distribution // does not outweigh the extra cost in computational complexity. const avalanche = false if avalanche { h ^= h >> 15 h *= prime2 h ^= h >> 13 h *= prime3 h ^= h >> 16 } return h }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "errors" "fmt" "io" "reflect" "sort" "strconv" "strings" "unicode" "unicode/utf8" ) var errIgnoredField = errors.New("ignored field") type isZeroer interface { IsZero() bool } var isZeroerType = reflect.TypeOf((*isZeroer)(nil)).Elem() type structFields struct { flattened []structField // listed in depth-first ordering byActualName map[string]*structField byFoldedName map[string][]*structField inlinedFallback *structField } type structField struct { id int // unique numeric ID in breadth-first ordering index []int // index into a struct according to reflect.Type.FieldByIndex typ reflect.Type fncs *arshaler isZero func(addressableValue) bool isEmpty func(addressableValue) bool fieldOptions } func makeStructFields(root reflect.Type) (structFields, *SemanticError) { var fs structFields fs.byActualName = make(map[string]*structField, root.NumField()) fs.byFoldedName = make(map[string][]*structField, root.NumField()) // ambiguous is a sentinel value to indicate that at least two fields // at the same depth have the same name, and thus cancel each other out. // This follows the same rules as selecting a field on embedded structs // where the shallowest field takes precedence. If more than one field // exists at the shallowest depth, then the selection is illegal. // See https://go.dev/ref/spec#Selectors. ambiguous := new(structField) // Setup a queue for a breath-first search. var queueIndex int type queueEntry struct { typ reflect.Type index []int visitChildren bool // whether to recursively visit inlined field in this struct } queue := []queueEntry{{root, nil, true}} seen := map[reflect.Type]bool{root: true} // Perform a breadth-first search over all reachable fields. // This ensures that len(f.index) will be monotonically increasing. for queueIndex < len(queue) { qe := queue[queueIndex] queueIndex++ t := qe.typ inlinedFallbackIndex := -1 // index of last inlined fallback field in current struct namesIndex := make(map[string]int) // index of each field with a given JSON object name in current struct var hasAnyJSONTag bool // whether any Go struct field has a `json` tag var hasAnyJSONField bool // whether any JSON serializable fields exist in current struct for i := 0; i < t.NumField(); i++ { sf := t.Field(i) _, hasTag := sf.Tag.Lookup("json") hasAnyJSONTag = hasAnyJSONTag || hasTag options, err := parseFieldOptions(sf) if err != nil { if err == errIgnoredField { continue } return structFields{}, &SemanticError{GoType: t, Err: err} } hasAnyJSONField = true f := structField{ // Allocate a new slice (len=N+1) to hold both // the parent index (len=N) and the current index (len=1). // Do this to avoid clobbering the memory of the parent index. index: append(append(make([]int, 0, len(qe.index)+1), qe.index...), i), typ: sf.Type, fieldOptions: options, } if sf.Anonymous && !f.hasName { f.inline = true // implied by use of Go embedding without an explicit name } if f.inline || f.unknown { // Handle an inlined field that serializes to/from // zero or more JSON object members. if f.inline && f.unknown { err := fmt.Errorf("Go struct field %s cannot have both `inline` and `unknown` specified", sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } switch f.fieldOptions { case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true}: case fieldOptions{name: f.name, quotedName: f.quotedName, unknown: true}: default: err := fmt.Errorf("Go struct field %s cannot have any options other than `inline` or `unknown` specified", sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } // Unwrap one level of pointer indirection similar to how Go // only allows embedding either T or *T, but not **T. tf := f.typ if tf.Kind() == reflect.Pointer && tf.Name() == "" { tf = tf.Elem() } // Reject any types with custom serialization otherwise // it becomes impossible to know what sub-fields to inline. if which, _ := implementsWhich(tf, jsonMarshalerV2Type, jsonMarshalerV1Type, textMarshalerType, jsonUnmarshalerV2Type, jsonUnmarshalerV1Type, textUnmarshalerType, ); which != nil && tf != rawValueType { err := fmt.Errorf("inlined Go struct field %s of type %s must not implement JSON marshal or unmarshal methods", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } // Handle an inlined field that serializes to/from // a finite number of JSON object members backed by a Go struct. if tf.Kind() == reflect.Struct { if f.unknown { err := fmt.Errorf("inlined Go struct field %s of type %s with `unknown` tag must be a Go map of string key or a json.RawValue", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } if qe.visitChildren { queue = append(queue, queueEntry{tf, f.index, !seen[tf]}) } seen[tf] = true continue } // Handle an inlined field that serializes to/from any number of // JSON object members back by a Go map or RawValue. switch { case tf == rawValueType: f.fncs = nil // specially handled in arshal_inlined.go case tf.Kind() == reflect.Map && tf.Key() == stringType: f.fncs = lookupArshaler(tf.Elem()) default: err := fmt.Errorf("inlined Go struct field %s of type %s must be a Go struct, Go map of string key, or json.RawValue", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } // Reject multiple inlined fallback fields within the same struct. if inlinedFallbackIndex >= 0 { err := fmt.Errorf("inlined Go struct fields %s and %s cannot both be a Go map or json.RawValue", t.Field(inlinedFallbackIndex).Name, sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } inlinedFallbackIndex = i // Multiple inlined fallback fields across different structs // follow the same precedence rules as Go struct embedding. if fs.inlinedFallback == nil { fs.inlinedFallback = &f // store first occurrence at lowest depth } else if len(fs.inlinedFallback.index) == len(f.index) { fs.inlinedFallback = ambiguous // at least two occurrences at same depth } } else { // Handle normal Go struct field that serializes to/from // a single JSON object member. // Provide a function that uses a type's IsZero method. switch { case sf.Type.Kind() == reflect.Interface && sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { // Avoid panics calling IsZero on a nil interface or // non-nil interface with nil pointer. return va.IsNil() || (va.Elem().Kind() == reflect.Pointer && va.Elem().IsNil()) || va.Interface().(isZeroer).IsZero() } case sf.Type.Kind() == reflect.Pointer && sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { // Avoid panics calling IsZero on nil pointer. return va.IsNil() || va.Interface().(isZeroer).IsZero() } case sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { return va.Interface().(isZeroer).IsZero() } case reflect.PointerTo(sf.Type).Implements(isZeroerType): f.isZero = func(va addressableValue) bool { return va.Addr().Interface().(isZeroer).IsZero() } } // Provide a function that can determine whether the value would // serialize as an empty JSON value. switch sf.Type.Kind() { case reflect.String, reflect.Map, reflect.Array, reflect.Slice: f.isEmpty = func(va addressableValue) bool { return va.Len() == 0 } case reflect.Pointer, reflect.Interface: f.isEmpty = func(va addressableValue) bool { return va.IsNil() } } f.id = len(fs.flattened) f.fncs = lookupArshaler(sf.Type) fs.flattened = append(fs.flattened, f) // Reject user-specified names with invalid UTF-8. if !utf8.ValidString(f.name) { err := fmt.Errorf("Go struct field %s has JSON object name %q with invalid UTF-8", sf.Name, f.name) return structFields{}, &SemanticError{GoType: t, Err: err} } // Reject multiple fields with same name within the same struct. if j, ok := namesIndex[f.name]; ok { err := fmt.Errorf("Go struct fields %s and %s conflict over JSON object name %q", t.Field(j).Name, sf.Name, f.name) return structFields{}, &SemanticError{GoType: t, Err: err} } namesIndex[f.name] = i // Multiple fields of the same name across different structs // follow the same precedence rules as Go struct embedding. if f2 := fs.byActualName[f.name]; f2 == nil { fs.byActualName[f.name] = &fs.flattened[len(fs.flattened)-1] // store first occurrence at lowest depth } else if len(f2.index) == len(f.index) { fs.byActualName[f.name] = ambiguous // at least two occurrences at same depth } } } // NOTE: New users to the json package are occasionally surprised that // unexported fields are ignored. This occurs by necessity due to our // inability to directly introspect such fields with Go reflection // without the use of unsafe. // // To reduce friction here, refuse to serialize any Go struct that // has no JSON serializable fields, has at least one Go struct field, // and does not have any `json` tags present. For example, // errors returned by errors.New would fail to serialize. isEmptyStruct := t.NumField() == 0 if !isEmptyStruct && !hasAnyJSONTag && !hasAnyJSONField { err := errors.New("Go struct has no exported fields") return structFields{}, &SemanticError{GoType: t, Err: err} } } // Remove all fields that are duplicates. // This may move elements forward to fill the holes from removed fields. var n int for _, f := range fs.flattened { switch f2 := fs.byActualName[f.name]; { case f2 == ambiguous: delete(fs.byActualName, f.name) case f2 == nil: continue // may be nil due to previous delete // TODO(https://go.dev/issue/45955): Use slices.Equal. case reflect.DeepEqual(f.index, f2.index): f.id = n fs.flattened[n] = f fs.byActualName[f.name] = &fs.flattened[n] // fix pointer to new location n++ } } fs.flattened = fs.flattened[:n] if fs.inlinedFallback == ambiguous { fs.inlinedFallback = nil } if len(fs.flattened) != len(fs.byActualName) { panic(fmt.Sprintf("BUG: flattened list of fields mismatches fields mapped by name: %d != %d", len(fs.flattened), len(fs.byActualName))) } // Sort the fields according to a depth-first ordering. // This operation will cause pointers in byActualName to become incorrect, // which we will correct in another loop shortly thereafter. sort.Slice(fs.flattened, func(i, j int) bool { si := fs.flattened[i].index sj := fs.flattened[j].index for len(si) > 0 && len(sj) > 0 { switch { case si[0] < sj[0]: return true case si[0] > sj[0]: return false default: si = si[1:] sj = sj[1:] } } return len(si) < len(sj) }) // Recompute the mapping of fields in the byActualName map. // Pre-fold all names so that we can lookup folded names quickly. for i, f := range fs.flattened { foldedName := string(foldName([]byte(f.name))) fs.byActualName[f.name] = &fs.flattened[i] fs.byFoldedName[foldedName] = append(fs.byFoldedName[foldedName], &fs.flattened[i]) } for foldedName, fields := range fs.byFoldedName { if len(fields) > 1 { // The precedence order for conflicting nocase names // is by breadth-first order, rather than depth-first order. sort.Slice(fields, func(i, j int) bool { return fields[i].id < fields[j].id }) fs.byFoldedName[foldedName] = fields } } return fs, nil } type fieldOptions struct { name string quotedName string // quoted name per RFC 8785, section 3.2.2.2. hasName bool nocase bool inline bool unknown bool omitzero bool omitempty bool string bool format string } // parseFieldOptions parses the `json` tag in a Go struct field as // a structured set of options configuring parameters such as // the JSON member name and other features. // As a special case, it returns errIgnoredField if the field is ignored. func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { tag, hasTag := sf.Tag.Lookup("json") // Check whether this field is explicitly ignored. if tag == "-" { return fieldOptions{}, errIgnoredField } // Check whether this field is unexported. if !sf.IsExported() { // In contrast to v1, v2 no longer forwards exported fields from // embedded fields of unexported types since Go reflection does not // allow the same set of operations that are available in normal cases // of purely exported fields. // See https://go.dev/issue/21357 and https://go.dev/issue/24153. if sf.Anonymous { return fieldOptions{}, fmt.Errorf("embedded Go struct field %s of an unexported type must be explicitly ignored with a `json:\"-\"` tag", sf.Type.Name()) } // Tag options specified on an unexported field suggests user error. if hasTag { return fieldOptions{}, fmt.Errorf("unexported Go struct field %s cannot have non-ignored `json:%q` tag", sf.Name, tag) } return fieldOptions{}, errIgnoredField } // Determine the JSON member name for this Go field. A user-specified name // may be provided as either an identifier or a single-quoted string. // The single-quoted string allows arbitrary characters in the name. // See https://go.dev/issue/2718 and https://go.dev/issue/3546. out.name = sf.Name // always starts with an uppercase character if len(tag) > 0 && !strings.HasPrefix(tag, ",") { // For better compatibility with v1, accept almost any unescaped name. n := len(tag) - len(strings.TrimLeftFunc(tag, func(r rune) bool { return !strings.ContainsRune(",\\'\"`", r) // reserve comma, backslash, and quotes })) opt := tag[:n] if n == 0 { // Allow a single quoted string for arbitrary names. opt, n, err = consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) } } out.hasName = true out.name = opt tag = tag[n:] } b, _ := appendString(nil, out.name, false, nil) out.quotedName = string(b) // Handle any additional tag options (if any). var wasFormat bool seenOpts := make(map[string]bool) for len(tag) > 0 { // Consume comma delimiter. if tag[0] != ',' { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", sf.Name, tag[0]) } tag = tag[len(","):] if len(tag) == 0 { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid trailing ',' character", sf.Name) } // Consume and process the tag option. opt, n, err := consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) } rawOpt := tag[:n] tag = tag[n:] switch { case wasFormat: return fieldOptions{}, fmt.Errorf("Go struct field %s has `format` tag option that was not specified last", sf.Name) case strings.HasPrefix(rawOpt, "'") && strings.TrimFunc(opt, isLetterOrDigit) == "": return fieldOptions{}, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", sf.Name, rawOpt, opt) } switch opt { case "nocase": out.nocase = true case "inline": out.inline = true case "unknown": out.unknown = true case "omitzero": out.omitzero = true case "omitempty": out.omitempty = true case "string": out.string = true case "format": if !strings.HasPrefix(tag, ":") { return fieldOptions{}, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name) } tag = tag[len(":"):] opt, n, err := consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err) } tag = tag[n:] out.format = opt wasFormat = true default: // Reject keys that resemble one of the supported options. // This catches invalid mutants such as "omitEmpty" or "omit_empty". normOpt := strings.ReplaceAll(strings.ToLower(opt), "_", "") switch normOpt { case "nocase", "inline", "unknown", "omitzero", "omitempty", "string", "format": return fieldOptions{}, fmt.Errorf("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", sf.Name, opt, normOpt) } // NOTE: Everything else is ignored. This does not mean it is // forward compatible to insert arbitrary tag options since // a future version of this package may understand that tag. } // Reject duplicates. if seenOpts[opt] { return fieldOptions{}, fmt.Errorf("Go struct field %s has duplicate appearance of `%s` tag option", sf.Name, rawOpt) } seenOpts[opt] = true } return out, nil } func consumeTagOption(in string) (string, int, error) { switch r, _ := utf8.DecodeRuneInString(in); { // Option as a Go identifier. case r == '_' || unicode.IsLetter(r): n := len(in) - len(strings.TrimLeftFunc(in, isLetterOrDigit)) return in[:n], n, nil // Option as a single-quoted string. case r == '\'': // The grammar is nearly identical to a double-quoted Go string literal, // but uses single quotes as the terminators. The reason for a custom // grammar is because both backtick and double quotes cannot be used // verbatim in a struct tag. // // Convert a single-quoted string to a double-quote string and rely on // strconv.Unquote to handle the rest. var inEscape bool b := []byte{'"'} n := len(`'`) for len(in) > n { r, rn := utf8.DecodeRuneInString(in[n:]) switch { case inEscape: if r == '\'' { b = b[:len(b)-1] // remove escape character: `\'` => `'` } inEscape = false case r == '\\': inEscape = true case r == '"': b = append(b, '\\') // insert escape character: `"` => `\"` case r == '\'': b = append(b, '"') n += len(`'`) out, err := strconv.Unquote(string(b)) if err != nil { return "", 0, fmt.Errorf("invalid single-quoted string: %s", in[:n]) } return out, n, nil } b = append(b, in[n:][:rn]...) n += rn } if n > 10 { n = 10 // limit the amount of context printed in the error } return "", 0, fmt.Errorf("single-quoted string not terminated: %s...", in[:n]) case len(in) == 0: return "", 0, io.ErrUnexpectedEOF default: return "", 0, fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", r) } } func isLetterOrDigit(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go
/* 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 handler3 import ( "bytes" "crypto/sha512" "encoding/json" "fmt" "net/http" "net/url" "path" "strconv" "strings" "sync" "time" openapi_v3 "github.com/google/gnostic-models/openapiv3" "github.com/google/uuid" "github.com/munnerz/goautoneg" "google.golang.org/protobuf/proto" "k8s.io/klog/v2" "k8s.io/kube-openapi/pkg/cached" "k8s.io/kube-openapi/pkg/common" "k8s.io/kube-openapi/pkg/spec3" ) const ( subTypeProtobufDeprecated = "com.github.proto-openapi.spec.v3@v1.0+protobuf" subTypeProtobuf = "com.github.proto-openapi.spec.v3.v1.0+protobuf" subTypeJSON = "json" ) // OpenAPIV3Discovery is the format of the Discovery document for OpenAPI V3 // It maps Discovery paths to their corresponding URLs with a hash parameter included type OpenAPIV3Discovery struct { Paths map[string]OpenAPIV3DiscoveryGroupVersion `json:"paths"` } // OpenAPIV3DiscoveryGroupVersion includes information about a group version and URL // for accessing the OpenAPI. The URL includes a hash parameter to support client side caching type OpenAPIV3DiscoveryGroupVersion struct { // Path is an absolute path of an OpenAPI V3 document in the form of /openapi/v3/apis/apps/v1?hash=014fbff9a07c ServerRelativeURL string `json:"serverRelativeURL"` } func ToV3ProtoBinary(json []byte) ([]byte, error) { document, err := openapi_v3.ParseDocument(json) if err != nil { return nil, err } return proto.Marshal(document) } type timedSpec struct { spec []byte lastModified time.Time } // This type is protected by the lock on OpenAPIService. type openAPIV3Group struct { specCache cached.LastSuccess[*spec3.OpenAPI] pbCache cached.Value[timedSpec] jsonCache cached.Value[timedSpec] } func newOpenAPIV3Group() *openAPIV3Group { o := &openAPIV3Group{} o.jsonCache = cached.Transform[*spec3.OpenAPI](func(spec *spec3.OpenAPI, etag string, err error) (timedSpec, string, error) { if err != nil { return timedSpec{}, "", err } json, err := json.Marshal(spec) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: json, lastModified: time.Now()}, computeETag(json), nil }, &o.specCache) o.pbCache = cached.Transform(func(ts timedSpec, etag string, err error) (timedSpec, string, error) { if err != nil { return timedSpec{}, "", err } proto, err := ToV3ProtoBinary(ts.spec) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: proto, lastModified: ts.lastModified}, etag, nil }, o.jsonCache) return o } func (o *openAPIV3Group) UpdateSpec(openapi cached.Value[*spec3.OpenAPI]) { o.specCache.Store(openapi) } // OpenAPIService is the service responsible for serving OpenAPI spec. It has // the ability to safely change the spec while serving it. type OpenAPIService struct { // Mutex protects the schema map. mutex sync.Mutex v3Schema map[string]*openAPIV3Group discoveryCache cached.LastSuccess[timedSpec] } func computeETag(data []byte) string { if data == nil { return "" } return fmt.Sprintf("%X", sha512.Sum512(data)) } func constructServerRelativeURL(gvString, etag string) string { u := url.URL{Path: path.Join("/openapi/v3", gvString)} query := url.Values{} query.Set("hash", etag) u.RawQuery = query.Encode() return u.String() } // NewOpenAPIService builds an OpenAPIService starting with the given spec. func NewOpenAPIService() *OpenAPIService { o := &OpenAPIService{} o.v3Schema = make(map[string]*openAPIV3Group) // We're not locked because we haven't shared the structure yet. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) return o } func (o *OpenAPIService) buildDiscoveryCacheLocked() cached.Value[timedSpec] { caches := make(map[string]cached.Value[timedSpec], len(o.v3Schema)) for gvName, group := range o.v3Schema { caches[gvName] = group.jsonCache } return cached.Merge(func(results map[string]cached.Result[timedSpec]) (timedSpec, string, error) { discovery := &OpenAPIV3Discovery{Paths: make(map[string]OpenAPIV3DiscoveryGroupVersion)} for gvName, result := range results { if result.Err != nil { return timedSpec{}, "", result.Err } discovery.Paths[gvName] = OpenAPIV3DiscoveryGroupVersion{ ServerRelativeURL: constructServerRelativeURL(gvName, result.Etag), } } j, err := json.Marshal(discovery) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: j, lastModified: time.Now()}, computeETag(j), nil }, caches) } func (o *OpenAPIService) getSingleGroupBytes(getType string, group string) ([]byte, string, time.Time, error) { o.mutex.Lock() defer o.mutex.Unlock() v, ok := o.v3Schema[group] if !ok { return nil, "", time.Now(), fmt.Errorf("Cannot find CRD group %s", group) } switch getType { case subTypeJSON: ts, etag, err := v.jsonCache.Get() return ts.spec, etag, ts.lastModified, err case subTypeProtobuf, subTypeProtobufDeprecated: ts, etag, err := v.pbCache.Get() return ts.spec, etag, ts.lastModified, err default: return nil, "", time.Now(), fmt.Errorf("Invalid accept clause %s", getType) } } // UpdateGroupVersionLazy adds or updates an existing group with the new cached. func (o *OpenAPIService) UpdateGroupVersionLazy(group string, openapi cached.Value[*spec3.OpenAPI]) { o.mutex.Lock() defer o.mutex.Unlock() if _, ok := o.v3Schema[group]; !ok { o.v3Schema[group] = newOpenAPIV3Group() // Since there is a new item, we need to re-build the cache map. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) } o.v3Schema[group].UpdateSpec(openapi) } func (o *OpenAPIService) UpdateGroupVersion(group string, openapi *spec3.OpenAPI) { o.UpdateGroupVersionLazy(group, cached.Static(openapi, uuid.New().String())) } func (o *OpenAPIService) DeleteGroupVersion(group string) { o.mutex.Lock() defer o.mutex.Unlock() delete(o.v3Schema, group) // Rebuild the merge cache map since the items have changed. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) } func (o *OpenAPIService) HandleDiscovery(w http.ResponseWriter, r *http.Request) { ts, etag, err := o.discoveryCache.Get() if err != nil { klog.Errorf("Error serving discovery: %s", err) w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Etag", strconv.Quote(etag)) w.Header().Set("Content-Type", "application/json") http.ServeContent(w, r, "/openapi/v3", ts.lastModified, bytes.NewReader(ts.spec)) } func (o *OpenAPIService) HandleGroupVersion(w http.ResponseWriter, r *http.Request) { url := strings.SplitAfterN(r.URL.Path, "/", 4) group := url[3] decipherableFormats := r.Header.Get("Accept") if decipherableFormats == "" { decipherableFormats = "*/*" } clauses := goautoneg.ParseAccept(decipherableFormats) w.Header().Add("Vary", "Accept") if len(clauses) == 0 { return } accepted := []struct { Type string SubType string ReturnedContentType string }{ {"application", subTypeJSON, "application/" + subTypeJSON}, {"application", subTypeProtobuf, "application/" + subTypeProtobuf}, {"application", subTypeProtobufDeprecated, "application/" + subTypeProtobuf}, } for _, clause := range clauses { for _, accepts := range accepted { if clause.Type != accepts.Type && clause.Type != "*" { continue } if clause.SubType != accepts.SubType && clause.SubType != "*" { continue } data, etag, lastModified, err := o.getSingleGroupBytes(accepts.SubType, group) if err != nil { return } // Set Content-Type header in the reponse w.Header().Set("Content-Type", accepts.ReturnedContentType) // ETag must be enclosed in double quotes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag w.Header().Set("Etag", strconv.Quote(etag)) if hash := r.URL.Query().Get("hash"); hash != "" { if hash != etag { u := constructServerRelativeURL(group, etag) http.Redirect(w, r, u, 301) return } // The Vary header is required because the Accept header can // change the contents returned. This prevents clients from caching // protobuf as JSON and vice versa. w.Header().Set("Vary", "Accept") // Only set these headers when a hash is given. w.Header().Set("Cache-Control", "public, immutable") // Set the Expires directive to the maximum value of one year from the request, // effectively indicating that the cache never expires. w.Header().Set("Expires", time.Now().AddDate(1, 0, 0).Format(time.RFC1123)) } http.ServeContent(w, r, "", lastModified, bytes.NewReader(data)) return } } w.WriteHeader(406) return } func (o *OpenAPIService) RegisterOpenAPIV3VersionedService(servePath string, handler common.PathHandlerByGroupVersion) error { handler.Handle(servePath, http.HandlerFunc(o.HandleDiscovery)) handler.HandlePrefix(servePath+"/", http.HandlerFunc(o.HandleGroupVersion)) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields.go
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package json is forked from the Go standard library to enable us to find the // field of a struct that a given JSON key maps to. package json import ( "bytes" "fmt" "reflect" "sort" "strings" "sync" "unicode" "unicode/utf8" ) const ( patchStrategyTagKey = "patchStrategy" patchMergeKeyTagKey = "patchMergeKey" ) // Finds the patchStrategy and patchMergeKey struct tag fields on a given // struct field given the struct type and the JSON name of the field. // It returns field type, a slice of patch strategies, merge key and error. // TODO: fix the returned errors to be introspectable. func LookupPatchMetadataForStruct(t reflect.Type, jsonField string) ( elemType reflect.Type, patchStrategies []string, patchMergeKey string, e error) { if t.Kind() == reflect.Pointer { t = t.Elem() } if t.Kind() != reflect.Struct { e = fmt.Errorf("merging an object in json but data type is not struct, instead is: %s", t.Kind().String()) return } jf := []byte(jsonField) // Find the field that the JSON library would use. var f *field fields := cachedTypeFields(t) for i := range fields { ff := &fields[i] if bytes.Equal(ff.nameBytes, jf) { f = ff break } // Do case-insensitive comparison. if f == nil && ff.equalFold(ff.nameBytes, jf) { f = ff } } if f != nil { // Find the reflect.Value of the most preferential struct field. tjf := t.Field(f.index[0]) // we must navigate down all the anonymously included structs in the chain for i := 1; i < len(f.index); i++ { tjf = tjf.Type.Field(f.index[i]) } patchStrategy := tjf.Tag.Get(patchStrategyTagKey) patchMergeKey = tjf.Tag.Get(patchMergeKeyTagKey) patchStrategies = strings.Split(patchStrategy, ",") elemType = tjf.Type return } e = fmt.Errorf("unable to find api field in struct %s for the json field %q", t.Name(), jsonField) return } // A field represents a single field found in a struct. type field struct { name string nameBytes []byte // []byte(name) equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent tag bool // index is the sequence of indexes from the containing type fields to this field. // it is a slice because anonymous structs will need multiple navigation steps to correctly // resolve the proper fields index []int typ reflect.Type omitEmpty bool quoted bool } func (f field) String() string { return fmt.Sprintf("{name: %s, type: %v, tag: %v, index: %v, omitEmpty: %v, quoted: %v}", f.name, f.typ, f.tag, f.index, f.omitEmpty, f.quoted) } func fillField(f field) field { f.nameBytes = []byte(f.name) f.equalFold = foldFunc(f.nameBytes) return f } // byName sorts field by name, breaking ties with depth, // then breaking ties with "name came from json tag", then // breaking ties with index sequence. type byName []field func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byName) Less(i, j int) bool { if x[i].name != x[j].name { return x[i].name < x[j].name } if len(x[i].index) != len(x[j].index) { return len(x[i].index) < len(x[j].index) } if x[i].tag != x[j].tag { return x[i].tag } return byIndex(x).Less(i, j) } // byIndex sorts field by index sequence. type byIndex []field func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byIndex) Less(i, j int) bool { for k, xik := range x[i].index { if k >= len(x[j].index) { return false } if xik != x[j].index[k] { return xik < x[j].index[k] } } return len(x[i].index) < len(x[j].index) } // typeFields returns a list of fields that JSON should recognize for the given type. // The algorithm is breadth-first search over the set of structs to include - the top struct // and then any reachable anonymous structs. func typeFields(t reflect.Type) []field { // Anonymous fields to explore at the current level and the next. current := []field{} next := []field{{typ: t}} // Count of queued names for current level and the next. count := map[reflect.Type]int{} nextCount := map[reflect.Type]int{} // Types already visited at an earlier level. visited := map[reflect.Type]bool{} // Fields found. var fields []field for len(next) > 0 { current, next = next, current[:0] count, nextCount = nextCount, map[reflect.Type]int{} for _, f := range current { if visited[f.typ] { continue } visited[f.typ] = true // Scan f.typ for fields to include. for i := 0; i < f.typ.NumField(); i++ { sf := f.typ.Field(i) if sf.PkgPath != "" { // unexported continue } tag := sf.Tag.Get("json") if tag == "-" { continue } name, opts := parseTag(tag) if !isValidTag(name) { name = "" } index := make([]int, len(f.index)+1) copy(index, f.index) index[len(f.index)] = i ft := sf.Type if ft.Name() == "" && ft.Kind() == reflect.Pointer { // Follow pointer. ft = ft.Elem() } // Record found field and index sequence. if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { tagged := name != "" if name == "" { name = sf.Name } fields = append(fields, fillField(field{ name: name, tag: tagged, index: index, typ: ft, omitEmpty: opts.Contains("omitempty"), quoted: opts.Contains("string"), })) if count[f.typ] > 1 { // If there were multiple instances, add a second, // so that the annihilation code will see a duplicate. // It only cares about the distinction between 1 or 2, // so don't bother generating any more copies. fields = append(fields, fields[len(fields)-1]) } continue } // Record new anonymous struct to explore in next round. nextCount[ft]++ if nextCount[ft] == 1 { next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) } } } } sort.Sort(byName(fields)) // Delete all fields that are hidden by the Go rules for embedded fields, // except that fields with JSON tags are promoted. // The fields are sorted in primary order of name, secondary order // of field index length. Loop over names; for each name, delete // hidden fields by choosing the one dominant field that survives. out := fields[:0] for advance, i := 0, 0; i < len(fields); i += advance { // One iteration per name. // Find the sequence of fields with the name of this first field. fi := fields[i] name := fi.name for advance = 1; i+advance < len(fields); advance++ { fj := fields[i+advance] if fj.name != name { break } } if advance == 1 { // Only one field with this name out = append(out, fi) continue } dominant, ok := dominantField(fields[i : i+advance]) if ok { out = append(out, dominant) } } fields = out sort.Sort(byIndex(fields)) return fields } // dominantField looks through the fields, all of which are known to // have the same name, to find the single field that dominates the // others using Go's embedding rules, modified by the presence of // JSON tags. If there are multiple top-level fields, the boolean // will be false: This condition is an error in Go and we skip all // the fields. func dominantField(fields []field) (field, bool) { // The fields are sorted in increasing index-length order. The winner // must therefore be one with the shortest index length. Drop all // longer entries, which is easy: just truncate the slice. length := len(fields[0].index) tagged := -1 // Index of first tagged field. for i, f := range fields { if len(f.index) > length { fields = fields[:i] break } if f.tag { if tagged >= 0 { // Multiple tagged fields at the same level: conflict. // Return no field. return field{}, false } tagged = i } } if tagged >= 0 { return fields[tagged], true } // All remaining fields have the same length. If there's more than one, // we have a conflict (two fields named "X" at the same level) and we // return no field. if len(fields) > 1 { return field{}, false } return fields[0], true } var fieldCache struct { sync.RWMutex m map[reflect.Type][]field } // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. func cachedTypeFields(t reflect.Type) []field { fieldCache.RLock() f := fieldCache.m[t] fieldCache.RUnlock() if f != nil { return f } // Compute fields without lock. // Might duplicate effort but won't hold other computations back. f = typeFields(t) if f == nil { f = []field{} } fieldCache.Lock() if fieldCache.m == nil { fieldCache.m = map[reflect.Type][]field{} } fieldCache.m[t] = f fieldCache.Unlock() return f } func isValidTag(s string) bool { if s == "" { return false } for _, c := range s { switch { case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): // Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name. default: if !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } return true } const ( caseMask = ^byte(0x20) // Mask to ignore case in ASCII. kelvin = '\u212a' smallLongEss = '\u017f' ) // foldFunc returns one of four different case folding equivalence // functions, from most general (and slow) to fastest: // // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') // 3) asciiEqualFold, no special, but includes non-letters (including _) // 4) simpleLetterEqualFold, no specials, no non-letters. // // The letters S and K are special because they map to 3 runes, not just 2: // * S maps to s and to U+017F 'ΕΏ' Latin small letter long s // * k maps to K and to U+212A 'β„ͺ' Kelvin sign // See http://play.golang.org/p/tTxjOc0OGo // // The returned function is specialized for matching against s and // should only be given s. It's not curried for performance reasons. func foldFunc(s []byte) func(s, t []byte) bool { nonLetter := false special := false // special letter for _, b := range s { if b >= utf8.RuneSelf { return bytes.EqualFold } upper := b & caseMask if upper < 'A' || upper > 'Z' { nonLetter = true } else if upper == 'K' || upper == 'S' { // See above for why these letters are special. special = true } } if special { return equalFoldRight } if nonLetter { return asciiEqualFold } return simpleLetterEqualFold } // equalFoldRight is a specialization of bytes.EqualFold when s is // known to be all ASCII (including punctuation), but contains an 's', // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. // See comments on foldFunc. func equalFoldRight(s, t []byte) bool { for _, sb := range s { if len(t) == 0 { return false } tb := t[0] if tb < utf8.RuneSelf { if sb != tb { sbUpper := sb & caseMask if 'A' <= sbUpper && sbUpper <= 'Z' { if sbUpper != tb&caseMask { return false } } else { return false } } t = t[1:] continue } // sb is ASCII and t is not. t must be either kelvin // sign or long s; sb must be s, S, k, or K. tr, size := utf8.DecodeRune(t) switch sb { case 's', 'S': if tr != smallLongEss { return false } case 'k', 'K': if tr != kelvin { return false } default: return false } t = t[size:] } if len(t) > 0 { return false } return true } // asciiEqualFold is a specialization of bytes.EqualFold for use when // s is all ASCII (but may contain non-letters) and contains no // special-folding letters. // See comments on foldFunc. func asciiEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, sb := range s { tb := t[i] if sb == tb { continue } if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { if sb&caseMask != tb&caseMask { return false } } else { return false } } return true } // simpleLetterEqualFold is a specialization of bytes.EqualFold for // use when s is all ASCII letters (no underscores, etc) and also // doesn't contain 'k', 'K', 's', or 'S'. // See comments on foldFunc. func simpleLetterEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, b := range s { if b&caseMask != t[i]&caseMask { return false } } return true } // tagOptions is the string following a comma in a struct field's "json" // tag, or the empty string. It does not include the leading comma. type tagOptions string // parseTag splits a struct field's json tag into its name and // comma-separated options. func parseTag(tag string) (string, tagOptions) { if idx := strings.Index(tag, ","); idx != -1 { return tag[:idx], tagOptions(tag[idx+1:]) } return tag, tagOptions("") } // Contains reports whether a comma-separated list of options // contains a particular substr flag. substr must be surrounded by a // string boundary or commas. func (o tagOptions) Contains(optionName string) bool { if len(o) == 0 { return false } s := string(o) for s != "" { var next string i := strings.Index(s, ",") if i >= 0 { s, next = s[:i], s[i+1:] } if s == optionName { return true } s = next } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package reflect is a fork of go's standard library reflection package, which // allows for deep equal with equality functions defined. package reflect import ( "fmt" "reflect" "strings" ) // Equalities is a map from type to a function comparing two values of // that type. type Equalities map[reflect.Type]reflect.Value // For convenience, panics on errors func EqualitiesOrDie(funcs ...interface{}) Equalities { e := Equalities{} if err := e.AddFuncs(funcs...); err != nil { panic(err) } return e } // AddFuncs is a shortcut for multiple calls to AddFunc. func (e Equalities) AddFuncs(funcs ...interface{}) error { for _, f := range funcs { if err := e.AddFunc(f); err != nil { return err } } return nil } // AddFunc uses func as an equality function: it must take // two parameters of the same type, and return a boolean. func (e Equalities) AddFunc(eqFunc interface{}) error { fv := reflect.ValueOf(eqFunc) ft := fv.Type() if ft.Kind() != reflect.Func { return fmt.Errorf("expected func, got: %v", ft) } if ft.NumIn() != 2 { return fmt.Errorf("expected two 'in' params, got: %v", ft) } if ft.NumOut() != 1 { return fmt.Errorf("expected one 'out' param, got: %v", ft) } if ft.In(0) != ft.In(1) { return fmt.Errorf("expected arg 1 and 2 to have same type, but got %v", ft) } var forReturnType bool boolType := reflect.TypeOf(forReturnType) if ft.Out(0) != boolType { return fmt.Errorf("expected bool return, got: %v", ft) } e[ft.In(0)] = fv return nil } // Below here is forked from go's reflect/deepequal.go // During deepValueEqual, must keep track of checks that are // in progress. The comparison algorithm assumes that all // checks in progress are true when it reencounters them. // Visited comparisons are stored in a map indexed by visit. type visit struct { a1 uintptr a2 uintptr typ reflect.Type } // unexportedTypePanic is thrown when you use this DeepEqual on something that has an // unexported type. It indicates a programmer error, so should not occur at runtime, // which is why it's not public and thus impossible to catch. type unexportedTypePanic []reflect.Type func (u unexportedTypePanic) Error() string { return u.String() } func (u unexportedTypePanic) String() string { strs := make([]string, len(u)) for i, t := range u { strs[i] = fmt.Sprintf("%v", t) } return "an unexported field was encountered, nested like this: " + strings.Join(strs, " -> ") } func makeUsefulPanic(v reflect.Value) { if x := recover(); x != nil { if u, ok := x.(unexportedTypePanic); ok { u = append(unexportedTypePanic{v.Type()}, u...) x = u } panic(x) } } // Tests for deep equality using reflected types. The map argument tracks // comparisons that have already been seen, which allows short circuiting on // recursive types. // equateNilAndEmpty controls whether empty maps/slices are equivalent to nil func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, equateNilAndEmpty bool, depth int) bool { defer makeUsefulPanic(v1) if !v1.IsValid() || !v2.IsValid() { return v1.IsValid() == v2.IsValid() } if v1.Type() != v2.Type() { return false } if fv, ok := e[v1.Type()]; ok { return fv.Call([]reflect.Value{v1, v2})[0].Bool() } hard := func(k reflect.Kind) bool { switch k { case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: return true } return false } if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { addr1 := v1.UnsafeAddr() addr2 := v2.UnsafeAddr() if addr1 > addr2 { // Canonicalize order to reduce number of entries in visited. addr1, addr2 = addr2, addr1 } // Short circuit if references are identical ... if addr1 == addr2 { return true } // ... or already seen typ := v1.Type() v := visit{addr1, addr2, typ} if visited[v] { return true } // Remember for later. visited[v] = true } switch v1.Kind() { case reflect.Array: // We don't need to check length here because length is part of // an array's type, which has already been filtered for. for i := 0; i < v1.Len(); i++ { if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Slice: if equateNilAndEmpty { if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { return false } if v1.IsNil() || v1.Len() == 0 { return true } } else { if v1.IsNil() != v2.IsNil() { return false } // Optimize nil and empty cases // Two lists that are BOTH nil are equal // No need to check v2 is nil since v1.IsNil == v2.IsNil from above if v1.IsNil() { return true } // Two lists that are both empty and both non nil are equal if v1.Len() == 0 || v2.Len() == 0 { return true } } if v1.Len() != v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for i := 0; i < v1.Len(); i++ { if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Interface: if v1.IsNil() || v2.IsNil() { return v1.IsNil() == v2.IsNil() } return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, equateNilAndEmpty, depth+1) case reflect.Ptr: return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, equateNilAndEmpty, depth+1) case reflect.Struct: for i, n := 0, v1.NumField(); i < n; i++ { if !e.deepValueEqual(v1.Field(i), v2.Field(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Map: if equateNilAndEmpty { if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { return false } if v1.IsNil() || v1.Len() == 0 { return true } } else { if v1.IsNil() != v2.IsNil() { return false } // Optimize nil and empty cases // Two maps that are BOTH nil are equal // No need to check v2 is nil since v1.IsNil == v2.IsNil from above if v1.IsNil() { return true } // Two maps that are both empty and both non nil are equal if v1.Len() == 0 || v2.Len() == 0 { return true } } if v1.Len() != v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for _, k := range v1.MapKeys() { if !e.deepValueEqual(v1.MapIndex(k), v2.MapIndex(k), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Func: if v1.IsNil() && v2.IsNil() { return true } // Can't do better than this: return false default: // Normal equality suffices if !v1.CanInterface() || !v2.CanInterface() { panic(unexportedTypePanic{}) } return v1.Interface() == v2.Interface() } } // DeepEqual is like reflect.DeepEqual, but focused on semantic equality // instead of memory equality. // // It will use e's equality functions if it finds types that match. // // An empty slice *is* equal to a nil slice for our purposes; same for maps. // // Unexported field members cannot be compared and will cause an informative panic; you must add an Equality // function for these types. func (e Equalities) DeepEqual(a1, a2 interface{}) bool { return e.deepEqual(a1, a2, true) } func (e Equalities) DeepEqualWithNilDifferentFromEmpty(a1, a2 interface{}) bool { return e.deepEqual(a1, a2, false) } func (e Equalities) deepEqual(a1, a2 interface{}, equateNilAndEmpty bool) bool { if a1 == nil || a2 == nil { return a1 == a2 } v1 := reflect.ValueOf(a1) v2 := reflect.ValueOf(a2) if v1.Type() != v2.Type() { return false } return e.deepValueEqual(v1, v2, make(map[visit]bool), equateNilAndEmpty, 0) } func (e Equalities) deepValueDerive(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool { defer makeUsefulPanic(v1) if !v1.IsValid() || !v2.IsValid() { return v1.IsValid() == v2.IsValid() } if v1.Type() != v2.Type() { return false } if fv, ok := e[v1.Type()]; ok { return fv.Call([]reflect.Value{v1, v2})[0].Bool() } hard := func(k reflect.Kind) bool { switch k { case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: return true } return false } if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { addr1 := v1.UnsafeAddr() addr2 := v2.UnsafeAddr() if addr1 > addr2 { // Canonicalize order to reduce number of entries in visited. addr1, addr2 = addr2, addr1 } // Short circuit if references are identical ... if addr1 == addr2 { return true } // ... or already seen typ := v1.Type() v := visit{addr1, addr2, typ} if visited[v] { return true } // Remember for later. visited[v] = true } switch v1.Kind() { case reflect.Array: // We don't need to check length here because length is part of // an array's type, which has already been filtered for. for i := 0; i < v1.Len(); i++ { if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { return false } } return true case reflect.Slice: if v1.IsNil() || v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for i := 0; i < v1.Len(); i++ { if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { return false } } return true case reflect.String: if v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } return v1.String() == v2.String() case reflect.Interface: if v1.IsNil() { return true } return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) case reflect.Pointer: if v1.IsNil() { return true } return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) case reflect.Struct: for i, n := 0, v1.NumField(); i < n; i++ { if !e.deepValueDerive(v1.Field(i), v2.Field(i), visited, depth+1) { return false } } return true case reflect.Map: if v1.IsNil() || v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for _, k := range v1.MapKeys() { if !e.deepValueDerive(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) { return false } } return true case reflect.Func: if v1.IsNil() && v2.IsNil() { return true } // Can't do better than this: return false default: // Normal equality suffices if !v1.CanInterface() || !v2.CanInterface() { panic(unexportedTypePanic{}) } return v1.Interface() == v2.Interface() } } // DeepDerivative is similar to DeepEqual except that unset fields in a1 are // ignored (not compared). This allows us to focus on the fields that matter to // the semantic comparison. // // The unset fields include a nil pointer and an empty string. func (e Equalities) DeepDerivative(a1, a2 interface{}) bool { if a1 == nil { return true } v1 := reflect.ValueOf(a1) v2 := reflect.ValueOf(a2) if v1.Type() != v2.Type() { return false } return e.deepValueDerive(v1, v2, make(map[visit]bool), 0) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 validation import ( "fmt" "math" "regexp" "strings" "unicode" "k8s.io/apimachinery/pkg/util/validation/field" netutils "k8s.io/utils/net" ) const qnameCharFmt string = "[A-Za-z0-9]" const qnameExtCharFmt string = "[-A-Za-z0-9_.]" const qualifiedNameFmt string = "(" + qnameCharFmt + qnameExtCharFmt + "*)?" + qnameCharFmt const qualifiedNameErrMsg string = "must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" const qualifiedNameMaxLength int = 63 var qualifiedNameRegexp = regexp.MustCompile("^" + qualifiedNameFmt + "$") // IsQualifiedName tests whether the value passed is what Kubernetes calls a // "qualified name". This is a format used in various places throughout the // system. If the value is not valid, a list of error strings is returned. // Otherwise an empty list (or nil) is returned. func IsQualifiedName(value string) []string { var errs []string parts := strings.Split(value, "/") var name string switch len(parts) { case 1: name = parts[0] case 2: var prefix string prefix, name = parts[0], parts[1] if len(prefix) == 0 { errs = append(errs, "prefix part "+EmptyError()) } else if msgs := IsDNS1123Subdomain(prefix); len(msgs) != 0 { errs = append(errs, prefixEach(msgs, "prefix part ")...) } default: return append(errs, "a qualified name "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")+ " with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')") } if len(name) == 0 { errs = append(errs, "name part "+EmptyError()) } else if len(name) > qualifiedNameMaxLength { errs = append(errs, "name part "+MaxLenError(qualifiedNameMaxLength)) } if !qualifiedNameRegexp.MatchString(name) { errs = append(errs, "name part "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")) } return errs } // IsFullyQualifiedName checks if the name is fully qualified. This is similar // to IsFullyQualifiedDomainName but requires a minimum of 3 segments instead of // 2 and does not accept a trailing . as valid. // TODO: This function is deprecated and preserved until all callers migrate to // IsFullyQualifiedDomainName; please don't add new callers. func IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList { var allErrors field.ErrorList if len(name) == 0 { return append(allErrors, field.Required(fldPath, "")) } if errs := IsDNS1123Subdomain(name); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ","))) } if len(strings.Split(name, ".")) < 3 { return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least three segments separated by dots")) } return allErrors } // IsFullyQualifiedDomainName checks if the domain name is fully qualified. This // is similar to IsFullyQualifiedName but only requires a minimum of 2 segments // instead of 3 and accepts a trailing . as valid. func IsFullyQualifiedDomainName(fldPath *field.Path, name string) field.ErrorList { var allErrors field.ErrorList if len(name) == 0 { return append(allErrors, field.Required(fldPath, "")) } if strings.HasSuffix(name, ".") { name = name[:len(name)-1] } if errs := IsDNS1123Subdomain(name); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ","))) } if len(strings.Split(name, ".")) < 2 { return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least two segments separated by dots")) } for _, label := range strings.Split(name, ".") { if errs := IsDNS1123Label(label); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, label, strings.Join(errs, ","))) } } return allErrors } // Allowed characters in an HTTP Path as defined by RFC 3986. A HTTP path may // contain: // * unreserved characters (alphanumeric, '-', '.', '_', '~') // * percent-encoded octets // * sub-delims ("!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=") // * a colon character (":") const httpPathFmt string = `[A-Za-z0-9/\-._~%!$&'()*+,;=:]+` var httpPathRegexp = regexp.MustCompile("^" + httpPathFmt + "$") // IsDomainPrefixedPath checks if the given string is a domain-prefixed path // (e.g. acme.io/foo). All characters before the first "/" must be a valid // subdomain as defined by RFC 1123. All characters trailing the first "/" must // be valid HTTP Path characters as defined by RFC 3986. func IsDomainPrefixedPath(fldPath *field.Path, dpPath string) field.ErrorList { var allErrs field.ErrorList if len(dpPath) == 0 { return append(allErrs, field.Required(fldPath, "")) } segments := strings.SplitN(dpPath, "/", 2) if len(segments) != 2 || len(segments[0]) == 0 || len(segments[1]) == 0 { return append(allErrs, field.Invalid(fldPath, dpPath, "must be a domain-prefixed path (such as \"acme.io/foo\")")) } host := segments[0] for _, err := range IsDNS1123Subdomain(host) { allErrs = append(allErrs, field.Invalid(fldPath, host, err)) } path := segments[1] if !httpPathRegexp.MatchString(path) { return append(allErrs, field.Invalid(fldPath, path, RegexError("Invalid path", httpPathFmt))) } return allErrs } const labelValueFmt string = "(" + qualifiedNameFmt + ")?" const labelValueErrMsg string = "a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" // LabelValueMaxLength is a label's max length const LabelValueMaxLength int = 63 var labelValueRegexp = regexp.MustCompile("^" + labelValueFmt + "$") // IsValidLabelValue tests whether the value passed is a valid label value. If // the value is not valid, a list of error strings is returned. Otherwise an // empty list (or nil) is returned. func IsValidLabelValue(value string) []string { var errs []string if len(value) > LabelValueMaxLength { errs = append(errs, MaxLenError(LabelValueMaxLength)) } if !labelValueRegexp.MatchString(value) { errs = append(errs, RegexError(labelValueErrMsg, labelValueFmt, "MyValue", "my_value", "12345")) } return errs } const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" const dns1123LabelFmtWithUnderscore string = "_?[a-z0-9]([-_a-z0-9]*[a-z0-9])?" const dns1123LabelErrMsg string = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character" // DNS1123LabelMaxLength is a label's max length in DNS (RFC 1123) const DNS1123LabelMaxLength int = 63 var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$") // IsDNS1123Label tests for a string that conforms to the definition of a label in // DNS (RFC 1123). func IsDNS1123Label(value string) []string { var errs []string if len(value) > DNS1123LabelMaxLength { errs = append(errs, MaxLenError(DNS1123LabelMaxLength)) } if !dns1123LabelRegexp.MatchString(value) { if dns1123SubdomainRegexp.MatchString(value) { // It was a valid subdomain and not a valid label. Since we // already checked length, it must be dots. errs = append(errs, "must not contain dots") } else { errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc")) } } return errs } const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*" const dns1123SubdomainErrorMsg string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character" const dns1123SubdomainFmtWithUnderscore string = dns1123LabelFmtWithUnderscore + "(\\." + dns1123LabelFmtWithUnderscore + ")*" const dns1123SubdomainErrorMsgFG string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '_', '-' or '.', and must start and end with an alphanumeric character" // DNS1123SubdomainMaxLength is a subdomain's max length in DNS (RFC 1123) const DNS1123SubdomainMaxLength int = 253 var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$") var dns1123SubdomainRegexpWithUnderscore = regexp.MustCompile("^" + dns1123SubdomainFmtWithUnderscore + "$") // IsDNS1123Subdomain tests for a string that conforms to the definition of a // subdomain in DNS (RFC 1123). func IsDNS1123Subdomain(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !dns1123SubdomainRegexp.MatchString(value) { errs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, "example.com")) } return errs } // IsDNS1123SubdomainWithUnderscore tests for a string that conforms to the definition of a // subdomain in DNS (RFC 1123), but allows the use of an underscore in the string func IsDNS1123SubdomainWithUnderscore(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !dns1123SubdomainRegexpWithUnderscore.MatchString(value) { errs = append(errs, RegexError(dns1123SubdomainErrorMsgFG, dns1123SubdomainFmt, "example.com")) } return errs } const dns1035LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?" const dns1035LabelErrMsg string = "a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character" // DNS1035LabelMaxLength is a label's max length in DNS (RFC 1035) const DNS1035LabelMaxLength int = 63 var dns1035LabelRegexp = regexp.MustCompile("^" + dns1035LabelFmt + "$") // IsDNS1035Label tests for a string that conforms to the definition of a label in // DNS (RFC 1035). func IsDNS1035Label(value string) []string { var errs []string if len(value) > DNS1035LabelMaxLength { errs = append(errs, MaxLenError(DNS1035LabelMaxLength)) } if !dns1035LabelRegexp.MatchString(value) { errs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, "my-name", "abc-123")) } return errs } // wildcard definition - RFC 1034 section 4.3.3. // examples: // - valid: *.bar.com, *.foo.bar.com // - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, * const wildcardDNS1123SubdomainFmt = "\\*\\." + dns1123SubdomainFmt const wildcardDNS1123SubdomainErrMsg = "a wildcard DNS-1123 subdomain must start with '*.', followed by a valid DNS subdomain, which must consist of lower case alphanumeric characters, '-' or '.' and end with an alphanumeric character" // IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a // wildcard subdomain in DNS (RFC 1034 section 4.3.3). func IsWildcardDNS1123Subdomain(value string) []string { wildcardDNS1123SubdomainRegexp := regexp.MustCompile("^" + wildcardDNS1123SubdomainFmt + "$") var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !wildcardDNS1123SubdomainRegexp.MatchString(value) { errs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, "*.example.com")) } return errs } const cIdentifierFmt string = "[A-Za-z_][A-Za-z0-9_]*" const identifierErrMsg string = "a valid C identifier must start with alphabetic character or '_', followed by a string of alphanumeric characters or '_'" var cIdentifierRegexp = regexp.MustCompile("^" + cIdentifierFmt + "$") // IsCIdentifier tests for a string that conforms the definition of an identifier // in C. This checks the format, but not the length. func IsCIdentifier(value string) []string { if !cIdentifierRegexp.MatchString(value) { return []string{RegexError(identifierErrMsg, cIdentifierFmt, "my_name", "MY_NAME", "MyName")} } return nil } // IsValidPortNum tests that the argument is a valid, non-zero port number. func IsValidPortNum(port int) []string { if 1 <= port && port <= 65535 { return nil } return []string{InclusiveRangeError(1, 65535)} } // IsInRange tests that the argument is in an inclusive range. func IsInRange(value int, min int, max int) []string { if value >= min && value <= max { return nil } return []string{InclusiveRangeError(min, max)} } // Now in libcontainer UID/GID limits is 0 ~ 1<<31 - 1 // TODO: once we have a type for UID/GID we should make these that type. const ( minUserID = 0 maxUserID = math.MaxInt32 minGroupID = 0 maxGroupID = math.MaxInt32 ) // IsValidGroupID tests that the argument is a valid Unix GID. func IsValidGroupID(gid int64) []string { if minGroupID <= gid && gid <= maxGroupID { return nil } return []string{InclusiveRangeError(minGroupID, maxGroupID)} } // IsValidUserID tests that the argument is a valid Unix UID. func IsValidUserID(uid int64) []string { if minUserID <= uid && uid <= maxUserID { return nil } return []string{InclusiveRangeError(minUserID, maxUserID)} } var portNameCharsetRegex = regexp.MustCompile("^[-a-z0-9]+$") var portNameOneLetterRegexp = regexp.MustCompile("[a-z]") // IsValidPortName check that the argument is valid syntax. It must be // non-empty and no more than 15 characters long. It may contain only [-a-z0-9] // and must contain at least one letter [a-z]. It must not start or end with a // hyphen, nor contain adjacent hyphens. // // Note: We only allow lower-case characters, even though RFC 6335 is case // insensitive. func IsValidPortName(port string) []string { var errs []string if len(port) > 15 { errs = append(errs, MaxLenError(15)) } if !portNameCharsetRegex.MatchString(port) { errs = append(errs, "must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)") } if !portNameOneLetterRegexp.MatchString(port) { errs = append(errs, "must contain at least one letter (a-z)") } if strings.Contains(port, "--") { errs = append(errs, "must not contain consecutive hyphens") } if len(port) > 0 && (port[0] == '-' || port[len(port)-1] == '-') { errs = append(errs, "must not begin or end with a hyphen") } return errs } // IsValidIP tests that the argument is a valid IP address. func IsValidIP(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList if netutils.ParseIPSloppy(value) == nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)")) } return allErrors } // IsValidIPv4Address tests that the argument is a valid IPv4 address. func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() == nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv4 address")) } return allErrors } // IsValidIPv6Address tests that the argument is a valid IPv6 address. func IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() != nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv6 address")) } return allErrors } // IsValidCIDR tests that the argument is a valid CIDR value. func IsValidCIDR(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList _, _, err := netutils.ParseCIDRSloppy(value) if err != nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid CIDR value, (e.g. 10.9.8.0/24 or 2001:db8::/64)")) } return allErrors } const percentFmt string = "[0-9]+%" const percentErrMsg string = "a valid percent string must be a numeric string followed by an ending '%'" var percentRegexp = regexp.MustCompile("^" + percentFmt + "$") // IsValidPercent checks that string is in the form of a percentage func IsValidPercent(percent string) []string { if !percentRegexp.MatchString(percent) { return []string{RegexError(percentErrMsg, percentFmt, "1%", "93%")} } return nil } const httpHeaderNameFmt string = "[-A-Za-z0-9]+" const httpHeaderNameErrMsg string = "a valid HTTP header must consist of alphanumeric characters or '-'" var httpHeaderNameRegexp = regexp.MustCompile("^" + httpHeaderNameFmt + "$") // IsHTTPHeaderName checks that a string conforms to the Go HTTP library's // definition of a valid header field name (a stricter subset than RFC7230). func IsHTTPHeaderName(value string) []string { if !httpHeaderNameRegexp.MatchString(value) { return []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, "X-Header-Name")} } return nil } const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*" const envVarNameFmtErrMsg string = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit" // TODO(hirazawaui): Rename this when the RelaxedEnvironmentVariableValidation gate is removed. const relaxedEnvVarNameFmtErrMsg string = "a valid environment variable name must consist only of printable ASCII characters other than '='" var envVarNameRegexp = regexp.MustCompile("^" + envVarNameFmt + "$") // IsEnvVarName tests if a string is a valid environment variable name. func IsEnvVarName(value string) []string { var errs []string if !envVarNameRegexp.MatchString(value) { errs = append(errs, RegexError(envVarNameFmtErrMsg, envVarNameFmt, "my.env-name", "MY_ENV.NAME", "MyEnvName1")) } errs = append(errs, hasChDirPrefix(value)...) return errs } // IsRelaxedEnvVarName tests if a string is a valid environment variable name. func IsRelaxedEnvVarName(value string) []string { var errs []string if len(value) == 0 { errs = append(errs, "environment variable name "+EmptyError()) } for _, r := range value { if r > unicode.MaxASCII || !unicode.IsPrint(r) || r == '=' { errs = append(errs, relaxedEnvVarNameFmtErrMsg) break } } return errs } const configMapKeyFmt = `[-._a-zA-Z0-9]+` const configMapKeyErrMsg string = "a valid config key must consist of alphanumeric characters, '-', '_' or '.'" var configMapKeyRegexp = regexp.MustCompile("^" + configMapKeyFmt + "$") // IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret func IsConfigMapKey(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !configMapKeyRegexp.MatchString(value) { errs = append(errs, RegexError(configMapKeyErrMsg, configMapKeyFmt, "key.name", "KEY_NAME", "key-name")) } errs = append(errs, hasChDirPrefix(value)...) return errs } // MaxLenError returns a string explanation of a "string too long" validation // failure. func MaxLenError(length int) string { return fmt.Sprintf("must be no more than %d characters", length) } // RegexError returns a string explanation of a regex validation failure. func RegexError(msg string, fmt string, examples ...string) string { if len(examples) == 0 { return msg + " (regex used for validation is '" + fmt + "')" } msg += " (e.g. " for i := range examples { if i > 0 { msg += " or " } msg += "'" + examples[i] + "', " } msg += "regex used for validation is '" + fmt + "')" return msg } // EmptyError returns a string explanation of a "must not be empty" validation // failure. func EmptyError() string { return "must be non-empty" } func prefixEach(msgs []string, prefix string) []string { for i := range msgs { msgs[i] = prefix + msgs[i] } return msgs } // InclusiveRangeError returns a string explanation of a numeric "must be // between" validation failure. func InclusiveRangeError(lo, hi int) string { return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi) } func hasChDirPrefix(value string) []string { var errs []string switch { case value == ".": errs = append(errs, `must not be '.'`) case value == "..": errs = append(errs, `must not be '..'`) case strings.HasPrefix(value, ".."): errs = append(errs, `must not start with '..'`) } return errs }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go
/* 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 field import ( "bytes" "fmt" "strconv" ) type pathOptions struct { path *Path } // PathOption modifies a pathOptions type PathOption func(o *pathOptions) // WithPath generates a PathOption func WithPath(p *Path) PathOption { return func(o *pathOptions) { o.path = p } } // ToPath produces *Path from a set of PathOption func ToPath(opts ...PathOption) *Path { c := &pathOptions{} for _, opt := range opts { opt(c) } return c.path } // Path represents the path from some root to a particular field. type Path struct { name string // the name of this field or "" if this is an index index string // if name == "", this is a subscript (index or map key) of the previous element parent *Path // nil if this is the root element } // NewPath creates a root Path object. func NewPath(name string, moreNames ...string) *Path { r := &Path{name: name, parent: nil} for _, anotherName := range moreNames { r = &Path{name: anotherName, parent: r} } return r } // Root returns the root element of this Path. func (p *Path) Root() *Path { for ; p.parent != nil; p = p.parent { // Do nothing. } return p } // Child creates a new Path that is a child of the method receiver. func (p *Path) Child(name string, moreNames ...string) *Path { r := NewPath(name, moreNames...) r.Root().parent = p return r } // Index indicates that the previous Path is to be subscripted by an int. // This sets the same underlying value as Key. func (p *Path) Index(index int) *Path { return &Path{index: strconv.Itoa(index), parent: p} } // Key indicates that the previous Path is to be subscripted by a string. // This sets the same underlying value as Index. func (p *Path) Key(key string) *Path { return &Path{index: key, parent: p} } // String produces a string representation of the Path. func (p *Path) String() string { if p == nil { return "<nil>" } // make a slice to iterate elems := []*Path{} for ; p != nil; p = p.parent { elems = append(elems, p) } // iterate, but it has to be backwards buf := bytes.NewBuffer(nil) for i := range elems { p := elems[len(elems)-1-i] if p.parent != nil && len(p.name) > 0 { // This is either the root or it is a subscript. buf.WriteString(".") } if len(p.name) > 0 { buf.WriteString(p.name) } else { fmt.Fprintf(buf, "[%s]", p.index) } } return buf.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 field import ( "fmt" "reflect" "strconv" "strings" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" ) // Error is an implementation of the 'error' interface, which represents a // field-level validation error. type Error struct { Type ErrorType Field string BadValue interface{} Detail string } var _ error = &Error{} // Error implements the error interface. func (v *Error) Error() string { return fmt.Sprintf("%s: %s", v.Field, v.ErrorBody()) } type OmitValueType struct{} var omitValue = OmitValueType{} // ErrorBody returns the error message without the field name. This is useful // for building nice-looking higher-level error reporting. func (v *Error) ErrorBody() string { var s string switch { case v.Type == ErrorTypeRequired: s = v.Type.String() case v.Type == ErrorTypeForbidden: s = v.Type.String() case v.Type == ErrorTypeTooLong: s = v.Type.String() case v.Type == ErrorTypeInternal: s = v.Type.String() case v.BadValue == omitValue: s = v.Type.String() default: value := v.BadValue valueType := reflect.TypeOf(value) if value == nil || valueType == nil { value = "null" } else if valueType.Kind() == reflect.Pointer { if reflectValue := reflect.ValueOf(value); reflectValue.IsNil() { value = "null" } else { value = reflectValue.Elem().Interface() } } switch t := value.(type) { case int64, int32, float64, float32, bool: // use simple printer for simple types s = fmt.Sprintf("%s: %v", v.Type, value) case string: s = fmt.Sprintf("%s: %q", v.Type, t) case fmt.Stringer: // anything that defines String() is better than raw struct s = fmt.Sprintf("%s: %s", v.Type, t.String()) default: // fallback to raw struct // TODO: internal types have panic guards against json.Marshalling to prevent // accidental use of internal types in external serialized form. For now, use // %#v, although it would be better to show a more expressive output in the future s = fmt.Sprintf("%s: %#v", v.Type, value) } } if len(v.Detail) != 0 { s += fmt.Sprintf(": %s", v.Detail) } return s } // ErrorType is a machine readable value providing more detail about why // a field is invalid. These values are expected to match 1-1 with // CauseType in api/types.go. type ErrorType string // TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it. const ( // ErrorTypeNotFound is used to report failure to find a requested value // (e.g. looking up an ID). See NotFound(). ErrorTypeNotFound ErrorType = "FieldValueNotFound" // ErrorTypeRequired is used to report required values that are not // provided (e.g. empty strings, null values, or empty arrays). See // Required(). ErrorTypeRequired ErrorType = "FieldValueRequired" // ErrorTypeDuplicate is used to report collisions of values that must be // unique (e.g. unique IDs). See Duplicate(). ErrorTypeDuplicate ErrorType = "FieldValueDuplicate" // ErrorTypeInvalid is used to report malformed values (e.g. failed regex // match, too long, out of bounds). See Invalid(). ErrorTypeInvalid ErrorType = "FieldValueInvalid" // ErrorTypeNotSupported is used to report unknown values for enumerated // fields (e.g. a list of valid values). See NotSupported(). ErrorTypeNotSupported ErrorType = "FieldValueNotSupported" // ErrorTypeForbidden is used to report valid (as per formatting rules) // values which would be accepted under some conditions, but which are not // permitted by the current conditions (such as security policy). See // Forbidden(). ErrorTypeForbidden ErrorType = "FieldValueForbidden" // ErrorTypeTooLong is used to report that the given value is too long. // This is similar to ErrorTypeInvalid, but the error will not include the // too-long value. See TooLong(). ErrorTypeTooLong ErrorType = "FieldValueTooLong" // ErrorTypeTooMany is used to report "too many". This is used to // 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" // 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" ) // String converts a ErrorType into its corresponding canonical error message. func (t ErrorType) String() string { switch t { case ErrorTypeNotFound: return "Not found" case ErrorTypeRequired: return "Required value" case ErrorTypeDuplicate: return "Duplicate value" case ErrorTypeInvalid: return "Invalid value" case ErrorTypeNotSupported: return "Unsupported value" case ErrorTypeForbidden: return "Forbidden" case ErrorTypeTooLong: return "Too long" case ErrorTypeTooMany: return "Too many" case ErrorTypeInternal: return "Internal error" case ErrorTypeTypeInvalid: return "Invalid value" default: panic(fmt.Sprintf("unrecognized validation error: %q", string(t))) } } // TypeInvalid returns a *Error indicating "type is invalid" func TypeInvalid(field *Path, value interface{}, detail string) *Error { return &Error{ErrorTypeTypeInvalid, field.String(), value, 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, ""} } // 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} } // 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, ""} } // 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} } // NotSupported returns a *Error indicating "unsupported value". // This is used to report unknown values for enumerated fields (e.g. a list of // valid values). func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *Error { detail := "" if len(validValues) > 0 { quotedValues := make([]string, len(validValues)) for i, v := range validValues { quotedValues[i] = strconv.Quote(fmt.Sprint(v)) } detail = "supported values: " + strings.Join(quotedValues, ", ") } return &Error{ErrorTypeNotSupported, field.String(), value, detail} } // Forbidden returns a *Error indicating "forbidden". This is used to // report valid (as per formatting rules) values which would be accepted under // 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} } // TooLong returns a *Error indicating "too long". This is used to report that // the given value is too long. 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 TooLong(field *Path, value interface{}, maxLength int) *Error { var msg string if maxLength >= 0 { msg = fmt.Sprintf("may not be more than %d bytes", maxLength) } else { msg = "value is too long" } return &Error{ErrorTypeTooLong, field.String(), "<value omitted>", msg} } // TooLongMaxLength returns a *Error indicating "too long". // Deprecated: Use TooLong instead. func TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error { return TooLong(field, "", maxLength) } // TooMany returns a *Error indicating "too many". This is used to // report that a given list has too many items. This is similar to TooLong, // but the returned error indicates quantity instead of length. func TooMany(field *Path, actualQuantity, maxQuantity int) *Error { var msg string if maxQuantity >= 0 { msg = fmt.Sprintf("must have at most %d items", maxQuantity) } else { msg = "has too many items" } var actual interface{} if actualQuantity >= 0 { actual = actualQuantity } else { actual = omitValue } return &Error{ErrorTypeTooMany, field.String(), actual, 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()} } // ErrorList holds a set of Errors. It is plausible that we might one day have // non-field errors in this same umbrella package, but for now we don't, so // we can keep it simple and leave ErrorList here. type ErrorList []*Error // NewErrorTypeMatcher returns an errors.Matcher that returns true // if the provided error is a Error and has the provided ErrorType. func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher { return func(err error) bool { if e, ok := err.(*Error); ok { return e.Type == t } return false } } // ToAggregate converts the ErrorList into an errors.Aggregate. func (list ErrorList) ToAggregate() utilerrors.Aggregate { if len(list) == 0 { return nil } errs := make([]error, 0, len(list)) errorMsgs := sets.NewString() for _, err := range list { msg := fmt.Sprintf("%v", err) if errorMsgs.Has(msg) { continue } errorMsgs.Insert(msg) errs = append(errs, err) } return utilerrors.NewAggregate(errs) } func fromAggregate(agg utilerrors.Aggregate) ErrorList { errs := agg.Errors() list := make(ErrorList, len(errs)) for i := range errs { list[i] = errs[i].(*Error) } return list } // Filter removes items from the ErrorList that match the provided fns. func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList { err := utilerrors.FilterOut(list.ToAggregate(), fns...) if err == nil { return nil } // FilterOut takes an Aggregate and returns an Aggregate return fromAggregate(err.(utilerrors.Aggregate)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strategicpatch import ( "errors" "strings" "k8s.io/apimachinery/pkg/util/mergepatch" openapi "k8s.io/kube-openapi/pkg/util/proto" ) const ( patchStrategyOpenapiextensionKey = "x-kubernetes-patch-strategy" patchMergeKeyOpenapiextensionKey = "x-kubernetes-patch-merge-key" ) type LookupPatchItem interface { openapi.SchemaVisitor Error() error Path() *openapi.Path } type kindItem struct { key string path *openapi.Path err error patchmeta PatchMeta subschema openapi.Schema hasVisitKind bool } func NewKindItem(key string, path *openapi.Path) *kindItem { return &kindItem{ key: key, path: path, } } var _ LookupPatchItem = &kindItem{} func (item *kindItem) Error() error { return item.err } func (item *kindItem) Path() *openapi.Path { return item.path } func (item *kindItem) VisitPrimitive(schema *openapi.Primitive) { item.err = errors.New("expected kind, but got primitive") } func (item *kindItem) VisitArray(schema *openapi.Array) { item.err = errors.New("expected kind, but got slice") } func (item *kindItem) VisitMap(schema *openapi.Map) { item.err = errors.New("expected kind, but got map") } func (item *kindItem) VisitReference(schema openapi.Reference) { if !item.hasVisitKind { schema.SubSchema().Accept(item) } } func (item *kindItem) VisitKind(schema *openapi.Kind) { subschema, ok := schema.Fields[item.key] if !ok { item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key} return } mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions()) if err != nil { item.err = err return } item.patchmeta = PatchMeta{ patchStrategies: patchStrategies, patchMergeKey: mergeKey, } item.subschema = subschema } type sliceItem struct { key string path *openapi.Path err error patchmeta PatchMeta subschema openapi.Schema hasVisitKind bool } func NewSliceItem(key string, path *openapi.Path) *sliceItem { return &sliceItem{ key: key, path: path, } } var _ LookupPatchItem = &sliceItem{} func (item *sliceItem) Error() error { return item.err } func (item *sliceItem) Path() *openapi.Path { return item.path } func (item *sliceItem) VisitPrimitive(schema *openapi.Primitive) { item.err = errors.New("expected slice, but got primitive") } func (item *sliceItem) VisitArray(schema *openapi.Array) { if !item.hasVisitKind { item.err = errors.New("expected visit kind first, then visit array") } subschema := schema.SubType item.subschema = subschema } func (item *sliceItem) VisitMap(schema *openapi.Map) { item.err = errors.New("expected slice, but got map") } func (item *sliceItem) VisitReference(schema openapi.Reference) { if !item.hasVisitKind { schema.SubSchema().Accept(item) } else { item.subschema = schema.SubSchema() } } func (item *sliceItem) VisitKind(schema *openapi.Kind) { subschema, ok := schema.Fields[item.key] if !ok { item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key} return } mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions()) if err != nil { item.err = err return } item.patchmeta = PatchMeta{ patchStrategies: patchStrategies, patchMergeKey: mergeKey, } item.hasVisitKind = true subschema.Accept(item) } func parsePatchMetadata(extensions map[string]interface{}) (string, []string, error) { ps, foundPS := extensions[patchStrategyOpenapiextensionKey] var patchStrategies []string var mergeKey, patchStrategy string var ok bool if foundPS { patchStrategy, ok = ps.(string) if ok { patchStrategies = strings.Split(patchStrategy, ",") } else { return "", nil, mergepatch.ErrBadArgType(patchStrategy, ps) } } mk, foundMK := extensions[patchMergeKeyOpenapiextensionKey] if foundMK { mergeKey, ok = mk.(string) if !ok { return "", nil, mergepatch.ErrBadArgType(mergeKey, mk) } } return mergeKey, patchStrategies, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strategicpatch import ( "fmt" ) type LookupPatchMetaError struct { Path string Err error } func (e LookupPatchMetaError) Error() string { return fmt.Sprintf("LookupPatchMetaError(%s): %v", e.Path, e.Err) } type FieldNotFoundError struct { Path string Field string } func (e FieldNotFoundError) Error() string { return fmt.Sprintf("unable to find api field %q in %s", e.Field, e.Path) } type InvalidTypeError struct { Path string Expected string Actual string } func (e InvalidTypeError) Error() string { return fmt.Sprintf("invalid type for %s: got %q, expected %q", e.Path, e.Actual, e.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package strategicpatch import ( "errors" "fmt" "reflect" "strings" "k8s.io/apimachinery/pkg/util/mergepatch" forkedjson "k8s.io/apimachinery/third_party/forked/golang/json" openapi "k8s.io/kube-openapi/pkg/util/proto" "k8s.io/kube-openapi/pkg/validation/spec" ) const patchMergeKey = "x-kubernetes-patch-merge-key" const patchStrategy = "x-kubernetes-patch-strategy" type PatchMeta struct { patchStrategies []string patchMergeKey string } func (pm *PatchMeta) GetPatchStrategies() []string { if pm.patchStrategies == nil { return []string{} } return pm.patchStrategies } func (pm *PatchMeta) SetPatchStrategies(ps []string) { pm.patchStrategies = ps } func (pm *PatchMeta) GetPatchMergeKey() string { return pm.patchMergeKey } func (pm *PatchMeta) SetPatchMergeKey(pmk string) { pm.patchMergeKey = pmk } type LookupPatchMeta interface { // LookupPatchMetadataForStruct gets subschema and the patch metadata (e.g. patch strategy and merge key) for map. LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) // LookupPatchMetadataForSlice get subschema and the patch metadata for slice. LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) // Get the type name of the field Name() string } type PatchMetaFromStruct struct { T reflect.Type } func NewPatchMetaFromStruct(dataStruct interface{}) (PatchMetaFromStruct, error) { t, err := getTagStructType(dataStruct) return PatchMetaFromStruct{T: t}, err } var _ LookupPatchMeta = PatchMetaFromStruct{} func (s PatchMetaFromStruct) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { fieldType, fieldPatchStrategies, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadataForStruct(s.T, key) if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromStruct{T: fieldType}, PatchMeta{ patchStrategies: fieldPatchStrategies, patchMergeKey: fieldPatchMergeKey, }, nil } func (s PatchMetaFromStruct) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { subschema, patchMeta, err := s.LookupPatchMetadataForStruct(key) if err != nil { return nil, PatchMeta{}, err } elemPatchMetaFromStruct := subschema.(PatchMetaFromStruct) t := elemPatchMetaFromStruct.T var elemType reflect.Type switch t.Kind() { // If t is an array or a slice, get the element type. // If element is still an array or a slice, return an error. // Otherwise, return element type. case reflect.Array, reflect.Slice: elemType = t.Elem() if elemType.Kind() == reflect.Array || elemType.Kind() == reflect.Slice { return nil, PatchMeta{}, errors.New("unexpected slice of slice") } // If t is an pointer, get the underlying element. // If the underlying element is neither an array nor a slice, the pointer is pointing to a slice, // e.g. https://github.com/kubernetes/kubernetes/blob/bc22e206c79282487ea0bf5696d5ccec7e839a76/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go#L2782-L2822 // If the underlying element is either an array or a slice, return its element type. case reflect.Pointer: t = t.Elem() if t.Kind() == reflect.Array || t.Kind() == reflect.Slice { t = t.Elem() } elemType = t default: return nil, PatchMeta{}, fmt.Errorf("expected slice or array type, but got: %s", s.T.Kind().String()) } return PatchMetaFromStruct{T: elemType}, patchMeta, nil } func (s PatchMetaFromStruct) Name() string { return s.T.Kind().String() } func getTagStructType(dataStruct interface{}) (reflect.Type, error) { if dataStruct == nil { return nil, mergepatch.ErrBadArgKind(struct{}{}, nil) } t := reflect.TypeOf(dataStruct) // Get the underlying type for pointers if t.Kind() == reflect.Pointer { t = t.Elem() } if t.Kind() != reflect.Struct { return nil, mergepatch.ErrBadArgKind(struct{}{}, dataStruct) } return t, nil } func GetTagStructTypeOrDie(dataStruct interface{}) reflect.Type { t, err := getTagStructType(dataStruct) if err != nil { panic(err) } return t } type PatchMetaFromOpenAPIV3 struct { // SchemaList is required to resolve OpenAPI V3 references SchemaList map[string]*spec.Schema Schema *spec.Schema } func (s PatchMetaFromOpenAPIV3) traverse(key string) (PatchMetaFromOpenAPIV3, error) { if s.Schema == nil { return PatchMetaFromOpenAPIV3{}, nil } if len(s.Schema.Properties) == 0 { return PatchMetaFromOpenAPIV3{}, fmt.Errorf("unable to find api field \"%s\"", key) } subschema, ok := s.Schema.Properties[key] if !ok { return PatchMetaFromOpenAPIV3{}, fmt.Errorf("unable to find api field \"%s\"", key) } return PatchMetaFromOpenAPIV3{SchemaList: s.SchemaList, Schema: &subschema}, nil } func resolve(l *PatchMetaFromOpenAPIV3) error { if len(l.Schema.AllOf) > 0 { l.Schema = &l.Schema.AllOf[0] } if refString := l.Schema.Ref.String(); refString != "" { str := strings.TrimPrefix(refString, "#/components/schemas/") sch, ok := l.SchemaList[str] if ok { l.Schema = sch } else { return fmt.Errorf("unable to resolve %s in OpenAPI V3", refString) } } return nil } func (s PatchMetaFromOpenAPIV3) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { l, err := s.traverse(key) if err != nil { return l, PatchMeta{}, err } p := PatchMeta{} f, ok := l.Schema.Extensions[patchMergeKey] if ok { p.SetPatchMergeKey(f.(string)) } g, ok := l.Schema.Extensions[patchStrategy] if ok { p.SetPatchStrategies(strings.Split(g.(string), ",")) } err = resolve(&l) return l, p, err } func (s PatchMetaFromOpenAPIV3) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { l, err := s.traverse(key) if err != nil { return l, PatchMeta{}, err } p := PatchMeta{} f, ok := l.Schema.Extensions[patchMergeKey] if ok { p.SetPatchMergeKey(f.(string)) } g, ok := l.Schema.Extensions[patchStrategy] if ok { p.SetPatchStrategies(strings.Split(g.(string), ",")) } if l.Schema.Items != nil { l.Schema = l.Schema.Items.Schema } err = resolve(&l) return l, p, err } func (s PatchMetaFromOpenAPIV3) Name() string { schema := s.Schema if len(schema.Type) > 0 { return strings.Join(schema.Type, "") } return "Struct" } type PatchMetaFromOpenAPI struct { Schema openapi.Schema } func NewPatchMetaFromOpenAPI(s openapi.Schema) PatchMetaFromOpenAPI { return PatchMetaFromOpenAPI{Schema: s} } var _ LookupPatchMeta = PatchMetaFromOpenAPI{} func (s PatchMetaFromOpenAPI) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { if s.Schema == nil { return nil, PatchMeta{}, nil } kindItem := NewKindItem(key, s.Schema.GetPath()) s.Schema.Accept(kindItem) err := kindItem.Error() if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromOpenAPI{Schema: kindItem.subschema}, kindItem.patchmeta, nil } func (s PatchMetaFromOpenAPI) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { if s.Schema == nil { return nil, PatchMeta{}, nil } sliceItem := NewSliceItem(key, s.Schema.GetPath()) s.Schema.Accept(sliceItem) err := sliceItem.Error() if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromOpenAPI{Schema: sliceItem.subschema}, sliceItem.patchmeta, nil } func (s PatchMetaFromOpenAPI) Name() string { schema := s.Schema return schema.GetName() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 strategicpatch import ( "fmt" "reflect" "sort" "strings" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/mergepatch" ) // An alternate implementation of JSON Merge Patch // (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate // certain fields with metadata that indicates whether the elements of JSON // lists should be merged or replaced. // // For more information, see the PATCH section of docs/devel/api-conventions.md. // // Some of the content of this package was borrowed with minor adaptations from // evanphx/json-patch and openshift/origin. const ( directiveMarker = "$patch" deleteDirective = "delete" replaceDirective = "replace" mergeDirective = "merge" retainKeysStrategy = "retainKeys" deleteFromPrimitiveListDirectivePrefix = "$deleteFromPrimitiveList" retainKeysDirective = "$" + retainKeysStrategy setElementOrderDirectivePrefix = "$setElementOrder" ) // JSONMap is a representations of JSON object encoded as map[string]interface{} // where the children can be either map[string]interface{}, []interface{} or // primitive type). // Operating on JSONMap representation is much faster as it doesn't require any // json marshaling and/or unmarshaling operations. type JSONMap map[string]interface{} type DiffOptions struct { // SetElementOrder determines whether we generate the $setElementOrder parallel list. SetElementOrder bool // IgnoreChangesAndAdditions indicates if we keep the changes and additions in the patch. IgnoreChangesAndAdditions bool // IgnoreDeletions indicates if we keep the deletions in the patch. IgnoreDeletions bool // We introduce a new value retainKeys for patchStrategy. // It indicates that all fields needing to be preserved must be // present in the `retainKeys` list. // And the fields that are present will be merged with live object. // All the missing fields will be cleared when patching. BuildRetainKeysDirective bool } type MergeOptions struct { // MergeParallelList indicates if we are merging the parallel list. // We don't merge parallel list when calling mergeMap() in CreateThreeWayMergePatch() // which is called client-side. // We merge parallel list iff when calling mergeMap() in StrategicMergeMapPatch() // which is called server-side MergeParallelList bool // IgnoreUnmatchedNulls indicates if we should process the unmatched nulls. IgnoreUnmatchedNulls bool } // The following code is adapted from github.com/openshift/origin/pkg/util/jsonmerge. // Instead of defining a Delta that holds an original, a patch and a set of preconditions, // the reconcile method accepts a set of preconditions as an argument. // CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original // document and a modified document, which are passed to the method as json encoded content. It will // return a patch that yields the modified document when applied to the original document, or an error // if either of the two documents is invalid. func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema, fns...) } func CreateTwoWayMergePatchUsingLookupPatchMeta( original, modified []byte, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) ([]byte, error) { originalMap := map[string]interface{}{} if len(original) > 0 { if err := json.Unmarshal(original, &originalMap); err != nil { return nil, mergepatch.ErrBadJSONDoc } } modifiedMap := map[string]interface{}{} if len(modified) > 0 { if err := json.Unmarshal(modified, &modifiedMap); err != nil { return nil, mergepatch.ErrBadJSONDoc } } patchMap, err := CreateTwoWayMergeMapPatchUsingLookupPatchMeta(originalMap, modifiedMap, schema, fns...) if err != nil { return nil, err } return json.Marshal(patchMap) } // CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects, // encoded JSONMap. // The serialized version of the map can then be passed to StrategicMergeMapPatch. func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified, schema, fns...) } func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error) { diffOptions := DiffOptions{ SetElementOrder: true, } patchMap, err := diffMaps(original, modified, schema, diffOptions) if err != nil { return nil, err } // Apply the preconditions to the patch, and return an error if any of them fail. for _, fn := range fns { if !fn(patchMap) { return nil, mergepatch.NewErrPreconditionFailed(patchMap) } } return patchMap, nil } // Returns a (recursive) strategic merge patch that yields modified when applied to original. // Including: // - Adding fields to the patch present in modified, missing from original // - Setting fields to the patch present in modified and original with different values // - Delete fields present in original, missing from modified through // - IFF map field - set to nil in patch // - IFF list of maps && merge strategy - use deleteDirective for the elements // - IFF list of primitives && merge strategy - use parallel deletion list // - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified // - Build $retainKeys directive for fields with retainKeys patch strategy func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) { patch := map[string]interface{}{} // This will be used to build the $retainKeys directive sent in the patch retainKeysList := make([]interface{}, 0, len(modified)) // Compare each value in the modified map against the value in the original map for key, modifiedValue := range modified { // Get the underlying type for pointers if diffOptions.BuildRetainKeysDirective && modifiedValue != nil { retainKeysList = append(retainKeysList, key) } originalValue, ok := original[key] if !ok { // Key was added, so add to patch if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } continue } // The patch may have a patch directive // TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it? foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch) if err != nil { return nil, err } if foundDirectiveMarker { continue } if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) { // Types have changed, so add to patch if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } continue } // Types are the same, so compare values switch originalValueTyped := originalValue.(type) { case map[string]interface{}: modifiedValueTyped := modifiedValue.(map[string]interface{}) err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions) case []interface{}: modifiedValueTyped := modifiedValue.([]interface{}) err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions) default: replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions) } if err != nil { return nil, err } } updatePatchIfMissing(original, modified, patch, diffOptions) // Insert the retainKeysList iff there are values present in the retainKeysList and // either of the following is true: // - the patch is not empty // - there are additional field in original that need to be cleared if len(retainKeysList) > 0 && (len(patch) > 0 || hasAdditionalNewField(original, modified)) { patch[retainKeysDirective] = sortScalars(retainKeysList) } return patch, nil } // handleDirectiveMarker handles how to diff directive marker between 2 objects func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) { if key == directiveMarker { originalString, ok := originalValue.(string) if !ok { return false, fmt.Errorf("invalid value for special key: %s", directiveMarker) } modifiedString, ok := modifiedValue.(string) if !ok { return false, fmt.Errorf("invalid value for special key: %s", directiveMarker) } if modifiedString != originalString { patch[directiveMarker] = modifiedValue } return true, nil } return false, nil } // handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`, // puts the diff in the `patch` associated with `key` // key is the key associated with originalValue and modifiedValue. // originalValue, modifiedValue are the old and new value respectively.They are both maps // patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue // diffOptions contains multiple options to control how we do the diff. func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) error { subschema, patchMeta, err := schema.LookupPatchMetadataForStruct(key) if err != nil { // We couldn't look up metadata for the field // If the values are identical, this doesn't matter, no patch is needed if reflect.DeepEqual(originalValue, modifiedValue) { return nil } // Otherwise, return the error return err } retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies()) if err != nil { return err } diffOptions.BuildRetainKeysDirective = retainKeys switch patchStrategy { // The patch strategic from metadata tells us to replace the entire object instead of diffing it case replaceDirective: if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } default: patchValue, err := diffMaps(originalValue, modifiedValue, subschema, diffOptions) if err != nil { return err } // Maps were not identical, use provided patch value if len(patchValue) > 0 { patch[key] = patchValue } } return nil } // handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`, // puts the diff in the `patch` associated with `key` // key is the key associated with originalValue and modifiedValue. // originalValue, modifiedValue are the old and new value respectively.They are both slices // patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue // diffOptions contains multiple options to control how we do the diff. func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) error { subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(key) if err != nil { // We couldn't look up metadata for the field // If the values are identical, this doesn't matter, no patch is needed if reflect.DeepEqual(originalValue, modifiedValue) { return nil } // Otherwise, return the error return err } retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies()) if err != nil { return err } switch patchStrategy { // Merge the 2 slices using mergePatchKey case mergeDirective: diffOptions.BuildRetainKeysDirective = retainKeys addList, deletionList, setOrderList, err := diffLists(originalValue, modifiedValue, subschema, patchMeta.GetPatchMergeKey(), diffOptions) if err != nil { return err } if len(addList) > 0 { patch[key] = addList } // generate a parallel list for deletion if len(deletionList) > 0 { parallelDeletionListKey := fmt.Sprintf("%s/%s", deleteFromPrimitiveListDirectivePrefix, key) patch[parallelDeletionListKey] = deletionList } if len(setOrderList) > 0 { parallelSetOrderListKey := fmt.Sprintf("%s/%s", setElementOrderDirectivePrefix, key) patch[parallelSetOrderListKey] = setOrderList } default: replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions) } return nil } // replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal // if diffOptions.IgnoreChangesAndAdditions is false. // original is the old value, maybe either the live cluster object or the last applied configuration // modified is the new value, is always the users new config func replacePatchFieldIfNotEqual(key string, original, modified interface{}, patch map[string]interface{}, diffOptions DiffOptions) { if diffOptions.IgnoreChangesAndAdditions { // Ignoring changes - do nothing return } if reflect.DeepEqual(original, modified) { // Contents are identical - do nothing return } // Create a patch to replace the old value with the new one patch[key] = modified } // updatePatchIfMissing iterates over `original` when ignoreDeletions is false. // Clear the field whose key is not present in `modified`. // original is the old value, maybe either the live cluster object or the last applied configuration // modified is the new value, is always the users new config func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) { if diffOptions.IgnoreDeletions { // Ignoring deletion - do nothing return } // Add nils for deleted values for key := range original { if _, found := modified[key]; !found { patch[key] = nil } } } // validateMergeKeyInLists checks if each map in the list has the mentryerge key. func validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error { for _, list := range lists { for _, item := range list { m, ok := item.(map[string]interface{}) if !ok { return mergepatch.ErrBadArgType(m, item) } if _, ok = m[mergeKey]; !ok { return mergepatch.ErrNoMergeKey(m, mergeKey) } } } return nil } // normalizeElementOrder sort `patch` list by `patchOrder` and sort `serverOnly` list by `serverOrder`. // Then it merges the 2 sorted lists. // It guarantee the relative order in the patch list and in the serverOnly list is kept. // `patch` is a list of items in the patch, and `serverOnly` is a list of items in the live object. // `patchOrder` is the order we want `patch` list to have and // `serverOrder` is the order we want `serverOnly` list to have. // kind is the kind of each item in the lists `patch` and `serverOnly`. func normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) { patch, err := normalizeSliceOrder(patch, patchOrder, mergeKey, kind) if err != nil { return nil, err } serverOnly, err = normalizeSliceOrder(serverOnly, serverOrder, mergeKey, kind) if err != nil { return nil, err } all := mergeSortedSlice(serverOnly, patch, serverOrder, mergeKey, kind) return all, nil } // mergeSortedSlice merges the 2 sorted lists by serverOrder with best effort. // It will insert each item in `left` list to `right` list. In most cases, the 2 lists will be interleaved. // The relative order of left and right are guaranteed to be kept. // They have higher precedence than the order in the live list. // The place for a item in `left` is found by: // scan from the place of last insertion in `right` to the end of `right`, // the place is before the first item that is greater than the item we want to insert. // example usage: using server-only items as left and patch items as right. We insert server-only items // to patch list. We use the order of live object as record for comparison. func mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{} { // Returns if l is less than r, and if both have been found. // If l and r both present and l is in front of r, l is less than r. less := func(l, r interface{}) (bool, bool) { li := index(serverOrder, l, mergeKey, kind) ri := index(serverOrder, r, mergeKey, kind) if li >= 0 && ri >= 0 { return li < ri, true } else { return false, false } } // left and right should be non-overlapping. size := len(left) + len(right) i, j := 0, 0 s := make([]interface{}, size, size) for k := 0; k < size; k++ { if i >= len(left) && j < len(right) { // have items left in `right` list s[k] = right[j] j++ } else if j >= len(right) && i < len(left) { // have items left in `left` list s[k] = left[i] i++ } else { // compare them if i and j are both in bound less, foundBoth := less(left[i], right[j]) if foundBoth && less { s[k] = left[i] i++ } else { s[k] = right[j] j++ } } } return s } // index returns the index of the item in the given items, or -1 if it doesn't exist // l must NOT be a slice of slices, this should be checked before calling. func index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int { var getValFn func(interface{}) interface{} // Get the correct `getValFn` based on item `kind`. // It should return the value of merge key for maps and // return the item for other kinds. switch kind { case reflect.Map: getValFn = func(item interface{}) interface{} { typedItem, ok := item.(map[string]interface{}) if !ok { return nil } val := typedItem[mergeKey] return val } default: getValFn = func(item interface{}) interface{} { return item } } for i, v := range l { if getValFn(valToLookUp) == getValFn(v) { return i } } return -1 } // extractToDeleteItems takes a list and // returns 2 lists: one contains items that should be kept and the other contains items to be deleted. func extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error) { var nonDelete, toDelete []interface{} for _, v := range l { m, ok := v.(map[string]interface{}) if !ok { return nil, nil, mergepatch.ErrBadArgType(m, v) } directive, foundDirective := m[directiveMarker] if foundDirective && directive == deleteDirective { toDelete = append(toDelete, v) } else { nonDelete = append(nonDelete, v) } } return nonDelete, toDelete, nil } // normalizeSliceOrder sort `toSort` list by `order` func normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) { var toDelete []interface{} if kind == reflect.Map { // make sure each item in toSort, order has merge key err := validateMergeKeyInLists(mergeKey, toSort, order) if err != nil { return nil, err } toSort, toDelete, err = extractToDeleteItems(toSort) if err != nil { return nil, err } } sort.SliceStable(toSort, func(i, j int) bool { if ii := index(order, toSort[i], mergeKey, kind); ii >= 0 { if ij := index(order, toSort[j], mergeKey, kind); ij >= 0 { return ii < ij } } return true }) toSort = append(toSort, toDelete...) return toSort, nil } // Returns a (recursive) strategic merge patch, a parallel deletion list if necessary and // another list to set the order of the list // Only list of primitives with merge strategy will generate a parallel deletion list. // These two lists should yield modified when applied to original, for lists with merge semantics. func diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error) { if len(original) == 0 { // Both slices are empty - do nothing if len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions { return nil, nil, nil, nil } // Old slice was empty - add all elements from the new slice return modified, nil, nil, nil } elementType, err := sliceElementType(original, modified) if err != nil { return nil, nil, nil, err } var patchList, deleteList, setOrderList []interface{} kind := elementType.Kind() switch kind { case reflect.Map: patchList, deleteList, err = diffListsOfMaps(original, modified, schema, mergeKey, diffOptions) if err != nil { return nil, nil, nil, err } patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind) if err != nil { return nil, nil, nil, err } orderSame, err := isOrderSame(original, modified, mergeKey) if err != nil { return nil, nil, nil, err } // append the deletions to the end of the patch list. patchList = append(patchList, deleteList...) deleteList = nil // generate the setElementOrder list when there are content changes or order changes if diffOptions.SetElementOrder && ((!diffOptions.IgnoreChangesAndAdditions && (len(patchList) > 0 || !orderSame)) || (!diffOptions.IgnoreDeletions && len(patchList) > 0)) { // Generate a list of maps that each item contains only the merge key. setOrderList = make([]interface{}, len(modified)) for i, v := range modified { typedV := v.(map[string]interface{}) setOrderList[i] = map[string]interface{}{ mergeKey: typedV[mergeKey], } } } case reflect.Slice: // Lists of Lists are not permitted by the api return nil, nil, nil, mergepatch.ErrNoListOfLists default: patchList, deleteList, err = diffListsOfScalars(original, modified, diffOptions) if err != nil { return nil, nil, nil, err } patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind) // generate the setElementOrder list when there are content changes or order changes if diffOptions.SetElementOrder && ((!diffOptions.IgnoreDeletions && len(deleteList) > 0) || (!diffOptions.IgnoreChangesAndAdditions && !reflect.DeepEqual(original, modified))) { setOrderList = modified } } return patchList, deleteList, setOrderList, err } // isOrderSame checks if the order in a list has changed func isOrderSame(original, modified []interface{}, mergeKey string) (bool, error) { if len(original) != len(modified) { return false, nil } for i, modifiedItem := range modified { equal, err := mergeKeyValueEqual(original[i], modifiedItem, mergeKey) if err != nil || !equal { return equal, err } } return true, nil } // diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList. // Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate. // Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate. // original may be changed, but modified is guaranteed to not be changed func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) { modifiedCopy := make([]interface{}, len(modified)) copy(modifiedCopy, modified) // Sort the scalars for easier calculating the diff originalScalars := sortScalars(original) modifiedScalars := sortScalars(modifiedCopy) originalIndex, modifiedIndex := 0, 0 addList := []interface{}{} deletionList := []interface{}{} for { originalInBounds := originalIndex < len(originalScalars) modifiedInBounds := modifiedIndex < len(modifiedScalars) if !originalInBounds && !modifiedInBounds { break } // we need to compare the string representation of the scalar, // because the scalar is an interface which doesn't support either < or > // And that's how func sortScalars compare scalars. var originalString, modifiedString string var originalValue, modifiedValue interface{} if originalInBounds { originalValue = originalScalars[originalIndex] originalString = fmt.Sprintf("%v", originalValue) } if modifiedInBounds { modifiedValue = modifiedScalars[modifiedIndex] modifiedString = fmt.Sprintf("%v", modifiedValue) } originalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString) switch { case originalV == nil && modifiedV == nil: originalIndex++ modifiedIndex++ case originalV != nil && modifiedV == nil: if !diffOptions.IgnoreDeletions { deletionList = append(deletionList, originalValue) } originalIndex++ case originalV == nil && modifiedV != nil: if !diffOptions.IgnoreChangesAndAdditions { addList = append(addList, modifiedValue) } modifiedIndex++ default: return nil, nil, fmt.Errorf("Unexpected returned value from compareListValuesAtIndex: %v and %v", originalV, modifiedV) } } return addList, deduplicateScalars(deletionList), nil } // If first return value is non-nil, list1 contains an element not present in list2 // If second return value is non-nil, list2 contains an element not present in list1 func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) { bothInBounds := list1Inbounds && list2Inbounds switch { // scalars are identical case bothInBounds && list1Value == list2Value: return nil, nil // only list2 is in bound case !list1Inbounds: fallthrough // list2 has additional scalar case bothInBounds && list1Value > list2Value: return nil, list2Value // only original is in bound case !list2Inbounds: fallthrough // original has additional scalar case bothInBounds && list1Value < list2Value: return list1Value, nil default: return nil, nil } } // diffListsOfMaps takes a pair of lists and // returns a (recursive) strategic merge patch list contains additions and changes and // a deletion list contains deletions func diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) { patch := make([]interface{}, 0, len(modified)) deletionList := make([]interface{}, 0, len(original)) originalSorted, err := sortMergeListsByNameArray(original, schema, mergeKey, false) if err != nil { return nil, nil, err } modifiedSorted, err := sortMergeListsByNameArray(modified, schema, mergeKey, false) if err != nil { return nil, nil, err } originalIndex, modifiedIndex := 0, 0 for { originalInBounds := originalIndex < len(originalSorted) modifiedInBounds := modifiedIndex < len(modifiedSorted) bothInBounds := originalInBounds && modifiedInBounds if !originalInBounds && !modifiedInBounds { break } var originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string var originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{} var originalElement, modifiedElement map[string]interface{} if originalInBounds { originalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted) if err != nil { return nil, nil, err } originalElementMergeKeyValueString = fmt.Sprintf("%v", originalElementMergeKeyValue) } if modifiedInBounds { modifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted) if err != nil { return nil, nil, err } modifiedElementMergeKeyValueString = fmt.Sprintf("%v", modifiedElementMergeKeyValue) } switch { case bothInBounds && ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): // Merge key values are equal, so recurse patchValue, err := diffMaps(originalElement, modifiedElement, schema, diffOptions) if err != nil { return nil, nil, err } if len(patchValue) > 0 { patchValue[mergeKey] = modifiedElementMergeKeyValue patch = append(patch, patchValue) } originalIndex++ modifiedIndex++ // only modified is in bound case !originalInBounds: fallthrough // modified has additional map case bothInBounds && ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): if !diffOptions.IgnoreChangesAndAdditions { patch = append(patch, modifiedElement) } modifiedIndex++ // only original is in bound case !modifiedInBounds: fallthrough // original has additional map case bothInBounds && ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): if !diffOptions.IgnoreDeletions { // Item was deleted, so add delete directive deletionList = append(deletionList, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue)) } originalIndex++ } } return patch, deletionList, nil } // getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map. func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) { m, ok := listOfMaps[index].(map[string]interface{}) if !ok { return nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index]) } val, ok := m[mergeKey] if !ok { return nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey) } return m, val, nil } // StrategicMergePatch applies a strategic merge patch. The patch and the original document // must be json encoded content. A patch can be created from an original and a modified document // by calling CreateStrategicMergePatch. func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return StrategicMergePatchUsingLookupPatchMeta(original, patch, schema) } func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error) { originalMap, err := handleUnmarshal(original) if err != nil { return nil, err } patchMap, err := handleUnmarshal(patch) if err != nil { return nil, err } result, err := StrategicMergeMapPatchUsingLookupPatchMeta(originalMap, patchMap, schema) if err != nil { return nil, err } return json.Marshal(result) } func handleUnmarshal(j []byte) (map[string]interface{}, error) { if j == nil { j = []byte("{}") } m := map[string]interface{}{} err := json.Unmarshal(j, &m) if err != nil { return nil, mergepatch.ErrBadJSONDoc } return m, nil } // StrategicMergeMapPatch applies a strategic merge patch. The original and patch documents // must be JSONMap. A patch can be created from an original and modified document by // calling CreateTwoWayMergeMapPatch. // Warning: the original and patch JSONMap objects are mutated by this function and should not be reused. func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } // We need the go struct tags `patchMergeKey` and `patchStrategy` for fields that support a strategic merge patch. // For native resources, we can easily figure out these tags since we know the fields. // Because custom resources are decoded as Unstructured and because we're missing the metadata about how to handle // each field in a strategic merge patch, we can't find the go struct tags. Hence, we can't easily do a strategic merge // for custom resources. So we should fail fast and return an error. if _, ok := dataStruct.(*unstructured.Unstructured); ok { return nil, mergepatch.ErrUnsupportedStrategicMergePatchFormat } return StrategicMergeMapPatchUsingLookupPatchMeta(original, patch, schema) } func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error) { mergeOptions := MergeOptions{ MergeParallelList: true, IgnoreUnmatchedNulls: true, } return mergeMap(original, patch, schema, mergeOptions) } // MergeStrategicMergeMapPatchUsingLookupPatchMeta merges strategic merge // patches retaining `null` fields and parallel lists. If 2 patches change the // same fields and the latter one will override the former one. If you don't // want that happen, you need to run func MergingMapsHaveConflicts before
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go
/* 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 errors import ( "errors" "fmt" "k8s.io/apimachinery/pkg/util/sets" ) // MessageCountMap contains occurrence for each error message. type MessageCountMap map[string]int // Aggregate represents an object that contains multiple errors, but does not // necessarily have singular semantic meaning. // The aggregate can be used with `errors.Is()` to check for the occurrence of // a specific error type. // Errors.As() is not supported, because the caller presumably cares about a // specific error of potentially multiple that match the given type. type Aggregate interface { error Errors() []error Is(error) bool } // NewAggregate converts a slice of errors into an Aggregate interface, which // is itself an implementation of the error interface. If the slice is empty, // this returns nil. // It will check if any of the element of input error list is nil, to avoid // nil pointer panic when call Error(). func NewAggregate(errlist []error) Aggregate { if len(errlist) == 0 { return nil } // In case of input error list contains nil var errs []error for _, e := range errlist { if e != nil { errs = append(errs, e) } } if len(errs) == 0 { return nil } return aggregate(errs) } // This helper implements the error and Errors interfaces. Keeping it private // prevents people from making an aggregate of 0 errors, which is not // an error, but does satisfy the error interface. type aggregate []error // Error is part of the error interface. func (agg aggregate) Error() string { if len(agg) == 0 { // This should never happen, really. return "" } if len(agg) == 1 { return agg[0].Error() } seenerrs := sets.NewString() result := "" agg.visit(func(err error) bool { msg := err.Error() if seenerrs.Has(msg) { return false } seenerrs.Insert(msg) if len(seenerrs) > 1 { result += ", " } result += msg return false }) if len(seenerrs) == 1 { return result } return "[" + result + "]" } func (agg aggregate) Is(target error) bool { return agg.visit(func(err error) bool { return errors.Is(err, target) }) } func (agg aggregate) visit(f func(err error) bool) bool { for _, err := range agg { switch err := err.(type) { case aggregate: if match := err.visit(f); match { return match } case Aggregate: for _, nestedErr := range err.Errors() { if match := f(nestedErr); match { return match } } default: if match := f(err); match { return match } } } return false } // Errors is part of the Aggregate interface. func (agg aggregate) Errors() []error { return []error(agg) } // Matcher is used to match errors. Returns true if the error matches. type Matcher func(error) bool // FilterOut removes all errors that match any of the matchers from the input // error. If the input is a singular error, only that error is tested. If the // input implements the Aggregate interface, the list of errors will be // processed recursively. // // This can be used, for example, to remove known-OK errors (such as io.EOF or // os.PathNotFound) from a list of errors. func FilterOut(err error, fns ...Matcher) error { if err == nil { return nil } if agg, ok := err.(Aggregate); ok { return NewAggregate(filterErrors(agg.Errors(), fns...)) } if !matchesError(err, fns...) { return err } return nil } // matchesError returns true if any Matcher returns true func matchesError(err error, fns ...Matcher) bool { for _, fn := range fns { if fn(err) { return true } } return false } // filterErrors returns any errors (or nested errors, if the list contains // nested Errors) for which all fns return false. If no errors // remain a nil list is returned. The resulting slice will have all // nested slices flattened as a side effect. func filterErrors(list []error, fns ...Matcher) []error { result := []error{} for _, err := range list { r := FilterOut(err, fns...) if r != nil { result = append(result, r) } } return result } // Flatten takes an Aggregate, which may hold other Aggregates in arbitrary // nesting, and flattens them all into a single Aggregate, recursively. func Flatten(agg Aggregate) Aggregate { result := []error{} if agg == nil { return nil } for _, err := range agg.Errors() { if a, ok := err.(Aggregate); ok { r := Flatten(a) if r != nil { result = append(result, r.Errors()...) } } else { if err != nil { result = append(result, err) } } } return NewAggregate(result) } // CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate { if m == nil { return nil } result := make([]error, 0, len(m)) for errStr, count := range m { var countStr string if count > 1 { countStr = fmt.Sprintf(" (repeated %v times)", count) } result = append(result, fmt.Errorf("%v%v", errStr, countStr)) } return NewAggregate(result) } // Reduce will return err or nil, if err is an Aggregate and only has one item, // the first item in the aggregate. func Reduce(err error) error { if agg, ok := err.(Aggregate); ok && err != nil { switch len(agg.Errors()) { case 1: return agg.Errors()[0] case 0: return nil } } return err } // AggregateGoroutines runs the provided functions in parallel, stuffing all // non-nil errors into the returned Aggregate. // Returns nil if all the functions complete successfully. func AggregateGoroutines(funcs ...func() error) Aggregate { errChan := make(chan error, len(funcs)) for _, f := range funcs { go func(f func() error) { errChan <- f() }(f) } errs := make([]error, 0) for i := 0; i < cap(errChan); i++ { if err := <-errChan; err != nil { errs = append(errs, err) } } return NewAggregate(errs) } // ErrPreconditionViolated is returned when the precondition is violated var ErrPreconditionViolated = errors.New("precondition is violated")
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go
/* 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 errors implements various utility functions and types around errors. package errors // import "k8s.io/apimachinery/pkg/util/errors"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/json/json.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/json/json.go
/* 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 json import ( "encoding/json" "fmt" "io" kjson "sigs.k8s.io/json" ) // NewEncoder delegates to json.NewEncoder // It is only here so this package can be a drop-in for common encoding/json uses func NewEncoder(w io.Writer) *json.Encoder { return json.NewEncoder(w) } // Marshal delegates to json.Marshal // It is only here so this package can be a drop-in for common encoding/json uses func Marshal(v interface{}) ([]byte, error) { return json.Marshal(v) } // limit recursive depth to prevent stack overflow errors const maxDepth = 10000 // Unmarshal unmarshals the given data. // Object keys are case-sensitive. // Numbers decoded into interface{} fields are converted to int64 or float64. func Unmarshal(data []byte, v interface{}) error { return kjson.UnmarshalCaseSensitivePreserveInts(data, v) } // ConvertInterfaceNumbers converts any json.Number values to int64 or float64. // Values which are map[string]interface{} or []interface{} are recursively visited func ConvertInterfaceNumbers(v *interface{}, depth int) error { var err error switch v2 := (*v).(type) { case json.Number: *v, err = convertNumber(v2) case map[string]interface{}: err = ConvertMapNumbers(v2, depth+1) case []interface{}: err = ConvertSliceNumbers(v2, depth+1) } return err } // ConvertMapNumbers traverses the map, converting any json.Number values to int64 or float64. // values which are map[string]interface{} or []interface{} are recursively visited func ConvertMapNumbers(m map[string]interface{}, depth int) error { if depth > maxDepth { return fmt.Errorf("exceeded max depth of %d", maxDepth) } var err error for k, v := range m { switch v := v.(type) { case json.Number: m[k], err = convertNumber(v) case map[string]interface{}: err = ConvertMapNumbers(v, depth+1) case []interface{}: err = ConvertSliceNumbers(v, depth+1) } if err != nil { return err } } return nil } // ConvertSliceNumbers traverses the slice, converting any json.Number values to int64 or float64. // values which are map[string]interface{} or []interface{} are recursively visited func ConvertSliceNumbers(s []interface{}, depth int) error { if depth > maxDepth { return fmt.Errorf("exceeded max depth of %d", maxDepth) } var err error for i, v := range s { switch v := v.(type) { case json.Number: s[i], err = convertNumber(v) case map[string]interface{}: err = ConvertMapNumbers(v, depth+1) case []interface{}: err = ConvertSliceNumbers(v, depth+1) } if err != nil { return err } } return nil } // convertNumber converts a json.Number to an int64 or float64, or returns an error func convertNumber(n json.Number) (interface{}, error) { // Attempt to convert to an int64 first if i, err := n.Int64(); err == nil { return i, nil } // Return a float64 (default json.Decode() behavior) // An overflow will return an error return n.Float64() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "context" "fmt" "net/http" "runtime" "sync" "time" "k8s.io/klog/v2" ) var ( // ReallyCrash controls the behavior of HandleCrash and defaults to // true. It's exposed so components can optionally set to false // to restore prior behavior. This flag is mostly used for tests to validate // crash conditions. ReallyCrash = true ) // PanicHandlers is a list of functions which will be invoked when a panic happens. var PanicHandlers = []func(context.Context, interface{}){logPanic} // HandleCrash simply catches a crash and logs an error. Meant to be called via // defer. Additional context-specific handlers can be provided, and will be // called in case of panic. HandleCrash actually crashes, after calling the // handlers and logging the panic message. // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // // Contextual logging: HandleCrashWithContext should be used instead of HandleCrash in code which supports contextual logging. 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) } } handleCrash(context.Background(), r, additionalHandlersWithContext...) } } // HandleCrashWithContext simply catches a crash and logs an error. Meant to be called via // defer. Additional context-specific handlers can be provided, and will be // called in case of panic. HandleCrash actually crashes, after calling the // handlers and logging the panic message. // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // // The context is used to determine how to log. func HandleCrashWithContext(ctx context.Context, additionalHandlers ...func(context.Context, interface{})) { if r := recover(); r != nil { handleCrash(ctx, r, additionalHandlers...) } } // handleCrash is the common implementation of HandleCrash and HandleCrash. // Having those call a common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleCrash(ctx context.Context, r any, additionalHandlers ...func(context.Context, interface{})) { for _, fn := range PanicHandlers { fn(ctx, r) } for _, fn := range additionalHandlers { fn(ctx, r) } if ReallyCrash { // Actually proceed to panic. panic(r) } } // logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler). func logPanic(ctx context.Context, r interface{}) { if r == http.ErrAbortHandler { // honor the http.ErrAbortHandler sentinel panic value: // ErrAbortHandler is a sentinel panic value to abort a handler. // While any panic from ServeHTTP aborts the response to the client, // panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log. return } // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs const size = 64 << 10 stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] // We don't really know how many call frames to skip because the Go // panic handler is between us and the code where the panic occurred. // If it's one function (as in Go 1.21), then skipping four levels // gets us to the function which called the `defer HandleCrashWithontext(...)`. logger := klog.FromContext(ctx).WithCallDepth(4) // For backwards compatibility, conversion to string // is handled here instead of defering to the logging // backend. if _, ok := r.(string); ok { logger.Error(nil, "Observed a panic", "panic", r, "stacktrace", string(stacktrace)) } else { logger.Error(nil, "Observed a panic", "panic", fmt.Sprintf("%v", r), "panicGoValue", fmt.Sprintf("%#v", r), "stacktrace", string(stacktrace)) } } // ErrorHandlers is a list of functions which will be invoked when a nonreturnable // error occurs. // TODO(lavalamp): for testability, this and the below HandleError function // should be packaged up into a testable and reusable object. var ErrorHandlers = []ErrorHandler{ logError, func(_ context.Context, _ error, _ string, _ ...interface{}) { (&rudimentaryErrorBackoff{ lastErrorTime: time.Now(), // 1ms was the number folks were able to stomach as a global rate limit. // If you need to log errors more than 1000 times a second you // should probably consider fixing your code instead. :) minPeriod: time.Millisecond, }).OnError() }, } type ErrorHandler func(ctx context.Context, err error, msg string, keysAndValues ...interface{}) // 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 // errors may be sent to a remote server for analysis. // // Contextual logging: HandleErrorWithContext should be used instead of HandleError in code which supports contextual logging. func HandleError(err error) { // this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead if err == nil { return } handleError(context.Background(), err, "Unhandled Error") } // HandlerErrorWithContext 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 // errors may be sent to a remote server for analysis. The context is used to // determine how to log the error. // // If contextual logging is enabled, the default log output is equivalent to // // logr.FromContext(ctx).WithName("UnhandledError").Error(err, msg, keysAndValues...) // // Without contextual logging, it is equivalent to: // // klog.ErrorS(err, msg, keysAndValues...) // // In contrast to HandleError, passing nil for the error is still going to // trigger a log entry. Don't construct a new error or wrap an error // with fmt.Errorf. Instead, add additional information via the mssage // and key/value pairs. // // This variant should be used instead of HandleError because it supports // structured, contextual logging. func HandleErrorWithContext(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { handleError(ctx, err, msg, keysAndValues...) } // handleError is the common implementation of HandleError and HandleErrorWithContext. // Using this common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleError(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { for _, fn := range ErrorHandlers { fn(ctx, err, msg, keysAndValues...) } } // logError prints an error with the call stack of the location it was reported. // It expects to be called as <caller> -> HandleError[WithContext] -> handleError -> logError. func logError(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { logger := klog.FromContext(ctx).WithCallDepth(3) logger = klog.LoggerWithName(logger, "UnhandledError") logger.Error(err, msg, keysAndValues...) //nolint:logcheck // logcheck complains about unknown key/value pairs. } type rudimentaryErrorBackoff struct { minPeriod time.Duration // immutable // TODO(lavalamp): use the clock for testability. Need to move that // package for that to be accessible here. lastErrorTimeLock sync.Mutex lastErrorTime time.Time } // OnError will block if it is called more often than the embedded period time. // This will prevent overly tight hot error loops. func (r *rudimentaryErrorBackoff) OnError() { now := time.Now() // start the timer before acquiring the lock r.lastErrorTimeLock.Lock() d := now.Sub(r.lastErrorTime) r.lastErrorTime = time.Now() r.lastErrorTimeLock.Unlock() // Do not sleep with the lock held because that causes all callers of HandleError to block. // We only want the current goroutine to block. // A negative or zero duration causes time.Sleep to return immediately. // If the time moves backwards for any reason, do nothing. time.Sleep(r.minPeriod - d) } // GetCaller returns the caller of the function that calls it. func GetCaller() string { var pc [1]uintptr runtime.Callers(3, pc[:]) f := runtime.FuncForPC(pc[0]) if f == nil { return "Unable to find caller" } return f.Name() } // RecoverFromPanic replaces the specified error with an error containing the // original error, and the call tree when a panic occurs. This enables error // handlers to handle errors and panics the same way. func RecoverFromPanic(err *error) { if r := recover(); r != nil { // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs const size = 64 << 10 stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] *err = fmt.Errorf( "recovered from panic %q. (err=%v) Call stack:\n%s", r, *err, stacktrace) } } // Must panics on non-nil errors. Useful to handling programmer level errors. func Must(err error) { if err != nil { panic(err) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/port_range.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/port_range.go
/* 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 net import ( "fmt" "strconv" "strings" ) // PortRange represents a range of TCP/UDP ports. To represent a single port, // set Size to 1. type PortRange struct { Base int Size int } // Contains tests whether a given port falls within the PortRange. func (pr *PortRange) Contains(p int) bool { return (p >= pr.Base) && ((p - pr.Base) < pr.Size) } // String converts the PortRange to a string representation, which can be // parsed by PortRange.Set or ParsePortRange. func (pr PortRange) String() string { if pr.Size == 0 { return "" } return fmt.Sprintf("%d-%d", pr.Base, pr.Base+pr.Size-1) } // Set parses a string of the form "value", "min-max", or "min+offset", inclusive at both ends, and // sets the PortRange from it. This is part of the flag.Value and pflag.Value // interfaces. func (pr *PortRange) Set(value string) error { const ( SinglePortNotation = 1 << iota HyphenNotation PlusNotation ) value = strings.TrimSpace(value) hyphenIndex := strings.Index(value, "-") plusIndex := strings.Index(value, "+") if value == "" { pr.Base = 0 pr.Size = 0 return nil } var err error var low, high int var notation int if plusIndex == -1 && hyphenIndex == -1 { notation |= SinglePortNotation } if hyphenIndex != -1 { notation |= HyphenNotation } if plusIndex != -1 { notation |= PlusNotation } switch notation { case SinglePortNotation: var port int port, err = strconv.Atoi(value) if err != nil { return err } low = port high = port case HyphenNotation: low, err = strconv.Atoi(value[:hyphenIndex]) if err != nil { return err } high, err = strconv.Atoi(value[hyphenIndex+1:]) if err != nil { return err } case PlusNotation: var offset int low, err = strconv.Atoi(value[:plusIndex]) if err != nil { return err } offset, err = strconv.Atoi(value[plusIndex+1:]) if err != nil { return err } high = low + offset default: return fmt.Errorf("unable to parse port range: %s", value) } if low > 65535 || high > 65535 { return fmt.Errorf("the port range cannot be greater than 65535: %s", value) } if high < low { return fmt.Errorf("end port cannot be less than start port: %s", value) } pr.Base = low pr.Size = 1 + high - low return nil } // Type returns a descriptive string about this type. This is part of the // pflag.Value interface. func (*PortRange) Type() string { return "portRange" } // ParsePortRange parses a string of the form "min-max", inclusive at both // ends, and initializes a new PortRange from it. func ParsePortRange(value string) (*PortRange, error) { pr := &PortRange{} err := pr.Set(value) if err != nil { return nil, err } return pr, nil } func ParsePortRangeOrDie(value string) *PortRange { pr, err := ParsePortRange(value) if err != nil { panic(fmt.Sprintf("couldn't parse port range %q: %v", value, err)) } return pr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/port_split.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/port_split.go
/* 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 net import ( "strings" "k8s.io/apimachinery/pkg/util/sets" ) var validSchemes = sets.NewString("http", "https", "") // SplitSchemeNamePort takes a string of the following forms: // - "<name>", returns "", "<name>","", true // - "<name>:<port>", returns "", "<name>","<port>",true // - "<scheme>:<name>:<port>", returns "<scheme>","<name>","<port>",true // // Name must be non-empty or valid will be returned false. // Scheme must be "http" or "https" if specified // Port is returned as a string, and it is not required to be numeric (could be // used for a named port, for example). func SplitSchemeNamePort(id string) (scheme, name, port string, valid bool) { parts := strings.Split(id, ":") switch len(parts) { case 1: name = parts[0] case 2: name = parts[0] port = parts[1] case 3: scheme = parts[0] name = parts[1] port = parts[2] default: return "", "", "", false } if len(name) > 0 && validSchemes.Has(scheme) { return scheme, name, port, true } else { return "", "", "", false } } // JoinSchemeNamePort returns a string that specifies the scheme, name, and port: // - "<name>" // - "<name>:<port>" // - "<scheme>:<name>:<port>" // // None of the parameters may contain a ':' character // Name is required // Scheme must be "", "http", or "https" func JoinSchemeNamePort(scheme, name, port string) string { if len(scheme) > 0 { // Must include three segments to specify scheme return scheme + ":" + name + ":" + port } if len(port) > 0 { // Must include two segments to specify port return name + ":" + port } // Return name alone return name }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/interface.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/interface.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 net import ( "bufio" "encoding/hex" "fmt" "io" "net" "os" "strings" "k8s.io/klog/v2" netutils "k8s.io/utils/net" ) type AddressFamily uint const ( familyIPv4 AddressFamily = 4 familyIPv6 AddressFamily = 6 ) type AddressFamilyPreference []AddressFamily var ( preferIPv4 = AddressFamilyPreference{familyIPv4, familyIPv6} preferIPv6 = AddressFamilyPreference{familyIPv6, familyIPv4} ) const ( // LoopbackInterfaceName is the default name of the loopback interface LoopbackInterfaceName = "lo" ) const ( ipv4RouteFile = "/proc/net/route" ipv6RouteFile = "/proc/net/ipv6_route" ) type Route struct { Interface string Destination net.IP Gateway net.IP Family AddressFamily } type RouteFile struct { name string parse func(input io.Reader) ([]Route, error) } // noRoutesError can be returned in case of no routes type noRoutesError struct { message string } func (e noRoutesError) Error() string { return e.message } // IsNoRoutesError checks if an error is of type noRoutesError func IsNoRoutesError(err error) bool { if err == nil { return false } switch err.(type) { case noRoutesError: return true default: return false } } var ( v4File = RouteFile{name: ipv4RouteFile, parse: getIPv4DefaultRoutes} v6File = RouteFile{name: ipv6RouteFile, parse: getIPv6DefaultRoutes} ) func (rf RouteFile) extract() ([]Route, error) { file, err := os.Open(rf.name) if err != nil { return nil, err } defer file.Close() return rf.parse(file) } // getIPv4DefaultRoutes obtains the IPv4 routes, and filters out non-default routes. func getIPv4DefaultRoutes(input io.Reader) ([]Route, error) { routes := []Route{} scanner := bufio.NewReader(input) for { line, err := scanner.ReadString('\n') if err == io.EOF { break } //ignore the headers in the route info if strings.HasPrefix(line, "Iface") { continue } fields := strings.Fields(line) // Interested in fields: // 0 - interface name // 1 - destination address // 2 - gateway dest, err := parseIP(fields[1], familyIPv4) if err != nil { return nil, err } gw, err := parseIP(fields[2], familyIPv4) if err != nil { return nil, err } if !dest.Equal(net.IPv4zero) { continue } routes = append(routes, Route{ Interface: fields[0], Destination: dest, Gateway: gw, Family: familyIPv4, }) } return routes, nil } func getIPv6DefaultRoutes(input io.Reader) ([]Route, error) { routes := []Route{} scanner := bufio.NewReader(input) for { line, err := scanner.ReadString('\n') if err == io.EOF { break } fields := strings.Fields(line) // Interested in fields: // 0 - destination address // 4 - gateway // 9 - interface name dest, err := parseIP(fields[0], familyIPv6) if err != nil { return nil, err } gw, err := parseIP(fields[4], familyIPv6) if err != nil { return nil, err } if !dest.Equal(net.IPv6zero) { continue } if gw.Equal(net.IPv6zero) { continue // loopback } routes = append(routes, Route{ Interface: fields[9], Destination: dest, Gateway: gw, Family: familyIPv6, }) } return routes, nil } // parseIP takes the hex IP address string from route file and converts it // to a net.IP address. For IPv4, the value must be converted to big endian. func parseIP(str string, family AddressFamily) (net.IP, error) { if str == "" { return nil, fmt.Errorf("input is nil") } bytes, err := hex.DecodeString(str) if err != nil { return nil, err } if family == familyIPv4 { if len(bytes) != net.IPv4len { return nil, fmt.Errorf("invalid IPv4 address in route") } return net.IP([]byte{bytes[3], bytes[2], bytes[1], bytes[0]}), nil } // Must be IPv6 if len(bytes) != net.IPv6len { return nil, fmt.Errorf("invalid IPv6 address in route") } return net.IP(bytes), nil } func isInterfaceUp(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) return true } return false } func isLoopbackOrPointToPoint(intf *net.Interface) bool { return intf.Flags&(net.FlagLoopback|net.FlagPointToPoint) != 0 } // 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) { if len(addrs) > 0 { for i := range addrs { klog.V(4).Infof("Checking addr %s.", addrs[i].String()) 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) return ip, nil } else { klog.V(4).Infof("Non-global unicast address found %v", ip) } } else { klog.V(4).Infof("%v is not an IPv%d address", ip, int(family)) } } } return nil, nil } // 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) { intf, err := nw.InterfaceByName(intfName) if err != nil { return nil, err } if isInterfaceUp(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) 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) return matchingIP, nil } } return nil, nil } // 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) { intfs, err := nw.Interfaces() if err != nil { return nil, err } for _, intf := range intfs { if !isInterfaceUp(&intf) { continue } if intf.Flags&(net.FlagLoopback) != 0 { addrs, err := nw.Addrs(&intf) 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) 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) return matchingIP, nil } } } return nil, nil } // memberOf tells if the IP is of the desired family. Used for checking interface addresses. func memberOf(ip net.IP, family AddressFamily) bool { if ip.To4() != nil { return family == familyIPv4 } else { return family == familyIPv6 } } // 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) { intfs, err := nw.Interfaces() if err != nil { return nil, err } if len(intfs) == 0 { 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)) for _, intf := range intfs { if !isInterfaceUp(&intf) { klog.V(4).Infof("Skipping: down interface %q", intf.Name) continue } if isLoopbackOrPointToPoint(&intf) { klog.V(4).Infof("Skipping: LB or P2P interface %q", intf.Name) continue } addrs, err := nw.Addrs(&intf) if err != nil { return nil, err } if len(addrs) == 0 { klog.V(4).Infof("Skipping: no addresses on interface %q", intf.Name) continue } for _, addr := range addrs { ip, _, err := netutils.ParseCIDRSloppy(addr.String()) if err != nil { 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) 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) continue } klog.V(4).Infof("Found global unicast address %q on interface %q.", ip, intf.Name) return ip, nil } } } return nil, fmt.Errorf("no acceptable interface with global unicast address found on host") } // ChooseHostInterface 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 ChooseHostInterface() (net.IP, error) { return chooseHostInterface(preferIPv4) } func chooseHostInterface(addressFamilies AddressFamilyPreference) (net.IP, error) { var nw networkInterfacer = networkInterface{} if _, err := os.Stat(ipv4RouteFile); os.IsNotExist(err) { return chooseIPFromHostInterfaces(nw, addressFamilies) } routes, err := getAllDefaultRoutes() if err != nil { return nil, err } return chooseHostInterfaceFromRoute(routes, nw, addressFamilies) } // networkInterfacer defines an interface for several net library functions. Production // code will forward to net library functions, and unit tests will override the methods // for testing purposes. type networkInterfacer interface { InterfaceByName(intfName string) (*net.Interface, error) Addrs(intf *net.Interface) ([]net.Addr, error) Interfaces() ([]net.Interface, error) } // networkInterface implements the networkInterfacer interface for production code, just // wrapping the underlying net library function calls. type networkInterface struct{} func (_ networkInterface) InterfaceByName(intfName string) (*net.Interface, error) { return net.InterfaceByName(intfName) } func (_ networkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { return intf.Addrs() } func (_ networkInterface) Interfaces() ([]net.Interface, error) { return net.Interfaces() } // getAllDefaultRoutes obtains IPv4 and IPv6 default routes on the node. If unable // to read the IPv4 routing info file, we return an error. If unable to read the IPv6 // routing info file (which is optional), we'll just use the IPv4 route information. // Using all the routing info, if no default routes are found, an error is returned. func getAllDefaultRoutes() ([]Route, error) { routes, err := v4File.extract() if err != nil { return nil, err } v6Routes, _ := v6File.extract() routes = append(routes, v6Routes...) if len(routes) == 0 { return nil, noRoutesError{ message: fmt.Sprintf("no default routes found in %q or %q", v4File.name, v6File.name), } } return routes, nil } // chooseHostInterfaceFromRoute cycles through each default route provided, looking for a // 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) { for _, family := range addressFamilies { klog.V(4).Infof("Looking for default routes with IPv%d addresses", 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) if err != nil { return nil, err } if finalIP != nil { klog.V(4).Infof("Found active IP %v ", 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) if err != nil { return nil, err } if loopbackIP != nil { klog.V(4).Infof("Found active IP %v on Loopback interface", loopbackIP) return loopbackIP, nil } } } klog.V(4).Infof("No active IP found by looking at default routes") return nil, fmt.Errorf("unable to select an IP from default routes.") } // ResolveBindAddress 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 ResolveBindAddress(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) if err != nil { return nil, err } bindAddress = hostIP } return bindAddress, nil } // ChooseBindAddressForInterface 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 ChooseBindAddressForInterface(intfName string) (net.IP, error) { var nw networkInterfacer = networkInterface{} for _, family := range preferIPv4 { ip, err := getIPFromInterface(intfName, family, nw) if err != nil { return nil, err } if ip != nil { return ip, nil } } return nil, fmt.Errorf("unable to select an IP from %s network interface", intfName) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/util.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/util.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 net import ( "errors" "net" "reflect" "strings" "syscall" ) // IPNetEqual checks if the two input IPNets are representing the same subnet. // For example, // // 10.0.0.1/24 and 10.0.0.0/24 are the same subnet. // 10.0.0.1/24 and 10.0.0.0/25 are not the same subnet. func IPNetEqual(ipnet1, ipnet2 *net.IPNet) bool { if ipnet1 == nil || ipnet2 == nil { return false } if reflect.DeepEqual(ipnet1.Mask, ipnet2.Mask) && ipnet1.Contains(ipnet2.IP) && ipnet2.Contains(ipnet1.IP) { return true } return false } // Returns if the given err is "connection reset by peer" error. func IsConnectionReset(err error) bool { var errno syscall.Errno if errors.As(err, &errno) { return errno == syscall.ECONNRESET } return false } // Returns if the given err is "http2: client connection lost" error. func IsHTTP2ConnectionLost(err error) bool { return err != nil && strings.Contains(err.Error(), "http2: client connection lost") } // Returns if the given err is "connection refused" error func IsConnectionRefused(err error) bool { var errno syscall.Errno if errors.As(err, &errno) { return errno == syscall.ECONNREFUSED } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/http.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/net/http.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 net import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io" "mime" "net" "net/http" "net/url" "os" "path" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "golang.org/x/net/http2" "k8s.io/klog/v2" netutils "k8s.io/utils/net" ) // JoinPreservingTrailingSlash does a path.Join of the specified elements, // preserving any trailing slash on the last non-empty segment func JoinPreservingTrailingSlash(elem ...string) string { // do the basic path join result := path.Join(elem...) // find the last non-empty segment for i := len(elem) - 1; i >= 0; i-- { if len(elem[i]) > 0 { // if the last segment ended in a slash, ensure our result does as well if strings.HasSuffix(elem[i], "/") && !strings.HasSuffix(result, "/") { result += "/" } break } } return result } // IsTimeout returns true if the given error is a network timeout error func IsTimeout(err error) bool { var neterr net.Error if errors.As(err, &neterr) { return neterr != nil && neterr.Timeout() } return false } // IsProbableEOF returns true if the given error resembles a connection termination // scenario that would justify assuming that the watch is empty. // These errors are what the Go http stack returns back to us which are general // connection closure errors (strongly correlated) and callers that need to // differentiate probable errors in connection behavior between normal "this is // disconnected" should use the method. func IsProbableEOF(err error) bool { if err == nil { return false } var uerr *url.Error if errors.As(err, &uerr) { err = uerr.Err } msg := err.Error() switch { case err == io.EOF: return true case err == io.ErrUnexpectedEOF: return true case msg == "http: can't write HTTP request on broken connection": return true case strings.Contains(msg, "http2: server sent GOAWAY and closed the connection"): return true case strings.Contains(msg, "connection reset by peer"): return true case strings.Contains(strings.ToLower(msg), "use of closed network connection"): return true } return false } var defaultTransport = http.DefaultTransport.(*http.Transport) // SetOldTransportDefaults applies the defaults from http.DefaultTransport // for the Proxy, Dial, and TLSHandshakeTimeout fields if unset func SetOldTransportDefaults(t *http.Transport) *http.Transport { if t.Proxy == nil || isDefault(t.Proxy) { // http.ProxyFromEnvironment doesn't respect CIDRs and that makes it impossible to exclude things like pod and service IPs from proxy settings // ProxierWithNoProxyCIDR allows CIDR rules in NO_PROXY t.Proxy = NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment) } // If no custom dialer is set, use the default context dialer //lint:file-ignore SA1019 Keep supporting deprecated Dial method of custom transports if t.DialContext == nil && t.Dial == nil { t.DialContext = defaultTransport.DialContext } if t.TLSHandshakeTimeout == 0 { t.TLSHandshakeTimeout = defaultTransport.TLSHandshakeTimeout } if t.IdleConnTimeout == 0 { t.IdleConnTimeout = defaultTransport.IdleConnTimeout } return t } // SetTransportDefaults applies the defaults from http.DefaultTransport // for the Proxy, Dial, and TLSHandshakeTimeout fields if unset 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 { klog.Info("HTTP2 has been explicitly disabled") } else if allowsHTTP2(t) { if err := configureHTTP2Transport(t); err != nil { klog.Warningf("Transport failed http2 configuration: %v", err) } } return t } func readIdleTimeoutSeconds() int { ret := 30 // User can set the readIdleTimeout to 0 to disable the HTTP/2 // connection health check. if s := os.Getenv("HTTP2_READ_IDLE_TIMEOUT_SECONDS"); len(s) > 0 { i, err := strconv.Atoi(s) if err != nil { klog.Warningf("Illegal HTTP2_READ_IDLE_TIMEOUT_SECONDS(%q): %v."+ " Default value %d is used", s, err, ret) return ret } ret = i } return ret } func pingTimeoutSeconds() int { ret := 15 if s := os.Getenv("HTTP2_PING_TIMEOUT_SECONDS"); len(s) > 0 { i, err := strconv.Atoi(s) if err != nil { klog.Warningf("Illegal HTTP2_PING_TIMEOUT_SECONDS(%q): %v."+ " Default value %d is used", s, err, ret) return ret } ret = i } return ret } func configureHTTP2Transport(t *http.Transport) error { t2, err := http2.ConfigureTransports(t) if err != nil { return err } // The following enables the HTTP/2 connection health check added in // https://github.com/golang/net/pull/55. The health check detects and // closes broken transport layer connections. Without the health check, // a broken connection can linger too long, e.g., a broken TCP // connection will be closed by the Linux kernel after 13 to 30 minutes // by default, which caused // https://github.com/kubernetes/client-go/issues/374 and // https://github.com/kubernetes/kubernetes/issues/87615. t2.ReadIdleTimeout = time.Duration(readIdleTimeoutSeconds()) * time.Second t2.PingTimeout = time.Duration(pingTimeoutSeconds()) * time.Second return nil } func allowsHTTP2(t *http.Transport) bool { if t.TLSClientConfig == nil || len(t.TLSClientConfig.NextProtos) == 0 { // the transport expressed no NextProto preference, allow return true } for _, p := range t.TLSClientConfig.NextProtos { if p == http2.NextProtoTLS { // the transport explicitly allowed http/2 return true } } // the transport explicitly set NextProtos and excluded http/2 return false } type RoundTripperWrapper interface { http.RoundTripper WrappedRoundTripper() http.RoundTripper } type DialFunc func(ctx context.Context, net, addr string) (net.Conn, error) func DialerFor(transport http.RoundTripper) (DialFunc, error) { if transport == nil { return nil, nil } switch transport := transport.(type) { case *http.Transport: // transport.DialContext takes precedence over transport.Dial if transport.DialContext != nil { return transport.DialContext, nil } // adapt transport.Dial to the DialWithContext signature if transport.Dial != nil { return func(ctx context.Context, net, addr string) (net.Conn, error) { return transport.Dial(net, addr) }, nil } // otherwise return nil return nil, nil case RoundTripperWrapper: return DialerFor(transport.WrappedRoundTripper()) default: return nil, fmt.Errorf("unknown transport type: %T", transport) } } // CloseIdleConnectionsFor close idles connections for the Transport. // If the Transport is wrapped it iterates over the wrapped round trippers // until it finds one that implements the CloseIdleConnections method. // If the Transport does not have a CloseIdleConnections method // then this function does nothing. func CloseIdleConnectionsFor(transport http.RoundTripper) { if transport == nil { return } type closeIdler interface { CloseIdleConnections() } switch transport := transport.(type) { case closeIdler: transport.CloseIdleConnections() case RoundTripperWrapper: CloseIdleConnectionsFor(transport.WrappedRoundTripper()) default: klog.Warningf("unknown transport type: %T", transport) } } type TLSClientConfigHolder interface { TLSClientConfig() *tls.Config } func TLSClientConfig(transport http.RoundTripper) (*tls.Config, error) { if transport == nil { return nil, nil } switch transport := transport.(type) { case *http.Transport: return transport.TLSClientConfig, nil case TLSClientConfigHolder: return transport.TLSClientConfig(), nil case RoundTripperWrapper: return TLSClientConfig(transport.WrappedRoundTripper()) default: return nil, fmt.Errorf("unknown transport type: %T", transport) } } func FormatURL(scheme string, host string, port int, path string) *url.URL { return &url.URL{ Scheme: scheme, Host: net.JoinHostPort(host, strconv.Itoa(port)), Path: path, } } func GetHTTPClient(req *http.Request) string { if ua := req.UserAgent(); len(ua) != 0 { return ua } return "unknown" } // SourceIPs splits the comma separated X-Forwarded-For header and joins it with // the X-Real-Ip header and/or req.RemoteAddr, ignoring invalid IPs. // The X-Real-Ip is omitted if it's already present in the X-Forwarded-For chain. // The req.RemoteAddr is always the last IP in the returned list. // It returns nil if all of these are empty or invalid. func SourceIPs(req *http.Request) []net.IP { var srcIPs []net.IP hdr := req.Header // First check the X-Forwarded-For header for requests via proxy. hdrForwardedFor := hdr.Get("X-Forwarded-For") if hdrForwardedFor != "" { // X-Forwarded-For can be a csv of IPs in case of multiple proxies. // Use the first valid one. parts := strings.Split(hdrForwardedFor, ",") for _, part := range parts { ip := netutils.ParseIPSloppy(strings.TrimSpace(part)) if ip != nil { srcIPs = append(srcIPs, ip) } } } // Try the X-Real-Ip header. hdrRealIp := hdr.Get("X-Real-Ip") if hdrRealIp != "" { ip := netutils.ParseIPSloppy(hdrRealIp) // Only append the X-Real-Ip if it's not already contained in the X-Forwarded-For chain. if ip != nil && !containsIP(srcIPs, ip) { srcIPs = append(srcIPs, ip) } } // Always include the request Remote Address as it cannot be easily spoofed. var remoteIP net.IP // Remote Address in Go's HTTP server is in the form host:port so we need to split that first. host, _, err := net.SplitHostPort(req.RemoteAddr) if err == nil { remoteIP = netutils.ParseIPSloppy(host) } // Fallback if Remote Address was just IP. if remoteIP == nil { remoteIP = netutils.ParseIPSloppy(req.RemoteAddr) } // Don't duplicate remote IP if it's already the last address in the chain. if remoteIP != nil && (len(srcIPs) == 0 || !remoteIP.Equal(srcIPs[len(srcIPs)-1])) { srcIPs = append(srcIPs, remoteIP) } return srcIPs } // Checks whether the given IP address is contained in the list of IPs. func containsIP(ips []net.IP, ip net.IP) bool { for _, v := range ips { if v.Equal(ip) { return true } } return false } // Extracts and returns the clients IP from the given request. // Looks at X-Forwarded-For header, X-Real-Ip header and request.RemoteAddr in that order. // Returns nil if none of them are set or is set to an invalid value. func GetClientIP(req *http.Request) net.IP { ips := SourceIPs(req) if len(ips) == 0 { return nil } return ips[0] } // Prepares the X-Forwarded-For header for another forwarding hop by appending the previous sender's // IP address to the X-Forwarded-For chain. func AppendForwardedForHeader(req *http.Request) { // Copied from net/http/httputil/reverseproxy.go: if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil { // If we aren't the first proxy retain prior // X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. if prior, ok := req.Header["X-Forwarded-For"]; ok { clientIP = strings.Join(prior, ", ") + ", " + clientIP } req.Header.Set("X-Forwarded-For", clientIP) } } var defaultProxyFuncPointer = fmt.Sprintf("%p", http.ProxyFromEnvironment) // isDefault checks to see if the transportProxierFunc is pointing to the default one func isDefault(transportProxier func(*http.Request) (*url.URL, error)) bool { transportProxierPointer := fmt.Sprintf("%p", transportProxier) return transportProxierPointer == defaultProxyFuncPointer } // NewProxierWithNoProxyCIDR constructs a Proxier function that respects CIDRs in NO_PROXY and delegates if // no matching CIDRs are found func NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error)) func(req *http.Request) (*url.URL, error) { // we wrap the default method, so we only need to perform our check if the NO_PROXY (or no_proxy) envvar has a CIDR in it noProxyEnv := os.Getenv("NO_PROXY") if noProxyEnv == "" { noProxyEnv = os.Getenv("no_proxy") } noProxyRules := strings.Split(noProxyEnv, ",") cidrs := []*net.IPNet{} for _, noProxyRule := range noProxyRules { _, cidr, _ := netutils.ParseCIDRSloppy(noProxyRule) if cidr != nil { cidrs = append(cidrs, cidr) } } if len(cidrs) == 0 { return delegate } return func(req *http.Request) (*url.URL, error) { ip := netutils.ParseIPSloppy(req.URL.Hostname()) if ip == nil { return delegate(req) } for _, cidr := range cidrs { if cidr.Contains(ip) { return nil, nil } } return delegate(req) } } // DialerFunc implements Dialer for the provided function. type DialerFunc func(req *http.Request) (net.Conn, error) func (fn DialerFunc) Dial(req *http.Request) (net.Conn, error) { return fn(req) } // Dialer dials a host and writes a request to it. type Dialer interface { // Dial connects to the host specified by req's URL, writes the request to the connection, and // returns the opened net.Conn. Dial(req *http.Request) (net.Conn, error) } // CloneRequest creates a shallow copy of the request along with a deep copy of the Headers. func CloneRequest(req *http.Request) *http.Request { r := new(http.Request) // shallow clone *r = *req // deep copy headers r.Header = CloneHeader(req.Header) return r } // CloneHeader creates a deep copy of an http.Header. func CloneHeader(in http.Header) http.Header { out := make(http.Header, len(in)) for key, values := range in { newValues := make([]string, len(values)) copy(newValues, values) out[key] = newValues } return out } // WarningHeader contains a single RFC2616 14.46 warnings header type WarningHeader struct { // Codeindicates the type of warning. 299 is a miscellaneous persistent warning Code int // Agent contains the name or pseudonym of the server adding the Warning header. // A single "-" is recommended when agent is unknown. Agent string // Warning text Text string } // ParseWarningHeaders extract RFC2616 14.46 warnings headers from the specified set of header values. // Multiple comma-separated warnings per header are supported. // If errors are encountered on a header, the remainder of that header are skipped and subsequent headers are parsed. // Returns successfully parsed warnings and any errors encountered. func ParseWarningHeaders(headers []string) ([]WarningHeader, []error) { var ( results []WarningHeader errs []error ) for _, header := range headers { for len(header) > 0 { result, remainder, err := ParseWarningHeader(header) if err != nil { errs = append(errs, err) break } results = append(results, result) header = remainder } } return results, errs } var ( codeMatcher = regexp.MustCompile(`^[0-9]{3}$`) wordDecoder = &mime.WordDecoder{} ) // ParseWarningHeader extracts one RFC2616 14.46 warning from the specified header, // returning an error if the header does not contain a correctly formatted warning. // Any remaining content in the header is returned. func ParseWarningHeader(header string) (result WarningHeader, remainder string, err error) { // https://tools.ietf.org/html/rfc2616#section-14.46 // updated by // https://tools.ietf.org/html/rfc7234#section-5.5 // https://tools.ietf.org/html/rfc7234#appendix-A // Some requirements regarding production and processing of the Warning // header fields have been relaxed, as it is not widely implemented. // Furthermore, the Warning header field no longer uses RFC 2047 // encoding, nor does it allow multiple languages, as these aspects were // not implemented. // // Format is one of: // warn-code warn-agent "warn-text" // warn-code warn-agent "warn-text" "warn-date" // // warn-code is a three digit number // warn-agent is unquoted and contains no spaces // warn-text is quoted with backslash escaping (RFC2047-encoded according to RFC2616, not encoded according to RFC7234) // warn-date is optional, quoted, and in HTTP-date format (no embedded or escaped quotes) // // additional warnings can optionally be included in the same header by comma-separating them: // warn-code warn-agent "warn-text" "warn-date"[, warn-code warn-agent "warn-text" "warn-date", ...] // tolerate leading whitespace header = strings.TrimSpace(header) parts := strings.SplitN(header, " ", 3) if len(parts) != 3 { return WarningHeader{}, "", errors.New("invalid warning header: fewer than 3 segments") } code, agent, textDateRemainder := parts[0], parts[1], parts[2] // verify code format if !codeMatcher.Match([]byte(code)) { return WarningHeader{}, "", errors.New("invalid warning header: code segment is not 3 digits between 100-299") } codeInt, _ := strconv.ParseInt(code, 10, 64) // verify agent presence if len(agent) == 0 { return WarningHeader{}, "", errors.New("invalid warning header: empty agent segment") } if !utf8.ValidString(agent) || hasAnyRunes(agent, unicode.IsControl) { return WarningHeader{}, "", errors.New("invalid warning header: invalid agent") } // verify textDateRemainder presence if len(textDateRemainder) == 0 { return WarningHeader{}, "", errors.New("invalid warning header: empty text segment") } // extract text text, dateAndRemainder, err := parseQuotedString(textDateRemainder) if err != nil { return WarningHeader{}, "", fmt.Errorf("invalid warning header: %v", err) } // tolerate RFC2047-encoded text from warnings produced according to RFC2616 if decodedText, err := wordDecoder.DecodeHeader(text); err == nil { text = decodedText } if !utf8.ValidString(text) || hasAnyRunes(text, unicode.IsControl) { return WarningHeader{}, "", errors.New("invalid warning header: invalid text") } result = WarningHeader{Code: int(codeInt), Agent: agent, Text: text} if len(dateAndRemainder) > 0 { if dateAndRemainder[0] == '"' { // consume date foundEndQuote := false for i := 1; i < len(dateAndRemainder); i++ { if dateAndRemainder[i] == '"' { foundEndQuote = true remainder = strings.TrimSpace(dateAndRemainder[i+1:]) break } } if !foundEndQuote { return WarningHeader{}, "", errors.New("invalid warning header: unterminated date segment") } } else { remainder = dateAndRemainder } } if len(remainder) > 0 { if remainder[0] == ',' { // consume comma if present remainder = strings.TrimSpace(remainder[1:]) } else { return WarningHeader{}, "", errors.New("invalid warning header: unexpected token after warn-date") } } return result, remainder, nil } func parseQuotedString(quotedString string) (string, string, error) { if len(quotedString) == 0 { return "", "", errors.New("invalid quoted string: 0-length") } if quotedString[0] != '"' { return "", "", errors.New("invalid quoted string: missing initial quote") } quotedString = quotedString[1:] var remainder string escaping := false closedQuote := false result := &strings.Builder{} loop: for i := 0; i < len(quotedString); i++ { b := quotedString[i] switch b { case '"': if escaping { result.WriteByte(b) escaping = false } else { closedQuote = true remainder = strings.TrimSpace(quotedString[i+1:]) break loop } case '\\': if escaping { result.WriteByte(b) escaping = false } else { escaping = true } default: result.WriteByte(b) escaping = false } } if !closedQuote { return "", "", errors.New("invalid quoted string: missing closing quote") } return result.String(), remainder, nil } func NewWarningHeader(code int, agent, text string) (string, error) { if code < 0 || code > 999 { return "", errors.New("code must be between 0 and 999") } if len(agent) == 0 { agent = "-" } else if !utf8.ValidString(agent) || strings.ContainsAny(agent, `\"`) || hasAnyRunes(agent, unicode.IsSpace, unicode.IsControl) { return "", errors.New("agent must be valid UTF-8 and must not contain spaces, quotes, backslashes, or control characters") } if !utf8.ValidString(text) || hasAnyRunes(text, unicode.IsControl) { return "", errors.New("text must be valid UTF-8 and must not contain control characters") } return fmt.Sprintf("%03d %s %s", code, agent, makeQuotedString(text)), nil } func hasAnyRunes(s string, runeCheckers ...func(rune) bool) bool { for _, r := range s { for _, checker := range runeCheckers { if checker(r) { return true } } } return false } func makeQuotedString(s string) string { result := &bytes.Buffer{} // opening quote result.WriteRune('"') for _, c := range s { switch c { case '"', '\\': // escape " and \ result.WriteRune('\\') result.WriteRune(c) default: // write everything else as-is result.WriteRune(c) } } // closing quote result.WriteRune('"') return result.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mergepatch import ( "errors" "fmt" "reflect" ) var ( ErrBadJSONDoc = errors.New("invalid JSON document") ErrNoListOfLists = errors.New("lists of lists are not supported") ErrBadPatchFormatForPrimitiveList = errors.New("invalid patch format of primitive list") ErrBadPatchFormatForRetainKeys = errors.New("invalid patch format of retainKeys") ErrBadPatchFormatForSetElementOrderList = errors.New("invalid patch format of setElementOrder list") ErrPatchContentNotMatchRetainKeys = errors.New("patch content doesn't match retainKeys list") ErrUnsupportedStrategicMergePatchFormat = errors.New("strategic merge patch format is not supported") ) func ErrNoMergeKey(m map[string]interface{}, k string) error { return fmt.Errorf("map: %v does not contain declared merge key: %s", m, k) } func ErrBadArgType(expected, actual interface{}) error { return fmt.Errorf("expected a %s, but received a %s", reflect.TypeOf(expected), reflect.TypeOf(actual)) } func ErrBadArgKind(expected, actual interface{}) error { var expectedKindString, actualKindString string if expected == nil { expectedKindString = "nil" } else { expectedKindString = reflect.TypeOf(expected).Kind().String() } if actual == nil { actualKindString = "nil" } else { actualKindString = reflect.TypeOf(actual).Kind().String() } return fmt.Errorf("expected a %s, but received a %s", expectedKindString, actualKindString) } func ErrBadPatchType(t interface{}, m map[string]interface{}) error { return fmt.Errorf("unknown patch type: %s in map: %v", t, m) } // IsPreconditionFailed returns true if the provided error indicates // a precondition failed. func IsPreconditionFailed(err error) bool { _, ok := err.(ErrPreconditionFailed) return ok } type ErrPreconditionFailed struct { message string } func NewErrPreconditionFailed(target map[string]interface{}) ErrPreconditionFailed { s := fmt.Sprintf("precondition failed for: %v", target) return ErrPreconditionFailed{s} } func (err ErrPreconditionFailed) Error() string { return err.message } type ErrConflict struct { message string } func NewErrConflict(patch, current string) ErrConflict { s := fmt.Sprintf("patch:\n%s\nconflicts with changes made from original to current:\n%s\n", patch, current) return ErrConflict{s} } func (err ErrConflict) Error() string { return err.message } // IsConflict returns true if the provided error indicates // a conflict between the patch and the current configuration. func IsConflict(err error) bool { _, ok := err.(ErrConflict) return ok }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mergepatch import ( "fmt" "reflect" "k8s.io/apimachinery/pkg/util/dump" "sigs.k8s.io/yaml" ) // PreconditionFunc asserts that an incompatible change is not present within a patch. type PreconditionFunc func(interface{}) bool // RequireKeyUnchanged returns a precondition function that fails if the provided key // is present in the patch (indicating that its value has changed). func RequireKeyUnchanged(key string) PreconditionFunc { return func(patch interface{}) bool { patchMap, ok := patch.(map[string]interface{}) if !ok { return true } // The presence of key means that its value has been changed, so the test fails. _, ok = patchMap[key] return !ok } } // RequireMetadataKeyUnchanged creates a precondition function that fails // if the metadata.key is present in the patch (indicating its value // has changed). func RequireMetadataKeyUnchanged(key string) PreconditionFunc { return func(patch interface{}) bool { patchMap, ok := patch.(map[string]interface{}) if !ok { return true } patchMap1, ok := patchMap["metadata"] if !ok { return true } patchMap2, ok := patchMap1.(map[string]interface{}) if !ok { return true } _, ok = patchMap2[key] return !ok } } func ToYAMLOrError(v interface{}) string { y, err := toYAML(v) if err != nil { return err.Error() } return y } func toYAML(v interface{}) (string, error) { y, err := yaml.Marshal(v) if err != nil { return "", fmt.Errorf("yaml marshal failed:%v\n%v\n", err, dump.Pretty(v)) } return string(y), nil } // HasConflicts returns true if the left and right JSON interface objects overlap with // different values in any key. All keys are required to be strings. Since patches of the // same Type have congruent keys, this is valid for multiple patch types. This method // supports JSON merge patch semantics. // // NOTE: Numbers with different types (e.g. int(0) vs int64(0)) will be detected as conflicts. // Make sure the unmarshaling of left and right are consistent (e.g. use the same library). func HasConflicts(left, right interface{}) (bool, error) { switch typedLeft := left.(type) { case map[string]interface{}: switch typedRight := right.(type) { case map[string]interface{}: for key, leftValue := range typedLeft { rightValue, ok := typedRight[key] if !ok { continue } if conflict, err := HasConflicts(leftValue, rightValue); err != nil || conflict { return conflict, err } } return false, nil default: return true, nil } case []interface{}: switch typedRight := right.(type) { case []interface{}: if len(typedLeft) != len(typedRight) { return true, nil } for i := range typedLeft { if conflict, err := HasConflicts(typedLeft[i], typedRight[i]); err != nil || conflict { return conflict, err } } return false, nil default: return true, nil } case string, float64, bool, int64, nil: return !reflect.DeepEqual(left, right), nil default: return true, fmt.Errorf("unknown type: %v", reflect.TypeOf(left)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package yaml import ( "bufio" "bytes" "encoding/json" "fmt" "io" "strings" "unicode" jsonutil "k8s.io/apimachinery/pkg/util/json" "sigs.k8s.io/yaml" ) // Unmarshal unmarshals the given data // If v is a *map[string]interface{}, *[]interface{}, or *interface{} numbers // are converted to int64 or float64 func Unmarshal(data []byte, v interface{}) error { preserveIntFloat := func(d *json.Decoder) *json.Decoder { d.UseNumber() return d } switch v := v.(type) { case *map[string]interface{}: if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertMapNumbers(*v, 0) case *[]interface{}: if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertSliceNumbers(*v, 0) case *interface{}: if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertInterfaceNumbers(v, 0) default: return yaml.Unmarshal(data, v) } } // UnmarshalStrict unmarshals the given data // strictly (erroring when there are duplicate fields). func UnmarshalStrict(data []byte, v interface{}) error { preserveIntFloat := func(d *json.Decoder) *json.Decoder { d.UseNumber() return d } switch v := v.(type) { case *map[string]interface{}: if err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertMapNumbers(*v, 0) case *[]interface{}: if err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertSliceNumbers(*v, 0) case *interface{}: if err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil { return err } return jsonutil.ConvertInterfaceNumbers(v, 0) default: return yaml.UnmarshalStrict(data, v) } } // ToJSON converts a single YAML document into a JSON document // or returns an error. If the document appears to be JSON the // YAML decoding path is not used (so that error messages are // JSON specific). func ToJSON(data []byte) ([]byte, error) { if hasJSONPrefix(data) { return data, nil } return yaml.YAMLToJSON(data) } // YAMLToJSONDecoder decodes YAML documents from an io.Reader by // separating individual documents. It first converts the YAML // body to JSON, then unmarshals the JSON. type YAMLToJSONDecoder struct { reader Reader } // NewYAMLToJSONDecoder decodes YAML documents from the provided // stream in chunks by converting each document (as defined by // the YAML spec) into its own chunk, converting it to JSON via // yaml.YAMLToJSON, and then passing it to json.Decoder. func NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder { reader := bufio.NewReader(r) return &YAMLToJSONDecoder{ reader: NewYAMLReader(reader), } } // Decode reads a YAML document as JSON from the stream or returns // an error. The decoding rules match json.Unmarshal, not // yaml.Unmarshal. func (d *YAMLToJSONDecoder) Decode(into interface{}) error { bytes, err := d.reader.Read() if err != nil && err != io.EOF { return err } if len(bytes) != 0 { err := yaml.Unmarshal(bytes, into) if err != nil { return YAMLSyntaxError{err} } } return err } // YAMLDecoder reads chunks of objects and returns ErrShortBuffer if // the data is not sufficient. type YAMLDecoder struct { r io.ReadCloser scanner *bufio.Scanner remaining []byte } // NewDocumentDecoder decodes YAML documents from the provided // stream in chunks by converting each document (as defined by // the YAML spec) into its own chunk. io.ErrShortBuffer will be // returned if the entire buffer could not be read to assist // the caller in framing the chunk. func NewDocumentDecoder(r io.ReadCloser) io.ReadCloser { scanner := bufio.NewScanner(r) // the size of initial allocation for buffer 4k buf := make([]byte, 4*1024) // the maximum size used to buffer a token 5M scanner.Buffer(buf, 5*1024*1024) scanner.Split(splitYAMLDocument) return &YAMLDecoder{ r: r, scanner: scanner, } } // Read reads the previous slice into the buffer, or attempts to read // the next chunk. // TODO: switch to readline approach. func (d *YAMLDecoder) Read(data []byte) (n int, err error) { left := len(d.remaining) if left == 0 { // return the next chunk from the stream if !d.scanner.Scan() { err := d.scanner.Err() if err == nil { err = io.EOF } return 0, err } out := d.scanner.Bytes() d.remaining = out left = len(out) } // fits within data if left <= len(data) { copy(data, d.remaining) d.remaining = nil return left, nil } // caller will need to reread copy(data, d.remaining[:len(data)]) d.remaining = d.remaining[len(data):] return len(data), io.ErrShortBuffer } func (d *YAMLDecoder) Close() error { return d.r.Close() } const yamlSeparator = "\n---" const separator = "---" // splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents. func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } sep := len([]byte(yamlSeparator)) if i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 { // We have a potential document terminator i += sep after := data[i:] if len(after) == 0 { // we can't read any more characters if atEOF { return len(data), data[:len(data)-sep], nil } return 0, nil, nil } if j := bytes.IndexByte(after, '\n'); j >= 0 { return i + j + 1, data[0 : i-sep], nil } return 0, nil, nil } // If we're at EOF, we have a final, non-terminated line. Return it. if atEOF { return len(data), data, nil } // Request more data. return 0, nil, nil } // decoder is a convenience interface for Decode. type decoder interface { Decode(into interface{}) error } // YAMLOrJSONDecoder attempts to decode a stream of JSON documents or // YAML documents by sniffing for a leading { character. type YAMLOrJSONDecoder struct { r io.Reader bufferSize int decoder decoder } type JSONSyntaxError struct { Offset int64 Err error } func (e JSONSyntaxError) Error() string { return fmt.Sprintf("json: offset %d: %s", e.Offset, e.Err.Error()) } type YAMLSyntaxError struct { err error } func (e YAMLSyntaxError) Error() string { return e.err.Error() } // NewYAMLOrJSONDecoder returns a decoder that will process YAML documents // or JSON documents from the given reader as a stream. bufferSize determines // how far into the stream the decoder will look to figure out whether this // is a JSON stream (has whitespace followed by an open brace). func NewYAMLOrJSONDecoder(r io.Reader, bufferSize int) *YAMLOrJSONDecoder { return &YAMLOrJSONDecoder{ r: r, bufferSize: bufferSize, } } // Decode unmarshals the next object from the underlying stream into the // provide object, or returns an error. func (d *YAMLOrJSONDecoder) Decode(into interface{}) error { if d.decoder == nil { buffer, _, isJSON := GuessJSONStream(d.r, d.bufferSize) if isJSON { d.decoder = json.NewDecoder(buffer) } else { d.decoder = NewYAMLToJSONDecoder(buffer) } } err := d.decoder.Decode(into) if syntax, ok := err.(*json.SyntaxError); ok { return JSONSyntaxError{ Offset: syntax.Offset, Err: syntax, } } return err } type Reader interface { Read() ([]byte, error) } type YAMLReader struct { reader Reader } func NewYAMLReader(r *bufio.Reader) *YAMLReader { return &YAMLReader{ reader: &LineReader{reader: r}, } } // Read returns a full YAML document. func (r *YAMLReader) Read() ([]byte, error) { var buffer bytes.Buffer for { line, err := r.reader.Read() if err != nil && err != io.EOF { return nil, err } sep := len([]byte(separator)) if i := bytes.Index(line, []byte(separator)); i == 0 { // We have a potential document terminator i += sep trimmed := strings.TrimSpace(string(line[i:])) // We only allow comments and spaces following the yaml doc separator, otherwise we'll return an error if len(trimmed) > 0 && string(trimmed[0]) != "#" { return nil, YAMLSyntaxError{ err: fmt.Errorf("invalid Yaml document separator: %s", trimmed), } } if buffer.Len() != 0 { return buffer.Bytes(), nil } if err == io.EOF { return nil, err } } if err == io.EOF { if buffer.Len() != 0 { // If we're at EOF, we have a final, non-terminated line. Return it. return buffer.Bytes(), nil } return nil, err } buffer.Write(line) } } type LineReader struct { reader *bufio.Reader } // Read returns a single line (with '\n' ended) from the underlying reader. // An error is returned iff there is an error with the underlying reader. func (r *LineReader) Read() ([]byte, error) { var ( isPrefix bool = true err error = nil line []byte buffer bytes.Buffer ) for isPrefix && err == nil { line, isPrefix, err = r.reader.ReadLine() buffer.Write(line) } buffer.WriteByte('\n') return buffer.Bytes(), err } // GuessJSONStream scans the provided reader up to size, looking // for an open brace indicating this is JSON. It will return the // bufio.Reader it creates for the consumer. func GuessJSONStream(r io.Reader, size int) (io.Reader, []byte, bool) { buffer := bufio.NewReaderSize(r, size) b, _ := buffer.Peek(size) return buffer, b, hasJSONPrefix(b) } // IsJSONBuffer scans the provided buffer, looking // for an open brace indicating this is JSON. func IsJSONBuffer(buf []byte) bool { return hasJSONPrefix(buf) } var jsonPrefix = []byte("{") // hasJSONPrefix returns true if the provided buffer appears to start with // a JSON open brace. func hasJSONPrefix(buf []byte) bool { return hasPrefix(buf, jsonPrefix) } // Return true if the first non-whitespace bytes in buf is // prefix. func hasPrefix(buf []byte, prefix []byte) bool { trim := bytes.TrimLeftFunc(buf, unicode.IsSpace) return bytes.HasPrefix(trim, prefix) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go
/* 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 managedfields import ( "fmt" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/managedfields/internal" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) var ( scaleGroupVersion = schema.GroupVersion{Group: "autoscaling", Version: "v1"} replicasPathInScale = fieldpath.MakePathOrDie("spec", "replicas") ) // ResourcePathMappings maps a group/version to its replicas path. The // assumption is that all the paths correspond to leaf fields. type ResourcePathMappings map[string]fieldpath.Path // ScaleHandler manages the conversion of managed fields between a main // resource and the scale subresource type ScaleHandler struct { parentEntries []metav1.ManagedFieldsEntry groupVersion schema.GroupVersion mappings ResourcePathMappings } // NewScaleHandler creates a new ScaleHandler func NewScaleHandler(parentEntries []metav1.ManagedFieldsEntry, groupVersion schema.GroupVersion, mappings ResourcePathMappings) *ScaleHandler { return &ScaleHandler{ parentEntries: parentEntries, groupVersion: groupVersion, mappings: mappings, } } // ToSubresource filter the managed fields of the main resource and convert // them so that they can be handled by scale. // For the managed fields that have a replicas path it performs two changes: // 1. APIVersion is changed to the APIVersion of the scale subresource // 2. Replicas path of the main resource is transformed to the replicas path of // the scale subresource func (h *ScaleHandler) ToSubresource() ([]metav1.ManagedFieldsEntry, error) { managed, err := internal.DecodeManagedFields(h.parentEntries) if err != nil { return nil, err } f := fieldpath.ManagedFields{} t := map[string]*metav1.Time{} for manager, versionedSet := range managed.Fields() { path, ok := h.mappings[string(versionedSet.APIVersion())] // Skip the entry if the APIVersion is unknown if !ok || path == nil { continue } if versionedSet.Set().Has(path) { newVersionedSet := fieldpath.NewVersionedSet( fieldpath.NewSet(replicasPathInScale), fieldpath.APIVersion(scaleGroupVersion.String()), versionedSet.Applied(), ) f[manager] = newVersionedSet t[manager] = managed.Times()[manager] } } return managedFieldsEntries(internal.NewManaged(f, t)) } // ToParent merges `scaleEntries` with the entries of the main resource and // transforms them accordingly func (h *ScaleHandler) ToParent(scaleEntries []metav1.ManagedFieldsEntry) ([]metav1.ManagedFieldsEntry, error) { decodedParentEntries, err := internal.DecodeManagedFields(h.parentEntries) if err != nil { return nil, err } parentFields := decodedParentEntries.Fields() decodedScaleEntries, err := internal.DecodeManagedFields(scaleEntries) if err != nil { return nil, err } scaleFields := decodedScaleEntries.Fields() f := fieldpath.ManagedFields{} t := map[string]*metav1.Time{} for manager, versionedSet := range parentFields { // Get the main resource "replicas" path path, ok := h.mappings[string(versionedSet.APIVersion())] // Drop the entry if the APIVersion is unknown. if !ok { continue } // If the parent entry does not have the replicas path or it is nil, just // keep it as it is. The path is nil for Custom Resources without scale // subresource. if path == nil || !versionedSet.Set().Has(path) { f[manager] = versionedSet t[manager] = decodedParentEntries.Times()[manager] continue } if _, ok := scaleFields[manager]; !ok { // "Steal" the replicas path from the main resource entry newSet := versionedSet.Set().Difference(fieldpath.NewSet(path)) if !newSet.Empty() { newVersionedSet := fieldpath.NewVersionedSet( newSet, versionedSet.APIVersion(), versionedSet.Applied(), ) f[manager] = newVersionedSet t[manager] = decodedParentEntries.Times()[manager] } } else { // Field wasn't stolen, let's keep the entry as it is. f[manager] = versionedSet t[manager] = decodedParentEntries.Times()[manager] delete(scaleFields, manager) } } for manager, versionedSet := range scaleFields { if !versionedSet.Set().Has(replicasPathInScale) { continue } newVersionedSet := fieldpath.NewVersionedSet( fieldpath.NewSet(h.mappings[h.groupVersion.String()]), fieldpath.APIVersion(h.groupVersion.String()), versionedSet.Applied(), ) f[manager] = newVersionedSet t[manager] = decodedParentEntries.Times()[manager] } return managedFieldsEntries(internal.NewManaged(f, t)) } func managedFieldsEntries(entries internal.ManagedInterface) ([]metav1.ManagedFieldsEntry, error) { obj := &unstructured.Unstructured{Object: map[string]interface{}{}} if err := internal.EncodeObjectManagedFields(obj, entries); err != nil { return nil, err } accessor, err := meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } return accessor.GetManagedFields(), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/fieldmanager.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/fieldmanager.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 managedfields import ( "fmt" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/managedfields/internal" ) // FieldManager updates the managed fields and merges applied // configurations. type FieldManager = internal.FieldManager // NewDefaultFieldManager creates a new FieldManager that merges apply requests // and update managed fields for other types of requests. func NewDefaultFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]fieldpath.Filter) (*FieldManager, error) { f, err := internal.NewStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields) if err != nil { return nil, fmt.Errorf("failed to create field manager: %v", err) } return internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil } // NewDefaultCRDFieldManager creates a new FieldManager specifically for // CRDs. This allows for the possibility of fields which are not defined // in models, as well as having no models defined at all. func NewDefaultCRDFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]fieldpath.Filter) (_ *FieldManager, err error) { f, err := internal.NewCRDStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields) if err != nil { return nil, fmt.Errorf("failed to create field manager: %v", err) } return internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil } func ValidateManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) error { _, err := internal.DecodeManagedFields(encodedManagedFields) return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/extract.go
/* 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 managedfields import ( "bytes" "fmt" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/typed" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // ExtractInto extracts the applied configuration state from object for fieldManager // into applyConfiguration. If no managed fields are found for the given fieldManager, // no error is returned, but applyConfiguration is left unpopulated. It is possible // that no managed fields were found for the fieldManager because other field managers // have taken ownership of all the fields previously owned by the fieldManager. It is // also possible the fieldManager never owned fields. // // The provided object MUST bo a root resource object since subresource objects // do not contain their own managed fields. For example, an autoscaling.Scale // object read from a "scale" subresource does not have any managed fields and so // cannot be used as the object. // // If the fields of a subresource are a subset of the fields of the root object, // and their field paths and types are exactly the same, then ExtractInto can be // called with the root resource as the object and the subresource as the // applyConfiguration. This works for "status", obviously, because status is // represented by the exact same object as the root resource. This does NOT // work, for example, with the "scale" subresources of Deployment, ReplicaSet and // StatefulSet. While the spec.replicas, status.replicas fields are in the same // exact field path locations as they are in autoscaling.Scale, the selector // fields are in different locations, and are a different type. func ExtractInto(object runtime.Object, objectType typed.ParseableType, fieldManager string, applyConfiguration interface{}, subresource string) error { typedObj, err := toTyped(object, objectType) if err != nil { return fmt.Errorf("error converting obj to typed: %w", err) } accessor, err := meta.Accessor(object) if err != nil { return fmt.Errorf("error accessing metadata: %w", err) } fieldsEntry, ok := findManagedFields(accessor, fieldManager, subresource) if !ok { return nil } fieldset := &fieldpath.Set{} err = fieldset.FromJSON(bytes.NewReader(fieldsEntry.FieldsV1.Raw)) if err != nil { return fmt.Errorf("error marshalling FieldsV1 to JSON: %w", err) } u := typedObj.ExtractItems(fieldset.Leaves()).AsValue().Unstructured() m, ok := u.(map[string]interface{}) if !ok { return fmt.Errorf("unable to convert managed fields for %s to unstructured, expected map, got %T", fieldManager, u) } // set the type meta manually if it doesn't exist to avoid missing kind errors // when decoding from unstructured JSON if _, ok := m["kind"]; !ok && object.GetObjectKind().GroupVersionKind().Kind != "" { m["kind"] = object.GetObjectKind().GroupVersionKind().Kind m["apiVersion"] = object.GetObjectKind().GroupVersionKind().GroupVersion().String() } if err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, applyConfiguration); err != nil { return fmt.Errorf("error extracting into obj from unstructured: %w", err) } return nil } func findManagedFields(accessor metav1.Object, fieldManager string, subresource string) (metav1.ManagedFieldsEntry, bool) { objManagedFields := accessor.GetManagedFields() for _, mf := range objManagedFields { if mf.Manager == fieldManager && mf.Operation == metav1.ManagedFieldsOperationApply && mf.Subresource == subresource { return mf, true } } return metav1.ManagedFieldsEntry{}, false } func toTyped(obj runtime.Object, objectType typed.ParseableType) (*typed.TypedValue, error) { switch o := obj.(type) { case *unstructured.Unstructured: return objectType.FromUnstructured(o.Object) default: return objectType.FromStructured(o) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/typeconverter.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/typeconverter.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 managedfields import ( "k8s.io/apimachinery/pkg/util/managedfields/internal" "k8s.io/kube-openapi/pkg/validation/spec" ) // TypeConverter allows you to convert from runtime.Object to // typed.TypedValue and the other way around. type TypeConverter = internal.TypeConverter // NewDeducedTypeConverter creates a TypeConverter for CRDs that don't // have a schema. It does implement the same interface though (and // create the same types of objects), so that everything can still work // the same. CRDs are merged with all their fields being "atomic" (lists // included). func NewDeducedTypeConverter() TypeConverter { return internal.NewDeducedTypeConverter() } // NewTypeConverter builds a TypeConverter from a map of OpenAPIV3 schemas. // This will automatically find the proper version of the object, and the // corresponding schema information. // The keys to the map must be consistent with the names // used by Refs within the schemas. // The schemas should conform to the Kubernetes Structural Schema OpenAPI // restrictions found in docs: // https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) { return internal.NewTypeConverter(openapiSpec, preserveUnknownFields) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 managedfields import ( "fmt" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/kube-openapi/pkg/schemaconv" "k8s.io/kube-openapi/pkg/util/proto" smdschema "sigs.k8s.io/structured-merge-diff/v4/schema" "sigs.k8s.io/structured-merge-diff/v4/typed" ) // groupVersionKindExtensionKey is the key used to lookup the // GroupVersionKind value for an object definition from the // definition's "extensions" map. const groupVersionKindExtensionKey = "x-kubernetes-group-version-kind" // GvkParser contains a Parser that allows introspecting the schema. type GvkParser struct { gvks map[schema.GroupVersionKind]string parser typed.Parser } // Type returns a helper which can produce objects of the given type. Any // errors are deferred until a further function is called. func (p *GvkParser) Type(gvk schema.GroupVersionKind) *typed.ParseableType { typeName, ok := p.gvks[gvk] if !ok { return nil } t := p.parser.Type(typeName) return &t } // NewGVKParser builds a GVKParser from a proto.Models. This // will automatically find the proper version of the object, and the // corresponding schema information. func NewGVKParser(models proto.Models, preserveUnknownFields bool) (*GvkParser, error) { typeSchema, err := schemaconv.ToSchemaWithPreserveUnknownFields(models, preserveUnknownFields) if err != nil { return nil, fmt.Errorf("failed to convert models to schema: %v", err) } parser := GvkParser{ gvks: map[schema.GroupVersionKind]string{}, } parser.parser = typed.Parser{Schema: smdschema.Schema{Types: typeSchema.Types}} for _, modelName := range models.ListModels() { model := models.LookupModel(modelName) if model == nil { panic(fmt.Sprintf("ListModels returns a model that can't be looked-up for: %v", modelName)) } gvkList := parseGroupVersionKind(model) for _, gvk := range gvkList { if len(gvk.Kind) > 0 { _, ok := parser.gvks[gvk] if ok { return nil, fmt.Errorf("duplicate entry for %v", gvk) } parser.gvks[gvk] = modelName } } } return &parser, nil } // Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one. func parseGroupVersionKind(s proto.Schema) []schema.GroupVersionKind { extensions := s.GetExtensions() gvkListResult := []schema.GroupVersionKind{} // Get the extensions gvkExtension, ok := extensions[groupVersionKindExtensionKey] if !ok { return []schema.GroupVersionKind{} } // gvk extension must be a list of at least 1 element. gvkList, ok := gvkExtension.([]interface{}) if !ok { return []schema.GroupVersionKind{} } for _, gvk := range gvkList { // gvk extension list must be a map with group, version, and // kind fields gvkMap, ok := gvk.(map[interface{}]interface{}) if !ok { continue } group, ok := gvkMap["group"].(string) if !ok { continue } version, ok := gvkMap["version"].(string) if !ok { continue } kind, ok := gvkMap["kind"].(string) if !ok { continue } gvkListResult = append(gvkListResult, schema.GroupVersionKind{ Group: group, Version: version, Kind: kind, }) } return gvkListResult }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/conflict.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/conflict.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "encoding/json" "fmt" "sort" "strings" "time" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/merge" ) // NewConflictError returns an error including details on the requests apply conflicts func NewConflictError(conflicts merge.Conflicts) *errors.StatusError { causes := []metav1.StatusCause{} for _, conflict := range conflicts { causes = append(causes, metav1.StatusCause{ Type: metav1.CauseTypeFieldManagerConflict, Message: fmt.Sprintf("conflict with %v", printManager(conflict.Manager)), Field: conflict.Path.String(), }) } return errors.NewApplyConflict(causes, getConflictMessage(conflicts)) } func getConflictMessage(conflicts merge.Conflicts) string { if len(conflicts) == 1 { return fmt.Sprintf("Apply failed with 1 conflict: conflict with %v: %v", printManager(conflicts[0].Manager), conflicts[0].Path) } m := map[string][]fieldpath.Path{} for _, conflict := range conflicts { m[conflict.Manager] = append(m[conflict.Manager], conflict.Path) } uniqueManagers := []string{} for manager := range m { uniqueManagers = append(uniqueManagers, manager) } // Print conflicts by sorted managers. sort.Strings(uniqueManagers) messages := []string{} for _, manager := range uniqueManagers { messages = append(messages, fmt.Sprintf("conflicts with %v:", printManager(manager))) for _, path := range m[manager] { messages = append(messages, fmt.Sprintf("- %v", path)) } } return fmt.Sprintf("Apply failed with %d conflicts: %s", len(conflicts), strings.Join(messages, "\n")) } func printManager(manager string) string { encodedManager := &metav1.ManagedFieldsEntry{} if err := json.Unmarshal([]byte(manager), encodedManager); err != nil { return fmt.Sprintf("%q", manager) } managerStr := fmt.Sprintf("%q", encodedManager.Manager) if encodedManager.Subresource != "" { managerStr = fmt.Sprintf("%s with subresource %q", managerStr, encodedManager.Subresource) } if encodedManager.Operation == metav1.ManagedFieldsOperationUpdate { if encodedManager.Time == nil { return fmt.Sprintf("%s using %v", managerStr, encodedManager.APIVersion) } return fmt.Sprintf("%s using %v at %v", managerStr, encodedManager.APIVersion, encodedManager.Time.UTC().Format(time.RFC3339)) } return managerStr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) type lastAppliedUpdater struct { fieldManager Manager } var _ Manager = &lastAppliedUpdater{} // NewLastAppliedUpdater sets the client-side apply annotation up to date with // server-side apply managed fields func NewLastAppliedUpdater(fieldManager Manager) Manager { return &lastAppliedUpdater{ fieldManager: fieldManager, } } // Update implements Manager. func (f *lastAppliedUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { return f.fieldManager.Update(liveObj, newObj, managed, manager) } // server-side apply managed fields func (f *lastAppliedUpdater) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { liveObj, managed, err := f.fieldManager.Apply(liveObj, newObj, managed, manager, force) if err != nil { return liveObj, managed, err } // Sync the client-side apply annotation only from kubectl server-side apply. // To opt-out of this behavior, users may specify a different field manager. // // If the client-side apply annotation doesn't exist, // then continue because we have no annotation to update if manager == "kubectl" && hasLastApplied(liveObj) { lastAppliedValue, err := buildLastApplied(newObj) if err != nil { return nil, nil, fmt.Errorf("failed to build last-applied annotation: %v", err) } err = SetLastApplied(liveObj, lastAppliedValue) if err != nil { return nil, nil, fmt.Errorf("failed to set last-applied annotation: %v", err) } } return liveObj, managed, err } func hasLastApplied(obj runtime.Object) bool { var accessor, err = meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } var annotations = accessor.GetAnnotations() if annotations == nil { return false } lastApplied, ok := annotations[LastAppliedConfigAnnotation] return ok && len(lastApplied) > 0 } func buildLastApplied(obj runtime.Object) (string, error) { obj = obj.DeepCopyObject() var accessor, err = meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } // Remove the annotation from the object before encoding the object var annotations = accessor.GetAnnotations() delete(annotations, LastAppliedConfigAnnotation) accessor.SetAnnotations(annotations) lastApplied, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj) if err != nil { return "", fmt.Errorf("couldn't encode object into last applied annotation: %v", err) } return string(lastApplied), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 internal import ( "encoding/json" "fmt" "sort" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) // ManagedInterface groups a fieldpath.ManagedFields together with the timestamps associated with each operation. type ManagedInterface interface { // Fields gets the fieldpath.ManagedFields. Fields() fieldpath.ManagedFields // Times gets the timestamps associated with each operation. Times() map[string]*metav1.Time } type managedStruct struct { fields fieldpath.ManagedFields times map[string]*metav1.Time } var _ ManagedInterface = &managedStruct{} // Fields implements ManagedInterface. func (m *managedStruct) Fields() fieldpath.ManagedFields { return m.fields } // Times implements ManagedInterface. func (m *managedStruct) Times() map[string]*metav1.Time { return m.times } // NewEmptyManaged creates an empty ManagedInterface. func NewEmptyManaged() ManagedInterface { return NewManaged(fieldpath.ManagedFields{}, map[string]*metav1.Time{}) } // NewManaged creates a ManagedInterface from a fieldpath.ManagedFields and the timestamps associated with each operation. func NewManaged(f fieldpath.ManagedFields, t map[string]*metav1.Time) ManagedInterface { return &managedStruct{ fields: f, times: t, } } // RemoveObjectManagedFields removes the ManagedFields from the object // before we merge so that it doesn't appear in the ManagedFields // recursively. func RemoveObjectManagedFields(obj runtime.Object) { accessor, err := meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } accessor.SetManagedFields(nil) } // EncodeObjectManagedFields converts and stores the fieldpathManagedFields into the objects ManagedFields func EncodeObjectManagedFields(obj runtime.Object, managed ManagedInterface) error { accessor, err := meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } encodedManagedFields, err := encodeManagedFields(managed) if err != nil { return fmt.Errorf("failed to convert back managed fields to API: %v", err) } accessor.SetManagedFields(encodedManagedFields) return nil } // DecodeManagedFields converts ManagedFields from the wire format (api format) // to the format used by sigs.k8s.io/structured-merge-diff func DecodeManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (ManagedInterface, error) { managed := managedStruct{} managed.fields = make(fieldpath.ManagedFields, len(encodedManagedFields)) managed.times = make(map[string]*metav1.Time, len(encodedManagedFields)) for i, encodedVersionedSet := range encodedManagedFields { switch encodedVersionedSet.Operation { case metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate: default: return nil, fmt.Errorf("operation must be `Apply` or `Update`") } if len(encodedVersionedSet.APIVersion) < 1 { return nil, fmt.Errorf("apiVersion must not be empty") } switch encodedVersionedSet.FieldsType { case "FieldsV1": // Valid case. case "": return nil, fmt.Errorf("missing fieldsType in managed fields entry %d", i) default: return nil, fmt.Errorf("invalid fieldsType %q in managed fields entry %d", encodedVersionedSet.FieldsType, i) } manager, err := BuildManagerIdentifier(&encodedVersionedSet) if err != nil { return nil, fmt.Errorf("error decoding manager from %v: %v", encodedVersionedSet, err) } managed.fields[manager], err = decodeVersionedSet(&encodedVersionedSet) if err != nil { return nil, fmt.Errorf("error decoding versioned set from %v: %v", encodedVersionedSet, err) } managed.times[manager] = encodedVersionedSet.Time } return &managed, nil } // BuildManagerIdentifier creates a manager identifier string from a ManagedFieldsEntry func BuildManagerIdentifier(encodedManager *metav1.ManagedFieldsEntry) (manager string, err error) { encodedManagerCopy := *encodedManager // Never include fields type in the manager identifier encodedManagerCopy.FieldsType = "" // Never include the fields in the manager identifier encodedManagerCopy.FieldsV1 = nil // Never include the time in the manager identifier encodedManagerCopy.Time = nil // For appliers, don't include the APIVersion in the manager identifier, // so it will always have the same manager identifier each time it applied. if encodedManager.Operation == metav1.ManagedFieldsOperationApply { encodedManagerCopy.APIVersion = "" } // Use the remaining fields to build the manager identifier b, err := json.Marshal(&encodedManagerCopy) if err != nil { return "", fmt.Errorf("error marshalling manager identifier: %v", err) } return string(b), nil } func decodeVersionedSet(encodedVersionedSet *metav1.ManagedFieldsEntry) (versionedSet fieldpath.VersionedSet, err error) { fields := EmptyFields if encodedVersionedSet.FieldsV1 != nil { fields = *encodedVersionedSet.FieldsV1 } set, err := FieldsToSet(fields) if err != nil { return nil, fmt.Errorf("error decoding set: %v", err) } return fieldpath.NewVersionedSet(&set, fieldpath.APIVersion(encodedVersionedSet.APIVersion), encodedVersionedSet.Operation == metav1.ManagedFieldsOperationApply), nil } // encodeManagedFields converts ManagedFields from the format used by // sigs.k8s.io/structured-merge-diff to the wire format (api format) func encodeManagedFields(managed ManagedInterface) (encodedManagedFields []metav1.ManagedFieldsEntry, err error) { if len(managed.Fields()) == 0 { return nil, nil } encodedManagedFields = []metav1.ManagedFieldsEntry{} for manager := range managed.Fields() { versionedSet := managed.Fields()[manager] v, err := encodeManagerVersionedSet(manager, versionedSet) if err != nil { return nil, fmt.Errorf("error encoding versioned set for %v: %v", manager, err) } if t, ok := managed.Times()[manager]; ok { v.Time = t } encodedManagedFields = append(encodedManagedFields, *v) } return sortEncodedManagedFields(encodedManagedFields) } func sortEncodedManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (sortedManagedFields []metav1.ManagedFieldsEntry, err error) { sort.Slice(encodedManagedFields, func(i, j int) bool { p, q := encodedManagedFields[i], encodedManagedFields[j] if p.Operation != q.Operation { return p.Operation < q.Operation } pSeconds, qSeconds := int64(0), int64(0) if p.Time != nil { pSeconds = p.Time.Unix() } if q.Time != nil { qSeconds = q.Time.Unix() } if pSeconds != qSeconds { return pSeconds < qSeconds } if p.Manager != q.Manager { return p.Manager < q.Manager } if p.APIVersion != q.APIVersion { return p.APIVersion < q.APIVersion } return p.Subresource < q.Subresource }) return encodedManagedFields, nil } func encodeManagerVersionedSet(manager string, versionedSet fieldpath.VersionedSet) (encodedVersionedSet *metav1.ManagedFieldsEntry, err error) { encodedVersionedSet = &metav1.ManagedFieldsEntry{} // Get as many fields as we can from the manager identifier err = json.Unmarshal([]byte(manager), encodedVersionedSet) if err != nil { return nil, fmt.Errorf("error unmarshalling manager identifier %v: %v", manager, err) } // Get the APIVersion, Operation, and Fields from the VersionedSet encodedVersionedSet.APIVersion = string(versionedSet.APIVersion()) if versionedSet.Applied() { encodedVersionedSet.Operation = metav1.ManagedFieldsOperationApply } encodedVersionedSet.FieldsType = "FieldsV1" fields, err := SetToFields(*versionedSet.Set()) if err != nil { return nil, fmt.Errorf("error encoding set: %v", err) } encodedVersionedSet.FieldsV1 = &fields return encodedVersionedSet, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) type stripMetaManager struct { fieldManager Manager // stripSet is the list of fields that should never be part of a mangedFields. stripSet *fieldpath.Set } var _ Manager = &stripMetaManager{} // NewStripMetaManager creates a new Manager that strips metadata and typemeta fields from the manager's fieldset. func NewStripMetaManager(fieldManager Manager) Manager { return &stripMetaManager{ fieldManager: fieldManager, stripSet: fieldpath.NewSet( fieldpath.MakePathOrDie("apiVersion"), fieldpath.MakePathOrDie("kind"), fieldpath.MakePathOrDie("metadata"), fieldpath.MakePathOrDie("metadata", "name"), fieldpath.MakePathOrDie("metadata", "namespace"), fieldpath.MakePathOrDie("metadata", "creationTimestamp"), fieldpath.MakePathOrDie("metadata", "selfLink"), fieldpath.MakePathOrDie("metadata", "uid"), fieldpath.MakePathOrDie("metadata", "clusterName"), fieldpath.MakePathOrDie("metadata", "generation"), fieldpath.MakePathOrDie("metadata", "managedFields"), fieldpath.MakePathOrDie("metadata", "resourceVersion"), ), } } // Update implements Manager. func (f *stripMetaManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { newObj, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager) if err != nil { return nil, nil, err } f.stripFields(managed.Fields(), manager) return newObj, managed, nil } // Apply implements Manager. func (f *stripMetaManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { newObj, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) if err != nil { return nil, nil, err } f.stripFields(managed.Fields(), manager) return newObj, managed, nil } // stripFields removes a predefined set of paths found in typed from managed func (f *stripMetaManager) stripFields(managed fieldpath.ManagedFields, manager string) { vs, ok := managed[manager] if ok { if vs == nil { panic(fmt.Sprintf("Found unexpected nil manager which should never happen: %s", manager)) } newSet := vs.Set().Difference(f.stripSet) if newSet.Empty() { delete(managed, manager) } else { managed[manager] = fieldpath.NewVersionedSet(newSet, vs.APIVersion(), vs.Applied()) } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/pathelement.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/pathelement.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 internal import ( "encoding/json" "errors" "fmt" "strconv" "strings" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/value" ) const ( // Field indicates that the content of this path element is a field's name Field = "f" // Value indicates that the content of this path element is a field's value Value = "v" // Index indicates that the content of this path element is an index in an array Index = "i" // Key indicates that the content of this path element is a key value map Key = "k" // Separator separates the type of a path element from the contents Separator = ":" ) // NewPathElement parses a serialized path element func NewPathElement(s string) (fieldpath.PathElement, error) { split := strings.SplitN(s, Separator, 2) if len(split) < 2 { return fieldpath.PathElement{}, fmt.Errorf("missing colon: %v", s) } switch split[0] { case Field: return fieldpath.PathElement{ FieldName: &split[1], }, nil case Value: val, err := value.FromJSON([]byte(split[1])) if err != nil { return fieldpath.PathElement{}, err } return fieldpath.PathElement{ Value: &val, }, nil case Index: i, err := strconv.Atoi(split[1]) if err != nil { return fieldpath.PathElement{}, err } return fieldpath.PathElement{ Index: &i, }, nil case Key: kv := map[string]json.RawMessage{} err := json.Unmarshal([]byte(split[1]), &kv) if err != nil { return fieldpath.PathElement{}, err } fields := value.FieldList{} for k, v := range kv { b, err := json.Marshal(v) if err != nil { return fieldpath.PathElement{}, err } val, err := value.FromJSON(b) if err != nil { return fieldpath.PathElement{}, err } fields = append(fields, value.Field{ Name: k, Value: val, }) } return fieldpath.PathElement{ Key: &fields, }, nil default: // Ignore unknown key types return fieldpath.PathElement{}, nil } } // PathElementString serializes a path element func PathElementString(pe fieldpath.PathElement) (string, error) { switch { case pe.FieldName != nil: return Field + Separator + *pe.FieldName, nil case pe.Key != nil: kv := map[string]json.RawMessage{} for _, k := range *pe.Key { b, err := value.ToJSON(k.Value) if err != nil { return "", err } m := json.RawMessage{} err = json.Unmarshal(b, &m) if err != nil { return "", err } kv[k.Name] = m } b, err := json.Marshal(kv) if err != nil { return "", err } return Key + ":" + string(b), nil case pe.Value != nil: b, err := value.ToJSON(*pe.Value) if err != nil { return "", err } return Value + ":" + string(b), nil case pe.Index != nil: return Index + ":" + strconv.Itoa(*pe.Index), nil default: return "", errors.New("Invalid type of path element") } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 internal import ( "fmt" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/merge" "sigs.k8s.io/structured-merge-diff/v4/typed" ) // versionConverter is an implementation of // sigs.k8s.io/structured-merge-diff/merge.Converter type versionConverter struct { typeConverter TypeConverter objectConvertor runtime.ObjectConvertor hubGetter func(from schema.GroupVersion) schema.GroupVersion } var _ merge.Converter = &versionConverter{} // NewVersionConverter builds a VersionConverter from a TypeConverter and an ObjectConvertor. func newVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter { return &versionConverter{ typeConverter: t, objectConvertor: o, hubGetter: func(from schema.GroupVersion) schema.GroupVersion { return schema.GroupVersion{ Group: from.Group, Version: h.Version, } }, } } // NewCRDVersionConverter builds a VersionConverter for CRDs from a TypeConverter and an ObjectConvertor. func newCRDVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter { return &versionConverter{ typeConverter: t, objectConvertor: o, hubGetter: func(from schema.GroupVersion) schema.GroupVersion { return h }, } } // Convert implements sigs.k8s.io/structured-merge-diff/merge.Converter func (v *versionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) { // Convert the smd typed value to a kubernetes object. objectToConvert, err := v.typeConverter.TypedToObject(object) if err != nil { return object, err } // Parse the target groupVersion. groupVersion, err := schema.ParseGroupVersion(string(version)) if err != nil { return object, err } // If attempting to convert to the same version as we already have, just return it. fromVersion := objectToConvert.GetObjectKind().GroupVersionKind().GroupVersion() if fromVersion == groupVersion { return object, nil } // Convert to internal internalObject, err := v.objectConvertor.ConvertToVersion(objectToConvert, v.hubGetter(fromVersion)) if err != nil { return object, err } // Convert the object into the target version convertedObject, err := v.objectConvertor.ConvertToVersion(internalObject, groupVersion) if err != nil { return object, err } // Convert the object back to a smd typed value and return it. return v.typeConverter.ObjectToTyped(convertedObject) } // IsMissingVersionError func (v *versionConverter) IsMissingVersionError(err error) bool { return runtime.IsNotRegisteredError(err) || isNoCorrespondingTypeError(err) } type noCorrespondingTypeErr struct { gvk schema.GroupVersionKind } func NewNoCorrespondingTypeError(gvk schema.GroupVersionKind) error { return &noCorrespondingTypeErr{gvk: gvk} } func (k *noCorrespondingTypeErr) Error() string { return fmt.Sprintf("no corresponding type for %v", k.gvk) } func isNoCorrespondingTypeError(err error) bool { if err == nil { return false } _, ok := err.(*noCorrespondingTypeErr) return ok }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" "math/rand" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" ) type skipNonAppliedManager struct { fieldManager Manager objectCreater runtime.ObjectCreater beforeApplyManagerName string probability float32 } var _ Manager = &skipNonAppliedManager{} // NewSkipNonAppliedManager creates a new wrapped FieldManager that only starts tracking managers after the first apply. func NewSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater) Manager { return NewProbabilisticSkipNonAppliedManager(fieldManager, objectCreater, 0.0) } // NewProbabilisticSkipNonAppliedManager creates a new wrapped FieldManager that starts tracking managers after the first apply, // or starts tracking on create with p probability. func NewProbabilisticSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, p float32) Manager { return &skipNonAppliedManager{ fieldManager: fieldManager, objectCreater: objectCreater, beforeApplyManagerName: "before-first-apply", probability: p, } } // Update implements Manager. func (f *skipNonAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { accessor, err := meta.Accessor(liveObj) if err != nil { return newObj, managed, nil } // If managed fields is empty, we need to determine whether to skip tracking managed fields. if len(managed.Fields()) == 0 { // Check if the operation is a create, by checking whether lastObj's UID is empty. // If the operation is create, P(tracking managed fields) = f.probability // If the operation is update, skip tracking managed fields, since we already know managed fields is empty. if len(accessor.GetUID()) == 0 { if f.probability <= rand.Float32() { return newObj, managed, nil } } else { return newObj, managed, nil } } return f.fieldManager.Update(liveObj, newObj, managed, manager) } // Apply implements Manager. func (f *skipNonAppliedManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { if len(managed.Fields()) == 0 { gvk := appliedObj.GetObjectKind().GroupVersionKind() emptyObj, err := f.objectCreater.New(gvk) if err != nil { return nil, nil, fmt.Errorf("failed to create empty object of type %v: %v", gvk, err) } liveObj, managed, err = f.fieldManager.Update(emptyObj, liveObj, managed, f.beforeApplyManagerName) if err != nil { return nil, nil, fmt.Errorf("failed to create manager for existing fields: %v", err) } } return f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) type buildManagerInfoManager struct { fieldManager Manager groupVersion schema.GroupVersion subresource string } var _ Manager = &buildManagerInfoManager{} // NewBuildManagerInfoManager creates a new Manager that converts the manager name into a unique identifier // combining operation and version for update requests, and just operation for apply requests. func NewBuildManagerInfoManager(f Manager, gv schema.GroupVersion, subresource string) Manager { return &buildManagerInfoManager{ fieldManager: f, groupVersion: gv, subresource: subresource, } } // Update implements Manager. func (f *buildManagerInfoManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { manager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationUpdate) if err != nil { return nil, nil, fmt.Errorf("failed to build manager identifier: %v", err) } return f.fieldManager.Update(liveObj, newObj, managed, manager) } // Apply implements Manager. func (f *buildManagerInfoManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { manager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationApply) if err != nil { return nil, nil, fmt.Errorf("failed to build manager identifier: %v", err) } return f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) } func (f *buildManagerInfoManager) buildManagerInfo(prefix string, operation metav1.ManagedFieldsOperationType) (string, error) { managerInfo := metav1.ManagedFieldsEntry{ Manager: prefix, Operation: operation, APIVersion: f.groupVersion.String(), Subresource: f.subresource, } if managerInfo.Manager == "" { managerInfo.Manager = "unknown" } return BuildManagerIdentifier(&managerInfo) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "encoding/json" "fmt" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/merge" ) type lastAppliedManager struct { fieldManager Manager typeConverter TypeConverter objectConverter runtime.ObjectConvertor groupVersion schema.GroupVersion } var _ Manager = &lastAppliedManager{} // NewLastAppliedManager converts the client-side apply annotation to // server-side apply managed fields func NewLastAppliedManager(fieldManager Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, groupVersion schema.GroupVersion) Manager { return &lastAppliedManager{ fieldManager: fieldManager, typeConverter: typeConverter, objectConverter: objectConverter, groupVersion: groupVersion, } } // Update implements Manager. func (f *lastAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { return f.fieldManager.Update(liveObj, newObj, managed, manager) } // Apply will consider the last-applied annotation // for upgrading an object managed by client-side apply to server-side apply // without conflicts. func (f *lastAppliedManager) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { newLiveObj, newManaged, newErr := f.fieldManager.Apply(liveObj, newObj, managed, manager, force) // Upgrade the client-side apply annotation only from kubectl server-side-apply. // To opt-out of this behavior, users may specify a different field manager. if manager != "kubectl" { return newLiveObj, newManaged, newErr } // Check if we have conflicts if newErr == nil { return newLiveObj, newManaged, newErr } conflicts, ok := newErr.(merge.Conflicts) if !ok { return newLiveObj, newManaged, newErr } conflictSet := conflictsToSet(conflicts) // Check if conflicts are allowed due to client-side apply, // and if so, then force apply allowedConflictSet, err := f.allowedConflictsFromLastApplied(liveObj) if err != nil { return newLiveObj, newManaged, newErr } if !conflictSet.Difference(allowedConflictSet).Empty() { newConflicts := conflictsDifference(conflicts, allowedConflictSet) return newLiveObj, newManaged, newConflicts } return f.fieldManager.Apply(liveObj, newObj, managed, manager, true) } func (f *lastAppliedManager) allowedConflictsFromLastApplied(liveObj runtime.Object) (*fieldpath.Set, error) { var accessor, err = meta.Accessor(liveObj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } // If there is no client-side apply annotation, then there is nothing to do var annotations = accessor.GetAnnotations() if annotations == nil { return nil, fmt.Errorf("no last applied annotation") } var lastApplied, ok = annotations[LastAppliedConfigAnnotation] if !ok || lastApplied == "" { return nil, fmt.Errorf("no last applied annotation") } liveObjVersioned, err := f.objectConverter.ConvertToVersion(liveObj, f.groupVersion) if err != nil { return nil, fmt.Errorf("failed to convert live obj to versioned: %v", err) } liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned) if err != nil { return nil, fmt.Errorf("failed to convert live obj to typed: %v", err) } var lastAppliedObj = &unstructured.Unstructured{Object: map[string]interface{}{}} err = json.Unmarshal([]byte(lastApplied), lastAppliedObj) if err != nil { return nil, fmt.Errorf("failed to decode last applied obj: %v in '%s'", err, lastApplied) } if lastAppliedObj.GetAPIVersion() != f.groupVersion.String() { return nil, fmt.Errorf("expected version of last applied to match live object '%s', but got '%s': %v", f.groupVersion.String(), lastAppliedObj.GetAPIVersion(), err) } lastAppliedObjTyped, err := f.typeConverter.ObjectToTyped(lastAppliedObj) if err != nil { return nil, fmt.Errorf("failed to convert last applied to typed: %v", err) } lastAppliedObjFieldSet, err := lastAppliedObjTyped.ToFieldSet() if err != nil { return nil, fmt.Errorf("failed to create fieldset for last applied object: %v", err) } comparison, err := lastAppliedObjTyped.Compare(liveObjTyped) if err != nil { return nil, fmt.Errorf("failed to compare last applied object and live object: %v", err) } // Remove fields in last applied that are different, added, or missing in // the live object. // Because last-applied fields don't match the live object fields, // then we don't own these fields. lastAppliedObjFieldSet = lastAppliedObjFieldSet. Difference(comparison.Modified). Difference(comparison.Added). Difference(comparison.Removed) return lastAppliedObjFieldSet, nil } // TODO: replace with merge.Conflicts.ToSet() func conflictsToSet(conflicts merge.Conflicts) *fieldpath.Set { conflictSet := fieldpath.NewSet() for _, conflict := range []merge.Conflict(conflicts) { conflictSet.Insert(conflict.Path) } return conflictSet } func conflictsDifference(conflicts merge.Conflicts, s *fieldpath.Set) merge.Conflicts { newConflicts := []merge.Conflict{} for _, conflict := range []merge.Conflict(conflicts) { if !s.Has(conflict.Path) { newConflicts = append(newConflicts, conflict) } } return newConflicts }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versioncheck.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/versioncheck.go
/* 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 internal import ( "fmt" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) type versionCheckManager struct { fieldManager Manager gvk schema.GroupVersionKind } var _ Manager = &versionCheckManager{} // NewVersionCheckManager creates a manager that makes sure that the // applied object is in the proper version. func NewVersionCheckManager(fieldManager Manager, gvk schema.GroupVersionKind) Manager { return &versionCheckManager{fieldManager: fieldManager, gvk: gvk} } // Update implements Manager. func (f *versionCheckManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { // Nothing to do for updates, this is checked in many other places. return f.fieldManager.Update(liveObj, newObj, managed, manager) } // Apply implements Manager. func (f *versionCheckManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { if gvk := appliedObj.GetObjectKind().GroupVersionKind(); gvk != f.gvk { return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid object type: %v", gvk)) } return f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" "sort" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) type capManagersManager struct { fieldManager Manager maxUpdateManagers int oldUpdatesManagerName string } var _ Manager = &capManagersManager{} // NewCapManagersManager creates a new wrapped FieldManager which ensures that the number of managers from updates // does not exceed maxUpdateManagers, by merging some of the oldest entries on each update. func NewCapManagersManager(fieldManager Manager, maxUpdateManagers int) Manager { return &capManagersManager{ fieldManager: fieldManager, maxUpdateManagers: maxUpdateManagers, oldUpdatesManagerName: "ancient-changes", } } // Update implements Manager. func (f *capManagersManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { object, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager) if err != nil { return object, managed, err } if managed, err = f.capUpdateManagers(managed); err != nil { return nil, nil, fmt.Errorf("failed to cap update managers: %v", err) } return object, managed, nil } // Apply implements Manager. func (f *capManagersManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { return f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) } // capUpdateManagers merges a number of the oldest update entries into versioned buckets, // such that the number of entries from updates does not exceed f.maxUpdateManagers. func (f *capManagersManager) capUpdateManagers(managed Managed) (newManaged Managed, err error) { // Gather all entries from updates updaters := []string{} for manager, fields := range managed.Fields() { if !fields.Applied() { updaters = append(updaters, manager) } } if len(updaters) <= f.maxUpdateManagers { return managed, nil } // If we have more than the maximum, sort the update entries by time, oldest first. sort.Slice(updaters, func(i, j int) bool { iTime, jTime, iSeconds, jSeconds := managed.Times()[updaters[i]], managed.Times()[updaters[j]], int64(0), int64(0) if iTime != nil { iSeconds = iTime.Unix() } if jTime != nil { jSeconds = jTime.Unix() } if iSeconds != jSeconds { return iSeconds < jSeconds } return updaters[i] < updaters[j] }) // Merge the oldest updaters with versioned bucket managers until the number of updaters is under the cap versionToFirstManager := map[string]string{} for i, length := 0, len(updaters); i < len(updaters) && length > f.maxUpdateManagers; i++ { manager := updaters[i] vs := managed.Fields()[manager] time := managed.Times()[manager] version := string(vs.APIVersion()) // Create a new manager identifier for the versioned bucket entry. // The version for this manager comes from the version of the update being merged into the bucket. bucket, err := BuildManagerIdentifier(&metav1.ManagedFieldsEntry{ Manager: f.oldUpdatesManagerName, Operation: metav1.ManagedFieldsOperationUpdate, APIVersion: version, }) if err != nil { return managed, fmt.Errorf("failed to create bucket manager for version %v: %v", version, err) } // Merge the fieldets if this is not the first time the version was seen. // Otherwise just record the manager name in versionToFirstManager if first, ok := versionToFirstManager[version]; ok { // If the bucket doesn't exists yet, create one. if _, ok := managed.Fields()[bucket]; !ok { s := managed.Fields()[first] delete(managed.Fields(), first) managed.Fields()[bucket] = s } managed.Fields()[bucket] = fieldpath.NewVersionedSet(vs.Set().Union(managed.Fields()[bucket].Set()), vs.APIVersion(), vs.Applied()) delete(managed.Fields(), manager) length-- // Use the time from the update being merged into the bucket, since it is more recent. managed.Times()[bucket] = time } else { versionToFirstManager[version] = manager } } return managed, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go
/* 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 internal import ( "fmt" "reflect" "time" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/klog/v2" "sigs.k8s.io/structured-merge-diff/v4/merge" ) // DefaultMaxUpdateManagers defines the default maximum retained number of managedFields entries from updates // if the number of update managers exceeds this, the oldest entries will be merged until the number is below the maximum. // TODO(jennybuckley): Determine if this is really the best value. Ideally we wouldn't unnecessarily merge too many entries. const DefaultMaxUpdateManagers int = 10 // DefaultTrackOnCreateProbability defines the default probability that the field management of an object // starts being tracked from the object's creation, instead of from the first time the object is applied to. const DefaultTrackOnCreateProbability float32 = 1 var atMostEverySecond = NewAtMostEvery(time.Second) // FieldManager updates the managed fields and merges applied // configurations. type FieldManager struct { fieldManager Manager subresource string } // NewFieldManager creates a new FieldManager that decodes, manages, then re-encodes managedFields // on update and apply requests. func NewFieldManager(f Manager, subresource string) *FieldManager { return &FieldManager{fieldManager: f, subresource: subresource} } // newDefaultFieldManager is a helper function which wraps a Manager with certain default logic. func NewDefaultFieldManager(f Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, subresource string) *FieldManager { return NewFieldManager( NewVersionCheckManager( NewLastAppliedUpdater( NewLastAppliedManager( NewProbabilisticSkipNonAppliedManager( NewCapManagersManager( NewBuildManagerInfoManager( NewManagedFieldsUpdater( NewStripMetaManager(f), ), kind.GroupVersion(), subresource, ), DefaultMaxUpdateManagers, ), objectCreater, DefaultTrackOnCreateProbability, ), typeConverter, objectConverter, kind.GroupVersion(), ), ), kind, ), subresource, ) } func decodeLiveOrNew(liveObj, newObj runtime.Object, ignoreManagedFieldsFromRequestObject bool) (Managed, error) { liveAccessor, err := meta.Accessor(liveObj) if err != nil { return nil, err } // We take the managedFields of the live object in case the request tries to // manually set managedFields via a subresource. if ignoreManagedFieldsFromRequestObject { return emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields())) } // If the object doesn't have metadata, we should just return without trying to // set the managedFields at all, so creates/updates/patches will work normally. newAccessor, err := meta.Accessor(newObj) if err != nil { return nil, err } if isResetManagedFields(newAccessor.GetManagedFields()) { return NewEmptyManaged(), nil } // If the managed field is empty or we failed to decode it, // let's try the live object. This is to prevent clients who // don't understand managedFields from deleting it accidentally. managed, err := DecodeManagedFields(newAccessor.GetManagedFields()) if err != nil || len(managed.Fields()) == 0 { return emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields())) } return managed, nil } func emptyManagedFieldsOnErr(managed Managed, err error) (Managed, error) { if err != nil { return NewEmptyManaged(), nil } return managed, nil } // Update is used when the object has already been merged (non-apply // use-case), and simply updates the managed fields in the output // object. func (f *FieldManager) Update(liveObj, newObj runtime.Object, manager string) (object runtime.Object, err error) { // First try to decode the managed fields provided in the update, // This is necessary to allow directly updating managed fields. isSubresource := f.subresource != "" managed, err := decodeLiveOrNew(liveObj, newObj, isSubresource) if err != nil { return newObj, nil } RemoveObjectManagedFields(newObj) if object, managed, err = f.fieldManager.Update(liveObj, newObj, managed, manager); err != nil { return nil, err } if err = EncodeObjectManagedFields(object, managed); err != nil { return nil, fmt.Errorf("failed to encode managed fields: %v", err) } return object, nil } // UpdateNoErrors is the same as Update, but it will not return // errors. If an error happens, the object is returned with // managedFields cleared. func (f *FieldManager) UpdateNoErrors(liveObj, newObj runtime.Object, manager string) runtime.Object { obj, err := f.Update(liveObj, newObj, manager) if err != nil { atMostEverySecond.Do(func() { ns, name := "unknown", "unknown" if accessor, err := meta.Accessor(newObj); err == nil { ns = accessor.GetNamespace() name = accessor.GetName() } klog.ErrorS(err, "[SHOULD NOT HAPPEN] failed to update managedFields", "versionKind", newObj.GetObjectKind().GroupVersionKind(), "namespace", ns, "name", name) }) // Explicitly remove managedFields on failure, so that // we can't have garbage in it. RemoveObjectManagedFields(newObj) return newObj } return obj } // Returns true if the managedFields indicate that the user is trying to // reset the managedFields, i.e. if the list is non-nil but empty, or if // the list has one empty item. func isResetManagedFields(managedFields []metav1.ManagedFieldsEntry) bool { if len(managedFields) == 0 { return managedFields != nil } if len(managedFields) == 1 { return reflect.DeepEqual(managedFields[0], metav1.ManagedFieldsEntry{}) } return false } // Apply is used when server-side apply is called, as it merges the // object and updates the managed fields. func (f *FieldManager) Apply(liveObj, appliedObj runtime.Object, manager string, force bool) (object runtime.Object, err error) { // If the object doesn't have metadata, apply isn't allowed. accessor, err := meta.Accessor(liveObj) if err != nil { return nil, fmt.Errorf("couldn't get accessor: %v", err) } // Decode the managed fields in the live object, since it isn't allowed in the patch. managed, err := DecodeManagedFields(accessor.GetManagedFields()) if err != nil { return nil, fmt.Errorf("failed to decode managed fields: %v", err) } object, managed, err = f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) if err != nil { if conflicts, ok := err.(merge.Conflicts); ok { return nil, NewConflictError(conflicts) } return nil, err } if err = EncodeObjectManagedFields(object, managed); err != nil { return nil, fmt.Errorf("failed to encode managed fields: %v", err) } return object, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/atmostevery.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/atmostevery.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "sync" "time" ) // AtMostEvery will never run the method more than once every specified // duration. type AtMostEvery struct { delay time.Duration lastCall time.Time mutex sync.Mutex } // NewAtMostEvery creates a new AtMostEvery, that will run the method at // most every given duration. func NewAtMostEvery(delay time.Duration) *AtMostEvery { return &AtMostEvery{ delay: delay, } } // updateLastCall returns true if the lastCall time has been updated, // false if it was too early. func (s *AtMostEvery) updateLastCall() bool { s.mutex.Lock() defer s.mutex.Unlock() if time.Since(s.lastCall) < s.delay { return false } s.lastCall = time.Now() return true } // Do will run the method if enough time has passed, and return true. // Otherwise, it does nothing and returns false. func (s *AtMostEvery) Do(fn func()) bool { if !s.updateLastCall() { return false } fn() return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "fmt" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/merge" "sigs.k8s.io/structured-merge-diff/v4/typed" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) type structuredMergeManager struct { typeConverter TypeConverter objectConverter runtime.ObjectConvertor objectDefaulter runtime.ObjectDefaulter groupVersion schema.GroupVersion hubVersion schema.GroupVersion updater merge.Updater } var _ Manager = &structuredMergeManager{} // NewStructuredMergeManager creates a new Manager that merges apply requests // and update managed fields for other types of requests. func NewStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]fieldpath.Filter) (Manager, error) { if typeConverter == nil { return nil, fmt.Errorf("typeconverter must not be nil") } return &structuredMergeManager{ typeConverter: typeConverter, objectConverter: objectConverter, objectDefaulter: objectDefaulter, groupVersion: gv, hubVersion: hub, updater: merge.Updater{ Converter: newVersionConverter(typeConverter, objectConverter, hub), // This is the converter provided to SMD from k8s IgnoreFilter: resetFields, }, }, nil } // NewCRDStructuredMergeManager creates a new Manager specifically for // CRDs. This allows for the possibility of fields which are not defined // in models, as well as having no models defined at all. func NewCRDStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]fieldpath.Filter) (_ Manager, err error) { return &structuredMergeManager{ typeConverter: typeConverter, objectConverter: objectConverter, objectDefaulter: objectDefaulter, groupVersion: gv, hubVersion: hub, updater: merge.Updater{ Converter: newCRDVersionConverter(typeConverter, objectConverter, hub), IgnoreFilter: resetFields, }, }, nil } func objectGVKNN(obj runtime.Object) string { name := "<unknown>" namespace := "<unknown>" if accessor, err := meta.Accessor(obj); err == nil { name = accessor.GetName() namespace = accessor.GetNamespace() } return fmt.Sprintf("%v/%v; %v", namespace, name, obj.GetObjectKind().GroupVersionKind()) } // Update implements Manager. func (f *structuredMergeManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { newObjVersioned, err := f.toVersioned(newObj) if err != nil { return nil, nil, fmt.Errorf("failed to convert new object (%v) to proper version (%v): %v", objectGVKNN(newObj), f.groupVersion, err) } liveObjVersioned, err := f.toVersioned(liveObj) if err != nil { return nil, nil, fmt.Errorf("failed to convert live object (%v) to proper version: %v", objectGVKNN(liveObj), err) } newObjTyped, err := f.typeConverter.ObjectToTyped(newObjVersioned, typed.AllowDuplicates) if err != nil { return nil, nil, fmt.Errorf("failed to convert new object (%v) to smd typed: %v", objectGVKNN(newObjVersioned), err) } liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned, typed.AllowDuplicates) if err != nil { return nil, nil, fmt.Errorf("failed to convert live object (%v) to smd typed: %v", objectGVKNN(liveObjVersioned), err) } apiVersion := fieldpath.APIVersion(f.groupVersion.String()) // TODO(apelisse) use the first return value when unions are implemented _, managedFields, err := f.updater.Update(liveObjTyped, newObjTyped, apiVersion, managed.Fields(), manager) if err != nil { return nil, nil, fmt.Errorf("failed to update ManagedFields (%v): %v", objectGVKNN(newObjVersioned), err) } managed = NewManaged(managedFields, managed.Times()) return newObj, managed, nil } // Apply implements Manager. func (f *structuredMergeManager) Apply(liveObj, patchObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { // Check that the patch object has the same version as the live object if patchVersion := patchObj.GetObjectKind().GroupVersionKind().GroupVersion(); patchVersion != f.groupVersion { return nil, nil, errors.NewBadRequest( fmt.Sprintf("Incorrect version specified in apply patch. "+ "Specified patch version: %s, expected: %s", patchVersion, f.groupVersion)) } patchObjMeta, err := meta.Accessor(patchObj) if err != nil { return nil, nil, fmt.Errorf("couldn't get accessor: %v", err) } if patchObjMeta.GetManagedFields() != nil { return nil, nil, errors.NewBadRequest("metadata.managedFields must be nil") } liveObjVersioned, err := f.toVersioned(liveObj) if err != nil { return nil, nil, fmt.Errorf("failed to convert live object (%v) to proper version: %v", objectGVKNN(liveObj), err) } // Don't allow duplicates in the applied object. patchObjTyped, err := f.typeConverter.ObjectToTyped(patchObj) if err != nil { return nil, nil, fmt.Errorf("failed to create typed patch object (%v): %v", objectGVKNN(patchObj), err) } liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned, typed.AllowDuplicates) if err != nil { return nil, nil, fmt.Errorf("failed to create typed live object (%v): %v", objectGVKNN(liveObjVersioned), err) } apiVersion := fieldpath.APIVersion(f.groupVersion.String()) newObjTyped, managedFields, err := f.updater.Apply(liveObjTyped, patchObjTyped, apiVersion, managed.Fields(), manager, force) if err != nil { return nil, nil, err } managed = NewManaged(managedFields, managed.Times()) if newObjTyped == nil { return nil, managed, nil } newObj, err := f.typeConverter.TypedToObject(newObjTyped) if err != nil { return nil, nil, fmt.Errorf("failed to convert new typed object (%v) to object: %v", objectGVKNN(patchObj), err) } newObjVersioned, err := f.toVersioned(newObj) if err != nil { return nil, nil, fmt.Errorf("failed to convert new object (%v) to proper version: %v", objectGVKNN(patchObj), err) } f.objectDefaulter.Default(newObjVersioned) newObjUnversioned, err := f.toUnversioned(newObjVersioned) if err != nil { return nil, nil, fmt.Errorf("failed to convert to unversioned (%v): %v", objectGVKNN(patchObj), err) } return newObjUnversioned, managed, nil } func (f *structuredMergeManager) toVersioned(obj runtime.Object) (runtime.Object, error) { return f.objectConverter.ConvertToVersion(obj, f.groupVersion) } func (f *structuredMergeManager) toUnversioned(obj runtime.Object) (runtime.Object, error) { return f.objectConverter.ConvertToVersion(obj, f.hubVersion) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfieldsupdater.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfieldsupdater.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internal import ( "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) type managedFieldsUpdater struct { fieldManager Manager } var _ Manager = &managedFieldsUpdater{} // NewManagedFieldsUpdater is responsible for updating the managedfields // in the object, updating the time of the operation as necessary. For // updates, it uses a hard-coded manager to detect if things have // changed, and swaps back the correct manager after the operation is // done. func NewManagedFieldsUpdater(fieldManager Manager) Manager { return &managedFieldsUpdater{ fieldManager: fieldManager, } } // Update implements Manager. func (f *managedFieldsUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { self := "current-operation" object, managed, err := f.fieldManager.Update(liveObj, newObj, managed, self) if err != nil { return object, managed, err } // If the current operation took any fields from anything, it means the object changed, // so update the timestamp of the managedFieldsEntry and merge with any previous updates from the same manager if vs, ok := managed.Fields()[self]; ok { delete(managed.Fields(), self) if previous, ok := managed.Fields()[manager]; ok { managed.Fields()[manager] = fieldpath.NewVersionedSet(vs.Set().Union(previous.Set()), vs.APIVersion(), vs.Applied()) } else { managed.Fields()[manager] = vs } managed.Times()[manager] = &metav1.Time{Time: time.Now().UTC()} } return object, managed, nil } // Apply implements Manager. func (f *managedFieldsUpdater) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { object, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) if err != nil { return object, managed, err } if object != nil { managed.Times()[fieldManager] = &metav1.Time{Time: time.Now().UTC()} } else { object = liveObj.DeepCopyObject() RemoveObjectManagedFields(object) } return object, managed, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastapplied.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/lastapplied.go
/* 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 internal import ( "fmt" "k8s.io/apimachinery/pkg/api/meta" apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" "k8s.io/apimachinery/pkg/runtime" ) // LastAppliedConfigAnnotation is the annotation used to store the previous // configuration of a resource for use in a three way diff by UpdateApplyAnnotation. // // This is a copy of the corev1 annotation since we don't want to depend on the whole package. const LastAppliedConfigAnnotation = "kubectl.kubernetes.io/last-applied-configuration" // SetLastApplied sets the last-applied annotation the given value in // the object. func SetLastApplied(obj runtime.Object, value string) error { accessor, err := meta.Accessor(obj) if err != nil { panic(fmt.Sprintf("couldn't get accessor: %v", err)) } var annotations = accessor.GetAnnotations() if annotations == nil { annotations = map[string]string{} } annotations[LastAppliedConfigAnnotation] = value if err := apimachineryvalidation.ValidateAnnotationsSize(annotations); err != nil { delete(annotations, LastAppliedConfigAnnotation) } accessor.SetAnnotations(annotations) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go
/* 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 internal import ( "fmt" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/kube-openapi/pkg/schemaconv" "k8s.io/kube-openapi/pkg/validation/spec" smdschema "sigs.k8s.io/structured-merge-diff/v4/schema" "sigs.k8s.io/structured-merge-diff/v4/typed" "sigs.k8s.io/structured-merge-diff/v4/value" ) // TypeConverter allows you to convert from runtime.Object to // typed.TypedValue and the other way around. type TypeConverter interface { ObjectToTyped(runtime.Object, ...typed.ValidationOptions) (*typed.TypedValue, error) TypedToObject(*typed.TypedValue) (runtime.Object, error) } type typeConverter struct { parser map[schema.GroupVersionKind]*typed.ParseableType } var _ TypeConverter = &typeConverter{} func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) { typeSchema, err := schemaconv.ToSchemaFromOpenAPI(openapiSpec, preserveUnknownFields) if err != nil { return nil, fmt.Errorf("failed to convert models to schema: %v", err) } typeParser := typed.Parser{Schema: smdschema.Schema{Types: typeSchema.Types}} tr := indexModels(&typeParser, openapiSpec) return &typeConverter{parser: tr}, nil } func (c *typeConverter) ObjectToTyped(obj runtime.Object, opts ...typed.ValidationOptions) (*typed.TypedValue, error) { gvk := obj.GetObjectKind().GroupVersionKind() t := c.parser[gvk] if t == nil { return nil, NewNoCorrespondingTypeError(gvk) } switch o := obj.(type) { case *unstructured.Unstructured: return t.FromUnstructured(o.UnstructuredContent(), opts...) default: return t.FromStructured(obj, opts...) } } func (c *typeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) { return valueToObject(value.AsValue()) } type deducedTypeConverter struct{} // DeducedTypeConverter is a TypeConverter for CRDs that don't have a // schema. It does implement the same interface though (and create the // same types of objects), so that everything can still work the same. // CRDs are merged with all their fields being "atomic" (lists // included). func NewDeducedTypeConverter() TypeConverter { return deducedTypeConverter{} } // ObjectToTyped converts an object into a TypedValue with a "deduced type". func (deducedTypeConverter) ObjectToTyped(obj runtime.Object, opts ...typed.ValidationOptions) (*typed.TypedValue, error) { switch o := obj.(type) { case *unstructured.Unstructured: return typed.DeducedParseableType.FromUnstructured(o.UnstructuredContent(), opts...) default: return typed.DeducedParseableType.FromStructured(obj, opts...) } } // TypedToObject transforms the typed value into a runtime.Object. That // is not specific to deduced type. func (deducedTypeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) { return valueToObject(value.AsValue()) } func valueToObject(val value.Value) (runtime.Object, error) { vu := val.Unstructured() switch o := vu.(type) { case map[string]interface{}: return &unstructured.Unstructured{Object: o}, nil default: return nil, fmt.Errorf("failed to convert value to unstructured for type %T", vu) } } func indexModels( typeParser *typed.Parser, openAPISchemas map[string]*spec.Schema, ) map[schema.GroupVersionKind]*typed.ParseableType { tr := map[schema.GroupVersionKind]*typed.ParseableType{} for modelName, model := range openAPISchemas { gvkList := parseGroupVersionKind(model.Extensions) if len(gvkList) == 0 { continue } parsedType := typeParser.Type(modelName) for _, gvk := range gvkList { if len(gvk.Kind) > 0 { tr[schema.GroupVersionKind(gvk)] = &parsedType } } } return tr } // Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one. func parseGroupVersionKind(extensions map[string]interface{}) []schema.GroupVersionKind { gvkListResult := []schema.GroupVersionKind{} // Get the extensions gvkExtension, ok := extensions["x-kubernetes-group-version-kind"] if !ok { return []schema.GroupVersionKind{} } // gvk extension must be a list of at least 1 element. gvkList, ok := gvkExtension.([]interface{}) if !ok { return []schema.GroupVersionKind{} } for _, gvk := range gvkList { var group, version, kind string // gvk extension list must be a map with group, version, and // kind fields if gvkMap, ok := gvk.(map[interface{}]interface{}); ok { group, ok = gvkMap["group"].(string) if !ok { continue } version, ok = gvkMap["version"].(string) if !ok { continue } kind, ok = gvkMap["kind"].(string) if !ok { continue } } else if gvkMap, ok := gvk.(map[string]interface{}); ok { group, ok = gvkMap["group"].(string) if !ok { continue } version, ok = gvkMap["version"].(string) if !ok { continue } kind, ok = gvkMap["kind"].(string) if !ok { continue } } else { continue } gvkListResult = append(gvkListResult, schema.GroupVersionKind{ Group: group, Version: version, Kind: kind, }) } return gvkListResult }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 internal import ( "bytes" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) // EmptyFields represents a set with no paths // It looks like metav1.Fields{Raw: []byte("{}")} var EmptyFields = func() metav1.FieldsV1 { f, err := SetToFields(*fieldpath.NewSet()) if err != nil { panic("should never happen") } return f }() // 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)) 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() return f, err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/manager.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/managedfields/internal/manager.go
/* 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 internal import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/structured-merge-diff/v4/fieldpath" ) // Managed groups a fieldpath.ManagedFields together with the timestamps associated with each operation. type Managed interface { // Fields gets the fieldpath.ManagedFields. Fields() fieldpath.ManagedFields // Times gets the timestamps associated with each operation. Times() map[string]*metav1.Time } // Manager updates the managed fields and merges applied configurations. type Manager interface { // Update is used when the object has already been merged (non-apply // use-case), and simply updates the managed fields in the output // object. // * `liveObj` is not mutated by this function // * `newObj` may be mutated by this function // Returns the new object with managedFields removed, and the object's new // proposed managedFields separately. Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) // Apply is used when server-side apply is called, as it merges the // object and updates the managed fields. // * `liveObj` is not mutated by this function // * `newObj` may be mutated by this function // Returns the new object with managedFields removed, and the object's new // proposed managedFields separately. Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int64.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int64.go
/* 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 sets // Int64 is a set of int64s, implemented via map[int64]struct{} for minimal memory consumption. // // Deprecated: use generic Set instead. // new ways: // s1 := Set[int64]{} // s2 := New[int64]() type Int64 map[int64]Empty // NewInt64 creates a Int64 from a list of values. func NewInt64(items ...int64) Int64 { return Int64(New[int64](items...)) } // Int64KeySet creates a Int64 from a keys of a map[int64](? extends interface{}). // If the value passed in is not actually a map, this will panic. func Int64KeySet[T any](theMap map[int64]T) Int64 { return Int64(KeySet(theMap)) } // Insert adds items to the set. func (s Int64) Insert(items ...int64) Int64 { return Int64(cast(s).Insert(items...)) } // Delete removes all items from the set. func (s Int64) Delete(items ...int64) Int64 { return Int64(cast(s).Delete(items...)) } // Has returns true if and only if item is contained in the set. func (s Int64) Has(item int64) bool { return cast(s).Has(item) } // HasAll returns true if and only if all items are contained in the set. func (s Int64) HasAll(items ...int64) bool { return cast(s).HasAll(items...) } // HasAny returns true if any items are contained in the set. func (s Int64) HasAny(items ...int64) bool { return cast(s).HasAny(items...) } // Clone returns a new set which is a copy of the current set. func (s Int64) Clone() Int64 { return Int64(cast(s).Clone()) } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 Int64) Difference(s2 Int64) Int64 { return Int64(cast(s1).Difference(cast(s2))) } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 Int64) SymmetricDifference(s2 Int64) Int64 { return Int64(cast(s1).SymmetricDifference(cast(s2))) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Int64) Union(s2 Int64) Int64 { return Int64(cast(s1).Union(cast(s2))) } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Int64) Intersection(s2 Int64) Int64 { return Int64(cast(s1).Intersection(cast(s2))) } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Int64) IsSuperset(s2 Int64) bool { return cast(s1).IsSuperset(cast(s2)) } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Int64) Equal(s2 Int64) bool { return cast(s1).Equal(cast(s2)) } // List returns the contents as a sorted int64 slice. func (s Int64) List() []int64 { return List(cast(s)) } // UnsortedList returns the slice with contents in random order. func (s Int64) UnsortedList() []int64 { return cast(s).UnsortedList() } // PopAny returns a single element from the set. func (s Int64) PopAny() (int64, bool) { return cast(s).PopAny() } // Len returns the size of the set. func (s Int64) Len() int { return len(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/byte.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/byte.go
/* 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 sets // Byte is a set of bytes, implemented via map[byte]struct{} for minimal memory consumption. // // Deprecated: use generic Set instead. // new ways: // s1 := Set[byte]{} // s2 := New[byte]() type Byte map[byte]Empty // NewByte creates a Byte from a list of values. func NewByte(items ...byte) Byte { return Byte(New[byte](items...)) } // ByteKeySet creates a Byte from a keys of a map[byte](? extends interface{}). // If the value passed in is not actually a map, this will panic. func ByteKeySet[T any](theMap map[byte]T) Byte { return Byte(KeySet(theMap)) } // Insert adds items to the set. func (s Byte) Insert(items ...byte) Byte { return Byte(cast(s).Insert(items...)) } // Delete removes all items from the set. func (s Byte) Delete(items ...byte) Byte { return Byte(cast(s).Delete(items...)) } // Has returns true if and only if item is contained in the set. func (s Byte) Has(item byte) bool { return cast(s).Has(item) } // HasAll returns true if and only if all items are contained in the set. func (s Byte) HasAll(items ...byte) bool { return cast(s).HasAll(items...) } // HasAny returns true if any items are contained in the set. func (s Byte) HasAny(items ...byte) bool { return cast(s).HasAny(items...) } // Clone returns a new set which is a copy of the current set. func (s Byte) Clone() Byte { return Byte(cast(s).Clone()) } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 Byte) Difference(s2 Byte) Byte { return Byte(cast(s1).Difference(cast(s2))) } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 Byte) SymmetricDifference(s2 Byte) Byte { return Byte(cast(s1).SymmetricDifference(cast(s2))) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Byte) Union(s2 Byte) Byte { return Byte(cast(s1).Union(cast(s2))) } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Byte) Intersection(s2 Byte) Byte { return Byte(cast(s1).Intersection(cast(s2))) } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Byte) IsSuperset(s2 Byte) bool { return cast(s1).IsSuperset(cast(s2)) } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Byte) Equal(s2 Byte) bool { return cast(s1).Equal(cast(s2)) } // List returns the contents as a sorted byte slice. func (s Byte) List() []byte { return List(cast(s)) } // UnsortedList returns the slice with contents in random order. func (s Byte) UnsortedList() []byte { return cast(s).UnsortedList() } // PopAny returns a single element from the set. func (s Byte) PopAny() (byte, bool) { return cast(s).PopAny() } // Len returns the size of the set. func (s Byte) Len() int { return len(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/empty.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/empty.go
/* 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 sets // Empty is public since it is used by some internal API objects for conversions between external // string arrays and internal sets, and conversion logic requires public types today. type Empty struct{}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/set.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/set.go
/* 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 sets import ( "cmp" "sort" ) // Set is a set of the same type elements, implemented via map[comparable]struct{} for minimal memory consumption. type Set[T comparable] map[T]Empty // cast transforms specified set to generic Set[T]. func cast[T comparable](s map[T]Empty) Set[T] { return s } // New creates a Set from a list of values. // NOTE: type param must be explicitly instantiated if given items are empty. func New[T comparable](items ...T) Set[T] { ss := make(Set[T], len(items)) ss.Insert(items...) return ss } // KeySet creates a Set from a keys of a map[comparable](? extends interface{}). // If the value passed in is not actually a map, this will panic. func KeySet[T comparable, V any](theMap map[T]V) Set[T] { ret := make(Set[T], len(theMap)) for keyValue := range theMap { ret.Insert(keyValue) } return ret } // Insert adds items to the set. func (s Set[T]) Insert(items ...T) Set[T] { for _, item := range items { s[item] = Empty{} } return s } func Insert[T comparable](set Set[T], items ...T) Set[T] { return set.Insert(items...) } // Delete removes all items from the set. func (s Set[T]) Delete(items ...T) Set[T] { for _, item := range items { delete(s, item) } return s } // Clear empties the set. // It is preferable to replace the set with a newly constructed set, // but not all callers can do that (when there are other references to the map). func (s Set[T]) Clear() Set[T] { clear(s) return s } // Has returns true if and only if item is contained in the set. func (s Set[T]) Has(item T) bool { _, contained := s[item] return contained } // HasAll returns true if and only if all items are contained in the set. func (s Set[T]) HasAll(items ...T) bool { for _, item := range items { if !s.Has(item) { return false } } return true } // HasAny returns true if any items are contained in the set. func (s Set[T]) HasAny(items ...T) bool { for _, item := range items { if s.Has(item) { return true } } return false } // Clone returns a new set which is a copy of the current set. func (s Set[T]) Clone() Set[T] { result := make(Set[T], len(s)) for key := range s { result.Insert(key) } return result } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 Set[T]) Difference(s2 Set[T]) Set[T] { result := New[T]() for key := range s1 { if !s2.Has(key) { result.Insert(key) } } return result } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 Set[T]) SymmetricDifference(s2 Set[T]) Set[T] { return s1.Difference(s2).Union(s2.Difference(s1)) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Set[T]) Union(s2 Set[T]) Set[T] { result := s1.Clone() for key := range s2 { result.Insert(key) } return result } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Set[T]) Intersection(s2 Set[T]) Set[T] { var walk, other Set[T] result := New[T]() if s1.Len() < s2.Len() { walk = s1 other = s2 } else { walk = s2 other = s1 } for key := range walk { if other.Has(key) { result.Insert(key) } } return result } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Set[T]) IsSuperset(s2 Set[T]) bool { for item := range s2 { if !s1.Has(item) { return false } } return true } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Set[T]) Equal(s2 Set[T]) bool { return len(s1) == len(s2) && s1.IsSuperset(s2) } type sortableSliceOfGeneric[T cmp.Ordered] []T func (g sortableSliceOfGeneric[T]) Len() int { return len(g) } func (g sortableSliceOfGeneric[T]) Less(i, j int) bool { return less[T](g[i], g[j]) } func (g sortableSliceOfGeneric[T]) Swap(i, j int) { g[i], g[j] = g[j], g[i] } // List returns the contents as a sorted T slice. // // This is a separate function and not a method because not all types supported // by Generic are ordered and only those can be sorted. func List[T cmp.Ordered](s Set[T]) []T { res := make(sortableSliceOfGeneric[T], 0, len(s)) for key := range s { res = append(res, key) } sort.Sort(res) return res } // UnsortedList returns the slice with contents in random order. func (s Set[T]) UnsortedList() []T { res := make([]T, 0, len(s)) for key := range s { res = append(res, key) } return res } // PopAny returns a single element from the set. func (s Set[T]) PopAny() (T, bool) { for key := range s { s.Delete(key) return key, true } var zeroValue T return zeroValue, false } // Len returns the size of the set. func (s Set[T]) Len() int { return len(s) } func less[T cmp.Ordered](lhs, rhs T) bool { return lhs < rhs }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/string.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/string.go
/* 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 sets // String is a set of strings, implemented via map[string]struct{} for minimal memory consumption. // // Deprecated: use generic Set instead. // new ways: // s1 := Set[string]{} // s2 := New[string]() type String map[string]Empty // NewString creates a String from a list of values. func NewString(items ...string) String { return String(New[string](items...)) } // StringKeySet creates a String from a keys of a map[string](? extends interface{}). // If the value passed in is not actually a map, this will panic. func StringKeySet[T any](theMap map[string]T) String { return String(KeySet(theMap)) } // Insert adds items to the set. func (s String) Insert(items ...string) String { return String(cast(s).Insert(items...)) } // Delete removes all items from the set. func (s String) Delete(items ...string) String { return String(cast(s).Delete(items...)) } // Has returns true if and only if item is contained in the set. func (s String) Has(item string) bool { return cast(s).Has(item) } // HasAll returns true if and only if all items are contained in the set. func (s String) HasAll(items ...string) bool { return cast(s).HasAll(items...) } // HasAny returns true if any items are contained in the set. func (s String) HasAny(items ...string) bool { return cast(s).HasAny(items...) } // Clone returns a new set which is a copy of the current set. func (s String) Clone() String { return String(cast(s).Clone()) } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 String) Difference(s2 String) String { return String(cast(s1).Difference(cast(s2))) } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 String) SymmetricDifference(s2 String) String { return String(cast(s1).SymmetricDifference(cast(s2))) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 String) Union(s2 String) String { return String(cast(s1).Union(cast(s2))) } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 String) Intersection(s2 String) String { return String(cast(s1).Intersection(cast(s2))) } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 String) IsSuperset(s2 String) bool { return cast(s1).IsSuperset(cast(s2)) } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 String) Equal(s2 String) bool { return cast(s1).Equal(cast(s2)) } // List returns the contents as a sorted string slice. func (s String) List() []string { return List(cast(s)) } // UnsortedList returns the slice with contents in random order. func (s String) UnsortedList() []string { return cast(s).UnsortedList() } // PopAny returns a single element from the set. func (s String) PopAny() (string, bool) { return cast(s).PopAny() } // Len returns the size of the set. func (s String) Len() int { return len(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int.go
/* 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 sets // Int is a set of ints, implemented via map[int]struct{} for minimal memory consumption. // // Deprecated: use generic Set instead. // new ways: // s1 := Set[int]{} // s2 := New[int]() type Int map[int]Empty // NewInt creates a Int from a list of values. func NewInt(items ...int) Int { return Int(New[int](items...)) } // IntKeySet creates a Int from a keys of a map[int](? extends interface{}). // If the value passed in is not actually a map, this will panic. func IntKeySet[T any](theMap map[int]T) Int { return Int(KeySet(theMap)) } // Insert adds items to the set. func (s Int) Insert(items ...int) Int { return Int(cast(s).Insert(items...)) } // Delete removes all items from the set. func (s Int) Delete(items ...int) Int { return Int(cast(s).Delete(items...)) } // Has returns true if and only if item is contained in the set. func (s Int) Has(item int) bool { return cast(s).Has(item) } // HasAll returns true if and only if all items are contained in the set. func (s Int) HasAll(items ...int) bool { return cast(s).HasAll(items...) } // HasAny returns true if any items are contained in the set. func (s Int) HasAny(items ...int) bool { return cast(s).HasAny(items...) } // Clone returns a new set which is a copy of the current set. func (s Int) Clone() Int { return Int(cast(s).Clone()) } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 Int) Difference(s2 Int) Int { return Int(cast(s1).Difference(cast(s2))) } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 Int) SymmetricDifference(s2 Int) Int { return Int(cast(s1).SymmetricDifference(cast(s2))) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Int) Union(s2 Int) Int { return Int(cast(s1).Union(cast(s2))) } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Int) Intersection(s2 Int) Int { return Int(cast(s1).Intersection(cast(s2))) } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Int) IsSuperset(s2 Int) bool { return cast(s1).IsSuperset(cast(s2)) } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Int) Equal(s2 Int) bool { return cast(s1).Equal(cast(s2)) } // List returns the contents as a sorted int slice. func (s Int) List() []int { return List(cast(s)) } // UnsortedList returns the slice with contents in random order. func (s Int) UnsortedList() []int { return cast(s).UnsortedList() } // PopAny returns a single element from the set. func (s Int) PopAny() (int, bool) { return cast(s).PopAny() } // Len returns the size of the set. func (s Int) Len() int { return len(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int32.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/int32.go
/* 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 sets // Int32 is a set of int32s, implemented via map[int32]struct{} for minimal memory consumption. // // Deprecated: use generic Set instead. // new ways: // s1 := Set[int32]{} // s2 := New[int32]() type Int32 map[int32]Empty // NewInt32 creates a Int32 from a list of values. func NewInt32(items ...int32) Int32 { return Int32(New[int32](items...)) } // Int32KeySet creates a Int32 from a keys of a map[int32](? extends interface{}). // If the value passed in is not actually a map, this will panic. func Int32KeySet[T any](theMap map[int32]T) Int32 { return Int32(KeySet(theMap)) } // Insert adds items to the set. func (s Int32) Insert(items ...int32) Int32 { return Int32(cast(s).Insert(items...)) } // Delete removes all items from the set. func (s Int32) Delete(items ...int32) Int32 { return Int32(cast(s).Delete(items...)) } // Has returns true if and only if item is contained in the set. func (s Int32) Has(item int32) bool { return cast(s).Has(item) } // HasAll returns true if and only if all items are contained in the set. func (s Int32) HasAll(items ...int32) bool { return cast(s).HasAll(items...) } // HasAny returns true if any items are contained in the set. func (s Int32) HasAny(items ...int32) bool { return cast(s).HasAny(items...) } // Clone returns a new set which is a copy of the current set. func (s Int32) Clone() Int32 { return Int32(cast(s).Clone()) } // Difference returns a set of objects that are not in s2. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.Difference(s2) = {a3} // s2.Difference(s1) = {a4, a5} func (s1 Int32) Difference(s2 Int32) Int32 { return Int32(cast(s1).Difference(cast(s2))) } // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection. // For example: // s1 = {a1, a2, a3} // s2 = {a1, a2, a4, a5} // s1.SymmetricDifference(s2) = {a3, a4, a5} // s2.SymmetricDifference(s1) = {a3, a4, a5} func (s1 Int32) SymmetricDifference(s2 Int32) Int32 { return Int32(cast(s1).SymmetricDifference(cast(s2))) } // Union returns a new set which includes items in either s1 or s2. // For example: // s1 = {a1, a2} // s2 = {a3, a4} // s1.Union(s2) = {a1, a2, a3, a4} // s2.Union(s1) = {a1, a2, a3, a4} func (s1 Int32) Union(s2 Int32) Int32 { return Int32(cast(s1).Union(cast(s2))) } // Intersection returns a new set which includes the item in BOTH s1 and s2 // For example: // s1 = {a1, a2} // s2 = {a2, a3} // s1.Intersection(s2) = {a2} func (s1 Int32) Intersection(s2 Int32) Int32 { return Int32(cast(s1).Intersection(cast(s2))) } // IsSuperset returns true if and only if s1 is a superset of s2. func (s1 Int32) IsSuperset(s2 Int32) bool { return cast(s1).IsSuperset(cast(s2)) } // Equal returns true if and only if s1 is equal (as a set) to s2. // Two sets are equal if their membership is identical. // (In practice, this means same elements, order doesn't matter) func (s1 Int32) Equal(s2 Int32) bool { return cast(s1).Equal(cast(s2)) } // List returns the contents as a sorted int32 slice. func (s Int32) List() []int32 { return List(cast(s)) } // UnsortedList returns the slice with contents in random order. func (s Int32) UnsortedList() []int32 { return cast(s).UnsortedList() } // PopAny returns a single element from the set. func (s Int32) PopAny() (int32, bool) { return cast(s).PopAny() } // Len returns the size of the set. func (s Int32) Len() int { return len(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go
/* 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 sets has generic set and specified sets. Generic set will // replace specified ones over time. And specific ones are deprecated. package sets // import "k8s.io/apimachinery/pkg/util/sets"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/dump/dump.go
/* 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) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go
/* 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 framer implements simple frame decoding techniques for an io.ReadCloser package framer import ( "encoding/binary" "encoding/json" "io" ) type lengthDelimitedFrameWriter struct { w io.Writer h [4]byte } func NewLengthDelimitedFrameWriter(w io.Writer) io.Writer { return &lengthDelimitedFrameWriter{w: w} } // Write writes a single frame to the nested writer, prepending it with the length // in bytes of data (as a 4 byte, bigendian uint32). func (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error) { binary.BigEndian.PutUint32(w.h[:], uint32(len(data))) n, err := w.w.Write(w.h[:]) if err != nil { return 0, err } if n != len(w.h) { return 0, io.ErrShortWrite } return w.w.Write(data) } type lengthDelimitedFrameReader struct { r io.ReadCloser remaining int } // NewLengthDelimitedFrameReader returns an io.Reader that will decode length-prefixed // frames off of a stream. // // The protocol is: // // stream: message ... // message: prefix body // prefix: 4 byte uint32 in BigEndian order, denotes length of body // body: bytes (0..prefix) // // If the buffer passed to Read is not long enough to contain an entire frame, io.ErrShortRead // will be returned along with the number of bytes read. func NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser { return &lengthDelimitedFrameReader{r: r} } // Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer // is returned and subsequent calls will attempt to read the last frame. A frame is complete when // err is nil. func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) { if r.remaining <= 0 { header := [4]byte{} n, err := io.ReadAtLeast(r.r, header[:4], 4) if err != nil { return 0, err } if n != 4 { return 0, io.ErrUnexpectedEOF } frameLength := int(binary.BigEndian.Uint32(header[:])) r.remaining = frameLength } expect := r.remaining max := expect if max > len(data) { max = len(data) } n, err := io.ReadAtLeast(r.r, data[:max], int(max)) r.remaining -= n if err == io.ErrShortBuffer || r.remaining > 0 { return n, io.ErrShortBuffer } if err != nil { return n, err } if n != expect { return n, io.ErrUnexpectedEOF } return n, nil } func (r *lengthDelimitedFrameReader) Close() error { return r.r.Close() } type jsonFrameReader struct { r io.ReadCloser decoder *json.Decoder remaining []byte } // NewJSONFramedReader returns an io.Reader that will decode individual JSON objects off // of a wire. // // The boundaries between each frame are valid JSON objects. A JSON parsing error will terminate // the read. func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser { return &jsonFrameReader{ r: r, decoder: json.NewDecoder(r), } } // ReadFrame decodes the next JSON object in the stream, or returns an error. The returned // byte slice will be modified the next time ReadFrame is invoked and should not be altered. func (r *jsonFrameReader) Read(data []byte) (int, error) { // Return whatever remaining data exists from an in progress frame if n := len(r.remaining); n > 0 { if n <= len(data) { //nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here. data = append(data[0:0], r.remaining...) r.remaining = nil return n, nil } n = len(data) //nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here. data = append(data[0:0], r.remaining[:n]...) r.remaining = r.remaining[n:] return n, io.ErrShortBuffer } // RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see // data written to data, or be larger than data and a different array. m := json.RawMessage(data[:0]) if err := r.decoder.Decode(&m); err != nil { return 0, err } // If capacity of data is less than length of the message, decoder will allocate a new slice // and set m to it, which means we need to copy the partial result back into data and preserve // the remaining result for subsequent reads. if len(m) > cap(data) { copy(data, m) r.remaining = m[len(data):] return len(data), io.ErrShortBuffer } if len(m) > len(data) { // The bytes beyond len(data) were stored in data's underlying array, which we do // not own after this function returns. r.remaining = append([]byte(nil), m[len(data):]...) return len(data), io.ErrShortBuffer } return len(m), nil } func (r *jsonFrameReader) Close() error { return r.r.Close() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go
//go:build !notest // +build !notest /* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package intstr import ( fuzz "github.com/google/gofuzz" ) // Fuzz satisfies fuzz.Interface func (intstr *IntOrString) Fuzz(c fuzz.Continue) { if intstr == nil { return } if c.RandBool() { intstr.Type = Int c.Fuzz(&intstr.IntVal) intstr.StrVal = "" } else { intstr.Type = String intstr.IntVal = 0 c.Fuzz(&intstr.StrVal) } } // ensure IntOrString implements fuzz.Interface var _ fuzz.Interface = &IntOrString{}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 intstr import ( "encoding/json" "errors" "fmt" "math" "runtime/debug" "strconv" "strings" cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct" "k8s.io/klog/v2" ) // IntOrString is a type that can hold an int32 or a string. When used in // JSON or YAML marshalling and unmarshalling, it produces or consumes the // inner type. This allows you to have, for example, a JSON field that can // accept a name or number. // TODO: Rename to Int32OrString // // +protobuf=true // +protobuf.options.(gogoproto.goproto_stringer)=false // +k8s:openapi-gen=true type IntOrString struct { Type Type `protobuf:"varint,1,opt,name=type,casttype=Type"` IntVal int32 `protobuf:"varint,2,opt,name=intVal"` StrVal string `protobuf:"bytes,3,opt,name=strVal"` } // Type represents the stored type of IntOrString. type Type int64 const ( Int Type = iota // The IntOrString holds an int. String // The IntOrString holds a string. ) // FromInt creates an IntOrString object with an int32 value. It is // your responsibility not to call this method with a value greater // than int32. // Deprecated: use FromInt32 instead. func FromInt(val int) IntOrString { if val > math.MaxInt32 || val < math.MinInt32 { klog.Errorf("value: %d overflows int32\n%s\n", val, debug.Stack()) } return IntOrString{Type: Int, IntVal: int32(val)} } // FromInt32 creates an IntOrString object with an int32 value. func FromInt32(val int32) IntOrString { return IntOrString{Type: Int, IntVal: val} } // FromString creates an IntOrString object with a string value. func FromString(val string) IntOrString { return IntOrString{Type: String, StrVal: val} } // Parse the given string and try to convert it to an int32 integer before // setting it as a string value. func Parse(val string) IntOrString { i, err := strconv.ParseInt(val, 10, 32) if err != nil { return FromString(val) } return FromInt32(int32(i)) } // UnmarshalJSON implements the json.Unmarshaller interface. func (intstr *IntOrString) UnmarshalJSON(value []byte) error { if value[0] == '"' { intstr.Type = String return json.Unmarshal(value, &intstr.StrVal) } intstr.Type = Int return json.Unmarshal(value, &intstr.IntVal) } func (intstr *IntOrString) UnmarshalCBOR(value []byte) error { if err := cbor.Unmarshal(value, &intstr.StrVal); err == nil { intstr.Type = String return nil } if err := cbor.Unmarshal(value, &intstr.IntVal); err != nil { return err } intstr.Type = Int return nil } // String returns the string value, or the Itoa of the int value. func (intstr *IntOrString) String() string { if intstr == nil { return "<nil>" } if intstr.Type == String { return intstr.StrVal } return strconv.Itoa(intstr.IntValue()) } // IntValue returns the IntVal if type Int, or if // it is a String, will attempt a conversion to int, // returning 0 if a parsing error occurs. func (intstr *IntOrString) IntValue() int { if intstr.Type == String { i, _ := strconv.Atoi(intstr.StrVal) return i } return int(intstr.IntVal) } // MarshalJSON implements the json.Marshaller interface. func (intstr IntOrString) MarshalJSON() ([]byte, error) { switch intstr.Type { case Int: return json.Marshal(intstr.IntVal) case String: return json.Marshal(intstr.StrVal) default: return []byte{}, fmt.Errorf("impossible IntOrString.Type") } } func (intstr IntOrString) MarshalCBOR() ([]byte, error) { switch intstr.Type { case Int: return cbor.Marshal(intstr.IntVal) case String: return cbor.Marshal(intstr.StrVal) default: return nil, fmt.Errorf("impossible IntOrString.Type") } } // OpenAPISchemaType is used by the kube-openapi generator when constructing // the OpenAPI spec of this type. // // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators func (IntOrString) OpenAPISchemaType() []string { return []string{"string"} } // OpenAPISchemaFormat is used by the kube-openapi generator when constructing // the OpenAPI spec of this type. func (IntOrString) OpenAPISchemaFormat() string { return "int-or-string" } // OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing // the OpenAPI v3 spec of this type. func (IntOrString) OpenAPIV3OneOfTypes() []string { return []string{"integer", "string"} } func ValueOrDefault(intOrPercent *IntOrString, defaultValue IntOrString) *IntOrString { if intOrPercent == nil { return &defaultValue } return intOrPercent } // GetScaledValueFromIntOrPercent is meant to replace GetValueFromIntOrPercent. // This method returns a scaled value from an IntOrString type. If the IntOrString // is a percentage string value it's treated as a percentage and scaled appropriately // in accordance to the total, if it's an int value it's treated as a simple value and // if it is a string value which is either non-numeric or numeric but lacking a trailing '%' it returns an error. func GetScaledValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) { if intOrPercent == nil { return 0, errors.New("nil value for IntOrString") } value, isPercent, err := getIntOrPercentValueSafely(intOrPercent) if err != nil { return 0, fmt.Errorf("invalid value for IntOrString: %v", err) } if isPercent { if roundUp { value = int(math.Ceil(float64(value) * (float64(total)) / 100)) } else { value = int(math.Floor(float64(value) * (float64(total)) / 100)) } } return value, nil } // GetValueFromIntOrPercent was deprecated in favor of // GetScaledValueFromIntOrPercent. This method was treating all int as a numeric value and all // strings with or without a percent symbol as a percentage value. // Deprecated func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) { if intOrPercent == nil { return 0, errors.New("nil value for IntOrString") } value, isPercent, err := getIntOrPercentValue(intOrPercent) if err != nil { return 0, fmt.Errorf("invalid value for IntOrString: %v", err) } if isPercent { if roundUp { value = int(math.Ceil(float64(value) * (float64(total)) / 100)) } else { value = int(math.Floor(float64(value) * (float64(total)) / 100)) } } return value, nil } // getIntOrPercentValue is a legacy function and only meant to be called by GetValueFromIntOrPercent // For a more correct implementation call getIntOrPercentSafely func getIntOrPercentValue(intOrStr *IntOrString) (int, bool, error) { switch intOrStr.Type { case Int: return intOrStr.IntValue(), false, nil case String: s := strings.Replace(intOrStr.StrVal, "%", "", -1) v, err := strconv.Atoi(s) if err != nil { return 0, false, fmt.Errorf("invalid value %q: %v", intOrStr.StrVal, err) } return int(v), true, nil } return 0, false, fmt.Errorf("invalid type: neither int nor percentage") } func getIntOrPercentValueSafely(intOrStr *IntOrString) (int, bool, error) { switch intOrStr.Type { case Int: return intOrStr.IntValue(), false, nil case String: isPercent := false s := intOrStr.StrVal if strings.HasSuffix(s, "%") { isPercent = true s = strings.TrimSuffix(intOrStr.StrVal, "%") } else { return 0, false, fmt.Errorf("invalid type: string is not a percentage") } v, err := strconv.Atoi(s) if err != nil { return 0, false, fmt.Errorf("invalid value %q: %v", intOrStr.StrVal, err) } return int(v), isPercent, nil } return 0, false, fmt.Errorf("invalid type: neither int nor percentage") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/intstr/generated.pb.go
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: k8s.io/apimachinery/pkg/util/intstr/generated.proto package intstr import ( fmt "fmt" io "io" math "math" math_bits "math/bits" proto "github.com/gogo/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func (m *IntOrString) Reset() { *m = IntOrString{} } func (*IntOrString) ProtoMessage() {} func (*IntOrString) Descriptor() ([]byte, []int) { return fileDescriptor_771bacc35a5ec189, []int{0} } func (m *IntOrString) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *IntOrString) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) if err != nil { return nil, err } return b[:n], nil } func (m *IntOrString) XXX_Merge(src proto.Message) { xxx_messageInfo_IntOrString.Merge(m, src) } func (m *IntOrString) XXX_Size() int { return m.Size() } func (m *IntOrString) XXX_DiscardUnknown() { xxx_messageInfo_IntOrString.DiscardUnknown(m) } var xxx_messageInfo_IntOrString proto.InternalMessageInfo func init() { proto.RegisterType((*IntOrString)(nil), "k8s.io.apimachinery.pkg.util.intstr.IntOrString") } func init() { proto.RegisterFile("k8s.io/apimachinery/pkg/util/intstr/generated.proto", fileDescriptor_771bacc35a5ec189) } var fileDescriptor_771bacc35a5ec189 = []byte{ // 277 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xce, 0xb6, 0x28, 0xd6, 0xcb, 0xcc, 0xd7, 0x4f, 0x2c, 0xc8, 0xcc, 0x4d, 0x4c, 0xce, 0xc8, 0xcc, 0x4b, 0x2d, 0xaa, 0xd4, 0x2f, 0xc8, 0x4e, 0xd7, 0x2f, 0x2d, 0xc9, 0xcc, 0xd1, 0xcf, 0xcc, 0x2b, 0x29, 0x2e, 0x29, 0xd2, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0x4a, 0x2c, 0x49, 0x4d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x86, 0x68, 0xd2, 0x43, 0xd6, 0xa4, 0x57, 0x90, 0x9d, 0xae, 0x07, 0xd2, 0xa4, 0x07, 0xd1, 0x24, 0xa5, 0x9b, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, 0x9e, 0x9f, 0x9e, 0xaf, 0x0f, 0xd6, 0x9b, 0x54, 0x9a, 0x06, 0xe6, 0x81, 0x39, 0x60, 0x16, 0xc4, 0x4c, 0xa5, 0x89, 0x8c, 0x5c, 0xdc, 0x9e, 0x79, 0x25, 0xfe, 0x45, 0xc1, 0x25, 0x45, 0x99, 0x79, 0xe9, 0x42, 0x1a, 0x5c, 0x2c, 0x25, 0x95, 0x05, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x4e, 0x22, 0x27, 0xee, 0xc9, 0x33, 0x3c, 0xba, 0x27, 0xcf, 0x12, 0x52, 0x59, 0x90, 0xfa, 0x0b, 0x4a, 0x07, 0x81, 0x55, 0x08, 0xa9, 0x71, 0xb1, 0x65, 0xe6, 0x95, 0x84, 0x25, 0xe6, 0x48, 0x30, 0x29, 0x30, 0x6a, 0xb0, 0x3a, 0xf1, 0x41, 0xd5, 0xb2, 0x79, 0x82, 0x45, 0x83, 0xa0, 0xb2, 0x20, 0x75, 0xc5, 0x25, 0x45, 0x20, 0x75, 0xcc, 0x0a, 0x8c, 0x1a, 0x9c, 0x08, 0x75, 0xc1, 0x60, 0xd1, 0x20, 0xa8, 0xac, 0x15, 0xc7, 0x8c, 0x05, 0xf2, 0x0c, 0x0d, 0x77, 0x14, 0x18, 0x9c, 0x3c, 0x4f, 0x3c, 0x94, 0x63, 0xb8, 0xf0, 0x50, 0x8e, 0xe1, 0xc6, 0x43, 0x39, 0x86, 0x86, 0x47, 0x72, 0x8c, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0x78, 0xe3, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x44, 0x29, 0x13, 0x11, 0x84, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x63, 0xa1, 0x0b, 0x1e, 0x68, 0x01, 0x00, 0x00, } func (m *IntOrString) 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 *IntOrString) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } func (m *IntOrString) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l i -= len(m.StrVal) copy(dAtA[i:], m.StrVal) i = encodeVarintGenerated(dAtA, i, uint64(len(m.StrVal))) i-- dAtA[i] = 0x1a i = encodeVarintGenerated(dAtA, i, uint64(m.IntVal)) i-- dAtA[i] = 0x10 i = encodeVarintGenerated(dAtA, i, uint64(m.Type)) i-- dAtA[i] = 0x8 return len(dAtA) - i, nil } func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { offset -= sovGenerated(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return base } func (m *IntOrString) Size() (n int) { if m == nil { return 0 } var l int _ = l n += 1 + sovGenerated(uint64(m.Type)) n += 1 + sovGenerated(uint64(m.IntVal)) l = len(m.StrVal) n += 1 + l + sovGenerated(uint64(l)) return n } func sovGenerated(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *IntOrString) 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: IntOrString: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IntOrString: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } m.Type = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Type |= Type(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field IntVal", wireType) } m.IntVal = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.IntVal |= int32(b&0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StrVal", 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.StrVal = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthGenerated } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroupGenerated } depth-- case 5: iNdEx += 4 default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLengthGenerated } if depth == 0 { return iNdEx, nil } } return 0, io.ErrUnexpectedEOF } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/error.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/error.go
/* 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 wait import ( "context" "errors" ) // ErrWaitTimeout is returned when the condition was not satisfied in time. // // Deprecated: This type will be made private in favor of Interrupted() // for checking errors or ErrorInterrupted(err) for returning a wrapped error. var ErrWaitTimeout = ErrorInterrupted(errors.New("timed out waiting for the condition")) // Interrupted returns true if the error indicates a Poll, ExponentialBackoff, or // Until loop exited for any reason besides the condition returning true or an // error. A loop is considered interrupted if the calling context is cancelled, // the context reaches its deadline, or a backoff reaches its maximum allowed // steps. // // Callers should use this method instead of comparing the error value directly to // ErrWaitTimeout, as methods that cancel a context may not return that error. // // Instead of: // // err := wait.Poll(...) // if err == wait.ErrWaitTimeout { // log.Infof("Wait for operation exceeded") // } else ... // // Use: // // err := wait.Poll(...) // if wait.Interrupted(err) { // log.Infof("Wait for operation exceeded") // } else ... func Interrupted(err error) bool { switch { case errors.Is(err, errWaitTimeout), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): return true default: return false } } // errInterrupted type errInterrupted struct { cause error } // ErrorInterrupted returns an error that indicates the wait was ended // early for a given reason. If no cause is provided a generic error // will be used but callers are encouraged to provide a real cause for // clarity in debugging. func ErrorInterrupted(cause error) error { switch cause.(type) { case errInterrupted: // no need to wrap twice since errInterrupted is only needed // once in a chain return cause default: return errInterrupted{cause} } } // errWaitTimeout is the private version of the previous ErrWaitTimeout // and is private to prevent direct comparison. Use ErrorInterrupted(err) // to get an error that will return true for Interrupted(err). var errWaitTimeout = errInterrupted{} func (e errInterrupted) Unwrap() error { return e.cause } func (e errInterrupted) Is(target error) bool { return target == errWaitTimeout } func (e errInterrupted) Error() string { if e.cause == nil { // returns the same error message as historical behavior return "timed out waiting for the condition" } return e.cause.Error() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 wait import ( "context" "math/rand" "sync" "time" "k8s.io/apimachinery/pkg/util/runtime" ) // For any test of the style: // // ... // <- time.After(timeout): // t.Errorf("Timed out") // // The value for timeout should effectively be "forever." Obviously we don't want our tests to truly lock up forever, but 30s // is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine // (GC, seeks, etc), but not so long as to make a developer ctrl-c a test run if they do happen to break that test. var ForeverTestTimeout = time.Second * 30 // NeverStop may be passed to Until to make it never stop. var NeverStop <-chan struct{} = make(chan struct{}) // Group allows to start a group of goroutines and wait for their completion. type Group struct { wg sync.WaitGroup } func (g *Group) Wait() { g.wg.Wait() } // StartWithChannel starts f in a new goroutine in the group. // stopCh is passed to f as an argument. f should stop when stopCh is available. func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{})) { g.Start(func() { f(stopCh) }) } // StartWithContext starts f in a new goroutine in the group. // ctx is passed to f as an argument. f should stop when ctx.Done() is available. func (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) { g.Start(func() { f(ctx) }) } // Start starts f in a new goroutine in the group. func (g *Group) Start(f func()) { g.wg.Add(1) go func() { defer g.wg.Done() f() }() } // Forever calls f every period for ever. // // Forever is syntactic sugar on top of Until. func Forever(f func(), period time.Duration) { Until(f, period, NeverStop) } // Jitter returns a time.Duration between duration and duration + maxFactor * // duration. // // This allows clients to avoid converging on periodic behavior. If maxFactor // is 0.0, a suggested default value will be chosen. func Jitter(duration time.Duration, maxFactor float64) time.Duration { if maxFactor <= 0.0 { maxFactor = 1.0 } wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration)) return wait } // ConditionFunc returns true if the condition is satisfied, or an error // if the loop should be aborted. type ConditionFunc func() (done bool, err error) // ConditionWithContextFunc returns true if the condition is satisfied, or an error // if the loop should be aborted. // // The caller passes along a context that can be used by the condition function. type ConditionWithContextFunc func(context.Context) (done bool, err error) // WithContext converts a ConditionFunc into a ConditionWithContextFunc func (cf ConditionFunc) WithContext() ConditionWithContextFunc { return func(context.Context) (done bool, err error) { return cf() } } // ContextForChannel provides a context that will be treated as cancelled // when the provided parentCh is closed. The implementation returns // context.Canceled for Err() if and only if the parentCh is closed. func ContextForChannel(parentCh <-chan struct{}) context.Context { return channelContext{stopCh: parentCh} } var _ context.Context = channelContext{} // channelContext will behave as if the context were cancelled when stopCh is // closed. type channelContext struct { stopCh <-chan struct{} } func (c channelContext) Done() <-chan struct{} { return c.stopCh } func (c channelContext) Err() error { select { case <-c.stopCh: return context.Canceled default: return nil } } func (c channelContext) Deadline() (time.Time, bool) { return time.Time{}, false } func (c channelContext) Value(key any) any { return nil } // runConditionWithCrashProtection runs a ConditionFunc with crash protection. // // Deprecated: Will be removed when the legacy polling methods are removed. func runConditionWithCrashProtection(condition ConditionFunc) (bool, error) { defer runtime.HandleCrash() return condition() } // runConditionWithCrashProtectionWithContext runs a ConditionWithContextFunc // with crash protection. // // Deprecated: Will be removed when the legacy polling methods are removed. func runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error) { defer runtime.HandleCrash() return condition(ctx) } // waitFunc creates a channel that receives an item every time a test // should be executed and is closed when the last test should be invoked. // // Deprecated: Will be removed in a future release in favor of // loopConditionUntilContext. type waitFunc func(done <-chan struct{}) <-chan struct{} // WithContext converts the WaitFunc to an equivalent WaitWithContextFunc func (w waitFunc) WithContext() waitWithContextFunc { return func(ctx context.Context) <-chan struct{} { return w(ctx.Done()) } } // waitWithContextFunc creates a channel that receives an item every time a test // should be executed and is closed when the last test should be invoked. // // When the specified context gets cancelled or expires the function // stops sending item and returns immediately. // // Deprecated: Will be removed in a future release in favor of // loopConditionUntilContext. type waitWithContextFunc func(ctx context.Context) <-chan struct{} // waitForWithContext continually checks 'fn' as driven by 'wait'. // // waitForWithContext gets a channel from 'wait()”, and then invokes 'fn' // once for every value placed on the channel and once more when the // channel is closed. If the channel is closed and 'fn' // returns false without error, waitForWithContext returns ErrWaitTimeout. // // If 'fn' returns an error the loop ends and that error is returned. If // 'fn' returns true the loop ends and nil is returned. // // context.Canceled will be returned if the ctx.Done() channel is closed // without fn ever returning true. // // When the ctx.Done() channel is closed, because the golang `select` statement is // "uniform pseudo-random", the `fn` might still run one or multiple times, // though eventually `waitForWithContext` will return. // // Deprecated: Will be removed in a future release in favor of // loopConditionUntilContext. func waitForWithContext(ctx context.Context, wait waitWithContextFunc, fn ConditionWithContextFunc) error { waitCtx, cancel := context.WithCancel(context.Background()) defer cancel() c := wait(waitCtx) for { select { case _, open := <-c: ok, err := runConditionWithCrashProtectionWithContext(ctx, fn) if err != nil { return err } if ok { return nil } if !open { return ErrWaitTimeout } case <-ctx.Done(): // returning ctx.Err() will break backward compatibility, use new PollUntilContext* // methods instead return ErrWaitTimeout } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/timer.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/timer.go
/* 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 wait import ( "time" "k8s.io/utils/clock" ) // Timer abstracts how wait functions interact with time runtime efficiently. Test // code may implement this interface directly but package consumers are encouraged // to use the Backoff type as the primary mechanism for acquiring a Timer. The // interface is a simplification of clock.Timer to prevent misuse. Timers are not // expected to be safe for calls from multiple goroutines. type Timer interface { // C returns a channel that will receive a struct{} each time the timer fires. // The channel should not be waited on after Stop() is invoked. It is allowed // to cache the returned value of C() for the lifetime of the Timer. C() <-chan time.Time // Next is invoked by wait functions to signal timers that the next interval // should begin. You may only use Next() if you have drained the channel C(). // You should not call Next() after Stop() is invoked. Next() // Stop releases the timer. It is safe to invoke if no other methods have been // called. Stop() } type noopTimer struct { closedCh <-chan time.Time } // newNoopTimer creates a timer with a unique channel to avoid contention // for the channel's lock across multiple unrelated timers. func newNoopTimer() noopTimer { ch := make(chan time.Time) close(ch) return noopTimer{closedCh: ch} } func (t noopTimer) C() <-chan time.Time { return t.closedCh } func (noopTimer) Next() {} func (noopTimer) Stop() {} type variableTimer struct { fn DelayFunc t clock.Timer new func(time.Duration) clock.Timer } func (t *variableTimer) C() <-chan time.Time { if t.t == nil { d := t.fn() t.t = t.new(d) } return t.t.C() } func (t *variableTimer) Next() { if t.t == nil { return } d := t.fn() t.t.Reset(d) } func (t *variableTimer) Stop() { if t.t == nil { return } t.t.Stop() t.t = nil } type fixedTimer struct { interval time.Duration t clock.Ticker new func(time.Duration) clock.Ticker } func (t *fixedTimer) C() <-chan time.Time { if t.t == nil { t.t = t.new(t.interval) } return t.t.C() } func (t *fixedTimer) Next() { // no-op for fixed timers } func (t *fixedTimer) Stop() { if t.t == nil { return } t.t.Stop() t.t = nil } var ( // RealTimer can be passed to methods that need a clock.Timer. RealTimer = clock.RealClock{}.NewTimer ) var ( // internalClock is used for test injection of clocks internalClock = clock.RealClock{} )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go
/* 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 wait import ( "context" "math" "sync" "time" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/utils/clock" ) // Backoff holds parameters applied to a Backoff function. type Backoff struct { // The initial duration. Duration time.Duration // Duration is multiplied by factor each iteration, if factor is not zero // and the limits imposed by Steps and Cap have not been reached. // Should not be negative. // The jitter does not contribute to the updates to the duration parameter. Factor float64 // The sleep at each iteration is the duration plus an additional // amount chosen uniformly at random from the interval between // zero and `jitter*duration`. Jitter float64 // The remaining number of iterations in which the duration // parameter may change (but progress can be stopped earlier by // hitting the cap). If not positive, the duration is not // changed. Used for exponential backoff in combination with // Factor and Cap. Steps int // A limit on revised values of the duration parameter. If a // multiplication by the factor parameter would make the duration // exceed the cap then the duration is set to the cap and the // steps parameter is set to zero. Cap time.Duration } // Step returns an amount of time to sleep determined by the original // Duration and Jitter. The backoff is mutated to update its Steps and // Duration. A nil Backoff always has a zero-duration step. func (b *Backoff) Step() time.Duration { if b == nil { return 0 } var nextDuration time.Duration nextDuration, b.Duration, b.Steps = delay(b.Steps, b.Duration, b.Cap, b.Factor, b.Jitter) return nextDuration } // DelayFunc returns a function that will compute the next interval to // wait given the arguments in b. It does not mutate the original backoff // but the function is safe to use only from a single goroutine. func (b Backoff) DelayFunc() DelayFunc { steps := b.Steps duration := b.Duration cap := b.Cap factor := b.Factor jitter := b.Jitter return func() time.Duration { var nextDuration time.Duration // jitter is applied per step and is not cumulative over multiple steps nextDuration, duration, steps = delay(steps, duration, cap, factor, jitter) return nextDuration } } // Timer returns a timer implementation appropriate to this backoff's parameters // for use with wait functions. func (b Backoff) Timer() Timer { if b.Steps > 1 || b.Jitter != 0 { return &variableTimer{new: internalClock.NewTimer, fn: b.DelayFunc()} } if b.Duration > 0 { return &fixedTimer{new: internalClock.NewTicker, interval: b.Duration} } return newNoopTimer() } // delay implements the core delay algorithm used in this package. func delay(steps int, duration, cap time.Duration, factor, jitter float64) (_ time.Duration, next time.Duration, nextSteps int) { // when steps is non-positive, do not alter the base duration if steps < 1 { if jitter > 0 { return Jitter(duration, jitter), duration, 0 } return duration, duration, 0 } steps-- // calculate the next step's interval if factor != 0 { next = time.Duration(float64(duration) * factor) if cap > 0 && next > cap { next = cap steps = 0 } } else { next = duration } // add jitter for this step if jitter > 0 { duration = Jitter(duration, jitter) } return duration, next, steps } // DelayWithReset returns a DelayFunc that will return the appropriate next interval to // wait. Every resetInterval the backoff parameters are reset to their initial state. // This method is safe to invoke from multiple goroutines, but all calls will advance // the backoff state when Factor is set. If Factor is zero, this method is the same as // invoking b.DelayFunc() since Steps has no impact without Factor. If resetInterval is // zero no backoff will be performed as the same calling DelayFunc with a zero factor // and steps. func (b Backoff) DelayWithReset(c clock.Clock, resetInterval time.Duration) DelayFunc { if b.Factor <= 0 { return b.DelayFunc() } if resetInterval <= 0 { b.Steps = 0 b.Factor = 0 return b.DelayFunc() } return (&backoffManager{ backoff: b, initialBackoff: b, resetInterval: resetInterval, clock: c, lastStart: c.Now(), timer: nil, }).Step } // Until loops until stop channel is closed, running f every period. // // Until is syntactic sugar on top of JitterUntil with zero jitter factor and // with sliding = true (which means the timer for period starts after the f // completes). func Until(f func(), period time.Duration, stopCh <-chan struct{}) { JitterUntil(f, period, 0.0, true, stopCh) } // UntilWithContext loops until context is done, running f every period. // // UntilWithContext is syntactic sugar on top of JitterUntilWithContext // with zero jitter factor and with sliding = true (which means the timer // for period starts after the f completes). func UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) { JitterUntilWithContext(ctx, f, period, 0.0, true) } // NonSlidingUntil loops until stop channel is closed, running f every // period. // // NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter // factor, with sliding = false (meaning the timer for period starts at the same // time as the function starts). func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) { JitterUntil(f, period, 0.0, false, stopCh) } // NonSlidingUntilWithContext loops until context is done, running f every // period. // // NonSlidingUntilWithContext is syntactic sugar on top of JitterUntilWithContext // with zero jitter factor, with sliding = false (meaning the timer for period // starts at the same time as the function starts). func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) { JitterUntilWithContext(ctx, f, period, 0.0, false) } // JitterUntil loops until stop channel is closed, running f every period. // // If jitterFactor is positive, the period is jittered before every run of f. // If jitterFactor is not positive, the period is unchanged and not jittered. // // If sliding is true, the period is computed after f runs. If it is false then // period includes the runtime for f. // // Close stopCh to stop. f may not be invoked if stop channel is already // closed. Pass NeverStop to if you don't want it stop. func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) { BackoffUntil(f, NewJitteredBackoffManager(period, jitterFactor, &clock.RealClock{}), sliding, stopCh) } // BackoffUntil loops until stop channel is closed, run f every duration given by BackoffManager. // // If sliding is true, the period is computed after f runs. If it is false then // period includes the runtime for f. func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan struct{}) { var t clock.Timer for { select { case <-stopCh: return default: } if !sliding { t = backoff.Backoff() } func() { defer runtime.HandleCrash() f() }() if sliding { t = backoff.Backoff() } // NOTE: b/c there is no priority selection in golang // it is possible for this to race, meaning we could // trigger t.C and stopCh, and t.C select falls through. // In order to mitigate we re-check stopCh at the beginning // of every loop to prevent extra executions of f(). select { case <-stopCh: if !t.Stop() { <-t.C() } return case <-t.C(): } } } // JitterUntilWithContext loops until context is done, running f every period. // // If jitterFactor is positive, the period is jittered before every run of f. // If jitterFactor is not positive, the period is unchanged and not jittered. // // If sliding is true, the period is computed after f runs. If it is false then // period includes the runtime for f. // // Cancel context to stop. f may not be invoked if context is already expired. func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) { JitterUntil(func() { f(ctx) }, period, jitterFactor, sliding, ctx.Done()) } // backoffManager provides simple backoff behavior in a threadsafe manner to a caller. type backoffManager struct { backoff Backoff initialBackoff Backoff resetInterval time.Duration clock clock.Clock lock sync.Mutex lastStart time.Time timer clock.Timer } // Step returns the expected next duration to wait. func (b *backoffManager) Step() time.Duration { b.lock.Lock() defer b.lock.Unlock() switch { case b.resetInterval == 0: b.backoff = b.initialBackoff case b.clock.Now().Sub(b.lastStart) > b.resetInterval: b.backoff = b.initialBackoff b.lastStart = b.clock.Now() } return b.backoff.Step() } // Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer // for exponential backoff. The returned timer must be drained before calling Backoff() the second // time. func (b *backoffManager) Backoff() clock.Timer { b.lock.Lock() defer b.lock.Unlock() if b.timer == nil { b.timer = b.clock.NewTimer(b.Step()) } else { b.timer.Reset(b.Step()) } return b.timer } // Timer returns a new Timer instance that shares the clock and the reset behavior with all other // timers. func (b *backoffManager) Timer() Timer { return DelayFunc(b.Step).Timer(b.clock) } // BackoffManager manages backoff with a particular scheme based on its underlying implementation. type BackoffManager interface { // Backoff returns a shared clock.Timer that is Reset on every invocation. This method is not // safe for use from multiple threads. It returns a timer for backoff, and caller shall backoff // until Timer.C() drains. If the second Backoff() is called before the timer from the first // Backoff() call finishes, the first timer will NOT be drained and result in undetermined // behavior. Backoff() clock.Timer } // Deprecated: Will be removed when the legacy polling functions are removed. type exponentialBackoffManagerImpl struct { backoff *Backoff backoffTimer clock.Timer lastBackoffStart time.Time initialBackoff time.Duration backoffResetDuration time.Duration clock clock.Clock } // NewExponentialBackoffManager returns a manager for managing exponential backoff. Each backoff is jittered and // backoff will not exceed the given max. If the backoff is not called within resetDuration, the backoff is reset. // This backoff manager is used to reduce load during upstream unhealthiness. // // Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a // Backoff struct, use DelayWithReset() to get a DelayFunc that periodically resets itself, and then // invoke Timer() when calling wait.BackoffUntil. // // Instead of: // // bm := wait.NewExponentialBackoffManager(init, max, reset, factor, jitter, clock) // ... // wait.BackoffUntil(..., bm.Backoff, ...) // // Use: // // delayFn := wait.Backoff{ // Duration: init, // Cap: max, // Steps: int(math.Ceil(float64(max) / float64(init))), // now a required argument // Factor: factor, // Jitter: jitter, // }.DelayWithReset(reset, clock) // wait.BackoffUntil(..., delayFn.Timer(), ...) func NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration time.Duration, backoffFactor, jitter float64, c clock.Clock) BackoffManager { return &exponentialBackoffManagerImpl{ backoff: &Backoff{ Duration: initBackoff, Factor: backoffFactor, Jitter: jitter, // the current impl of wait.Backoff returns Backoff.Duration once steps are used up, which is not // what we ideally need here, we set it to max int and assume we will never use up the steps Steps: math.MaxInt32, Cap: maxBackoff, }, backoffTimer: nil, initialBackoff: initBackoff, lastBackoffStart: c.Now(), backoffResetDuration: resetDuration, clock: c, } } func (b *exponentialBackoffManagerImpl) getNextBackoff() time.Duration { if b.clock.Now().Sub(b.lastBackoffStart) > b.backoffResetDuration { b.backoff.Steps = math.MaxInt32 b.backoff.Duration = b.initialBackoff } b.lastBackoffStart = b.clock.Now() return b.backoff.Step() } // Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for exponential backoff. // The returned timer must be drained before calling Backoff() the second time func (b *exponentialBackoffManagerImpl) Backoff() clock.Timer { if b.backoffTimer == nil { b.backoffTimer = b.clock.NewTimer(b.getNextBackoff()) } else { b.backoffTimer.Reset(b.getNextBackoff()) } return b.backoffTimer } // Deprecated: Will be removed when the legacy polling functions are removed. type jitteredBackoffManagerImpl struct { clock clock.Clock duration time.Duration jitter float64 backoffTimer clock.Timer } // NewJitteredBackoffManager returns a BackoffManager that backoffs with given duration plus given jitter. If the jitter // is negative, backoff will not be jittered. // // Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a // Backoff struct and invoke Timer() when calling wait.BackoffUntil. // // Instead of: // // bm := wait.NewJitteredBackoffManager(duration, jitter, clock) // ... // wait.BackoffUntil(..., bm.Backoff, ...) // // Use: // // wait.BackoffUntil(..., wait.Backoff{Duration: duration, Jitter: jitter}.Timer(), ...) func NewJitteredBackoffManager(duration time.Duration, jitter float64, c clock.Clock) BackoffManager { return &jitteredBackoffManagerImpl{ clock: c, duration: duration, jitter: jitter, backoffTimer: nil, } } func (j *jitteredBackoffManagerImpl) getNextBackoff() time.Duration { jitteredPeriod := j.duration if j.jitter > 0.0 { jitteredPeriod = Jitter(j.duration, j.jitter) } return jitteredPeriod } // Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for jittered backoff. // The returned timer must be drained before calling Backoff() the second time func (j *jitteredBackoffManagerImpl) Backoff() clock.Timer { backoff := j.getNextBackoff() if j.backoffTimer == nil { j.backoffTimer = j.clock.NewTimer(backoff) } else { j.backoffTimer.Reset(backoff) } return j.backoffTimer } // ExponentialBackoff repeats a condition check with exponential backoff. // // It repeatedly checks the condition and then sleeps, using `backoff.Step()` // to determine the length of the sleep and adjust Duration and Steps. // Stops and returns as soon as: // 1. the condition check returns true or an error, // 2. `backoff.Steps` checks of the condition have been done, or // 3. a sleep truncated by the cap on duration has been completed. // In case (1) the returned error is what the condition function returned. // In all other cases, ErrWaitTimeout is returned. // // Since backoffs are often subject to cancellation, we recommend using // ExponentialBackoffWithContext and passing a context to the method. func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error { for backoff.Steps > 0 { if ok, err := runConditionWithCrashProtection(condition); err != nil || ok { return err } if backoff.Steps == 1 { break } time.Sleep(backoff.Step()) } return ErrWaitTimeout } // ExponentialBackoffWithContext repeats a condition check with exponential backoff. // It immediately returns an error if the condition returns an error, the context is cancelled // or hits the deadline, or if the maximum attempts defined in backoff is exceeded (ErrWaitTimeout). // If an error is returned by the condition the backoff stops immediately. The condition will // never be invoked more than backoff.Steps times. func ExponentialBackoffWithContext(ctx context.Context, backoff Backoff, condition ConditionWithContextFunc) error { for backoff.Steps > 0 { select { case <-ctx.Done(): return ctx.Err() default: } if ok, err := runConditionWithCrashProtectionWithContext(ctx, condition); err != nil || ok { return err } if backoff.Steps == 1 { break } waitBeforeRetry := backoff.Step() select { case <-ctx.Done(): return ctx.Err() case <-time.After(waitBeforeRetry): } } return ErrWaitTimeout }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/delay.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/delay.go
/* 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 wait import ( "context" "sync" "time" "k8s.io/utils/clock" ) // DelayFunc returns the next time interval to wait. type DelayFunc func() time.Duration // Timer takes an arbitrary delay function and returns a timer that can handle arbitrary interval changes. // Use Backoff{...}.Timer() for simple delays and more efficient timers. func (fn DelayFunc) Timer(c clock.Clock) Timer { return &variableTimer{fn: fn, new: c.NewTimer} } // Until takes an arbitrary delay function and runs until cancelled or the condition indicates exit. This // offers all of the functionality of the methods in this package. func (fn DelayFunc) Until(ctx context.Context, immediate, sliding bool, condition ConditionWithContextFunc) error { return loopConditionUntilContext(ctx, &variableTimer{fn: fn, new: internalClock.NewTimer}, immediate, sliding, condition) } // Concurrent returns a version of this DelayFunc that is safe for use by multiple goroutines that // wish to share a single delay timer. func (fn DelayFunc) Concurrent() DelayFunc { var lock sync.Mutex return func() time.Duration { lock.Lock() defer lock.Unlock() return fn() } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 wait provides tools for polling or listening for changes // to a condition. package wait // import "k8s.io/apimachinery/pkg/util/wait"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/poll.go
/* 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 wait import ( "context" "time" ) // PollUntilContextCancel tries a condition func until it returns true, an error, or the context // is cancelled or hits a deadline. condition will be invoked after the first interval if the // context is not cancelled first. The returned error will be from ctx.Err(), the condition's // err return value, or nil. If invoking condition takes longer than interval the next condition // will be invoked immediately. When using very short intervals, condition may be invoked multiple // times before a context cancellation is detected. If immediate is true, condition will be // invoked before waiting and guarantees that condition is invoked at least once, regardless of // whether the context has been cancelled. func PollUntilContextCancel(ctx context.Context, interval time.Duration, immediate bool, condition ConditionWithContextFunc) error { return loopConditionUntilContext(ctx, Backoff{Duration: interval}.Timer(), immediate, false, condition) } // PollUntilContextTimeout will terminate polling after timeout duration by setting a context // timeout. This is provided as a convenience function for callers not currently executing under // a deadline and is equivalent to: // // deadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout) // err := PollUntilContextCancel(deadlineCtx, interval, immediate, condition) // // The deadline context will be cancelled if the Poll succeeds before the timeout, simplifying // inline usage. All other behavior is identical to PollUntilContextCancel. func PollUntilContextTimeout(ctx context.Context, interval, timeout time.Duration, immediate bool, condition ConditionWithContextFunc) error { deadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout) defer deadlineCancel() return loopConditionUntilContext(deadlineCtx, Backoff{Duration: interval}.Timer(), immediate, false, condition) } // Poll tries a condition func until it returns true, an error, or the timeout // is reached. // // Poll always waits the interval before the run of 'condition'. // 'condition' will always be invoked at least once. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // If you want to Poll something forever, see PollInfinite. // // Deprecated: This method does not return errors from context, use PollUntilContextTimeout. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func Poll(interval, timeout time.Duration, condition ConditionFunc) error { return PollWithContext(context.Background(), interval, timeout, condition.WithContext()) } // PollWithContext tries a condition func until it returns true, an error, // or when the context expires or the timeout is reached, whichever // happens first. // // PollWithContext always waits the interval before the run of 'condition'. // 'condition' will always be invoked at least once. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // If you want to Poll something forever, see PollInfinite. // // Deprecated: This method does not return errors from context, use PollUntilContextTimeout. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, false, poller(interval, timeout), condition) } // PollUntil tries a condition func until it returns true, an error or stopCh is // closed. // // PollUntil always waits interval before the first run of 'condition'. // 'condition' will always be invoked at least once. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error { return PollUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext()) } // PollUntilWithContext tries a condition func until it returns true, // an error or the specified context is cancelled or expired. // // PollUntilWithContext always waits interval before the first run of 'condition'. // 'condition' will always be invoked at least once. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, false, poller(interval, 0), condition) } // PollInfinite tries a condition func until it returns true or an error // // PollInfinite always waits the interval before the run of 'condition'. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollInfinite(interval time.Duration, condition ConditionFunc) error { return PollInfiniteWithContext(context.Background(), interval, condition.WithContext()) } // PollInfiniteWithContext tries a condition func until it returns true or an error // // PollInfiniteWithContext always waits the interval before the run of 'condition'. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, false, poller(interval, 0), condition) } // PollImmediate tries a condition func until it returns true, an error, or the timeout // is reached. // // PollImmediate always checks 'condition' before waiting for the interval. 'condition' // will always be invoked at least once. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // If you want to immediately Poll something forever, see PollImmediateInfinite. // // Deprecated: This method does not return errors from context, use PollUntilContextTimeout. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error { return PollImmediateWithContext(context.Background(), interval, timeout, condition.WithContext()) } // PollImmediateWithContext tries a condition func until it returns true, an error, // or the timeout is reached or the specified context expires, whichever happens first. // // PollImmediateWithContext always checks 'condition' before waiting for the interval. // 'condition' will always be invoked at least once. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // If you want to immediately Poll something forever, see PollImmediateInfinite. // // Deprecated: This method does not return errors from context, use PollUntilContextTimeout. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, true, poller(interval, timeout), condition) } // PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed. // // PollImmediateUntil runs the 'condition' before waiting for the interval. // 'condition' will always be invoked at least once. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error { return PollImmediateUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext()) } // PollImmediateUntilWithContext tries a condition func until it returns true, // an error or the specified context is cancelled or expired. // // PollImmediateUntilWithContext runs the 'condition' before waiting for the interval. // 'condition' will always be invoked at least once. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediateUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, true, poller(interval, 0), condition) } // PollImmediateInfinite tries a condition func until it returns true or an error // // PollImmediateInfinite runs the 'condition' before waiting for the interval. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error { return PollImmediateInfiniteWithContext(context.Background(), interval, condition.WithContext()) } // PollImmediateInfiniteWithContext tries a condition func until it returns true // or an error or the specified context gets cancelled or expired. // // PollImmediateInfiniteWithContext runs the 'condition' before waiting for the interval. // // Some intervals may be missed if the condition takes too long or the time // window is too short. // // Deprecated: This method does not return errors from context, use PollUntilContextCancel. // Note that the new method will no longer return ErrWaitTimeout and instead return errors // defined by the context package. Will be removed in a future release. func PollImmediateInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error { return poll(ctx, true, poller(interval, 0), condition) } // Internally used, each of the public 'Poll*' function defined in this // package should invoke this internal function with appropriate parameters. // ctx: the context specified by the caller, for infinite polling pass // a context that never gets cancelled or expired. // immediate: if true, the 'condition' will be invoked before waiting for the interval, // in this case 'condition' will always be invoked at least once. // wait: user specified WaitFunc function that controls at what interval the condition // function should be invoked periodically and whether it is bound by a timeout. // condition: user specified ConditionWithContextFunc function. // // Deprecated: will be removed in favor of loopConditionUntilContext. func poll(ctx context.Context, immediate bool, wait waitWithContextFunc, condition ConditionWithContextFunc) error { if immediate { done, err := runConditionWithCrashProtectionWithContext(ctx, condition) if err != nil { return err } if done { return nil } } select { case <-ctx.Done(): // returning ctx.Err() will break backward compatibility, use new PollUntilContext* // methods instead return ErrWaitTimeout default: return waitForWithContext(ctx, wait, condition) } } // poller returns a WaitFunc that will send to the channel every interval until // timeout has elapsed and then closes the channel. // // Over very short intervals you may receive no ticks before the channel is // closed. A timeout of 0 is interpreted as an infinity, and in such a case // it would be the caller's responsibility to close the done channel. // Failure to do so would result in a leaked goroutine. // // Output ticks are not buffered. If the channel is not ready to receive an // item, the tick is skipped. // // Deprecated: Will be removed in a future release. func poller(interval, timeout time.Duration) waitWithContextFunc { return waitWithContextFunc(func(ctx context.Context) <-chan struct{} { ch := make(chan struct{}) go func() { defer close(ch) tick := time.NewTicker(interval) defer tick.Stop() var after <-chan time.Time if timeout != 0 { // time.After is more convenient, but it // potentially leaves timers around much longer // than necessary if we exit early. timer := time.NewTimer(timeout) after = timer.C defer timer.Stop() } for { select { case <-tick.C: // If the consumer isn't ready for this signal drop it and // check the other channels. select { case ch <- struct{}{}: default: } case <-after: return case <-ctx.Done(): return } } }() return ch }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go
/* 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 wait import ( "context" "time" "k8s.io/apimachinery/pkg/util/runtime" ) // loopConditionUntilContext executes the provided condition at intervals defined by // the provided timer until the provided context is cancelled, the condition returns // true, or the condition returns an error. If sliding is true, the period is computed // after condition runs. If it is false then period includes the runtime for condition. // If immediate is false the first delay happens before any call to condition, if // immediate is true the condition will be invoked before waiting and guarantees that // the condition is invoked at least once, regardless of whether the context has been // cancelled. The returned error is the error returned by the last condition or the // context error if the context was terminated. // // This is the common loop construct for all polling in the wait package. func loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding bool, condition ConditionWithContextFunc) error { defer t.Stop() var timeCh <-chan time.Time doneCh := ctx.Done() if !sliding { timeCh = t.C() } // if immediate is true the condition is // guaranteed to be executed at least once, // if we haven't requested immediate execution, delay once if immediate { if ok, err := func() (bool, error) { defer runtime.HandleCrash() return condition(ctx) }(); err != nil || ok { return err } } if sliding { timeCh = t.C() } for { // Wait for either the context to be cancelled or the next invocation be called select { case <-doneCh: return ctx.Err() case <-timeCh: } // IMPORTANT: Because there is no channel priority selection in golang // it is possible for very short timers to "win" the race in the previous select // repeatedly even when the context has been canceled. We therefore must // explicitly check for context cancellation on every loop and exit if true to // guarantee that we don't invoke condition more than once after context has // been cancelled. if err := ctx.Err(); err != nil { return err } if !sliding { t.Next() } if ok, err := func() (bool, error) { defer runtime.HandleCrash() return condition(ctx) }(); err != nil || ok { return err } if sliding { t.Next() } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/util/naming/from_stack.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 naming import ( "fmt" "regexp" goruntime "runtime" "runtime/debug" "strconv" "strings" ) // GetNameFromCallsite walks back through the call stack until we find a caller from outside of the ignoredPackages // it returns back a shortpath/filename:line to aid in identification of this reflector when it starts logging func GetNameFromCallsite(ignoredPackages ...string) string { name := "????" const maxStack = 10 for i := 1; i < maxStack; i++ { _, file, line, ok := goruntime.Caller(i) if !ok { file, line, ok = extractStackCreator() if !ok { break } i += maxStack } if hasPackage(file, append(ignoredPackages, "/runtime/asm_")) { continue } file = trimPackagePrefix(file) name = fmt.Sprintf("%s:%d", file, line) break } return name } // hasPackage returns true if the file is in one of the ignored packages. func hasPackage(file string, ignoredPackages []string) bool { for _, ignoredPackage := range ignoredPackages { if strings.Contains(file, ignoredPackage) { return true } } return false } // trimPackagePrefix reduces duplicate values off the front of a package name. func trimPackagePrefix(file string) string { if l := strings.LastIndex(file, "/vendor/"); l >= 0 { return file[l+len("/vendor/"):] } if l := strings.LastIndex(file, "/src/"); l >= 0 { return file[l+5:] } if l := strings.LastIndex(file, "/pkg/"); l >= 0 { return file[l+1:] } return file } var stackCreator = regexp.MustCompile(`(?m)^created by (.*)\n\s+(.*):(\d+) \+0x[[:xdigit:]]+$`) // extractStackCreator retrieves the goroutine file and line that launched this stack. Returns false // if the creator cannot be located. // TODO: Go does not expose this via runtime https://github.com/golang/go/issues/11440 func extractStackCreator() (string, int, bool) { stack := debug.Stack() matches := stackCreator.FindStringSubmatch(string(stack)) if len(matches) != 4 { return "", 0, false } line, err := strconv.Atoi(matches[3]) if err != nil { return "", 0, false } return matches[2], line, true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/selector.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/selector.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package labels import ( "fmt" "slices" "sort" "strconv" "strings" "k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/klog/v2" ) var ( unaryOperators = []string{ string(selection.Exists), string(selection.DoesNotExist), } binaryOperators = []string{ string(selection.In), string(selection.NotIn), string(selection.Equals), string(selection.DoubleEquals), string(selection.NotEquals), string(selection.GreaterThan), string(selection.LessThan), } validRequirementOperators = append(binaryOperators, unaryOperators...) ) // Requirements is AND of all requirements. type Requirements []Requirement func (r Requirements) String() string { var sb strings.Builder for i, requirement := range r { if i > 0 { sb.WriteString(", ") } sb.WriteString(requirement.String()) } return sb.String() } // Selector represents a label selector. type Selector interface { // Matches returns true if this selector matches the given set of labels. Matches(Labels) bool // Empty returns true if this selector does not restrict the selection space. Empty() bool // String returns a human readable string that represents this selector. String() string // Add adds requirements to the Selector Add(r ...Requirement) Selector // Requirements converts this interface into Requirements to expose // more detailed selection information. // If there are querying parameters, it will return converted requirements and selectable=true. // If this selector doesn't want to select anything, it will return selectable=false. Requirements() (requirements Requirements, selectable bool) // Make a deep copy of the selector. DeepCopySelector() Selector // RequiresExactMatch allows a caller to introspect whether a given selector // requires a single specific label to be set, and if so returns the value it // requires. RequiresExactMatch(label string) (value string, found bool) } // Sharing this saves 1 alloc per use; this is safe because it's immutable. var sharedEverythingSelector Selector = internalSelector{} // Everything returns a selector that matches all labels. func Everything() Selector { return sharedEverythingSelector } type nothingSelector struct{} func (n nothingSelector) Matches(_ Labels) bool { return false } func (n nothingSelector) Empty() bool { return false } func (n nothingSelector) String() string { return "" } func (n nothingSelector) Add(_ ...Requirement) Selector { return n } func (n nothingSelector) Requirements() (Requirements, bool) { return nil, false } func (n nothingSelector) DeepCopySelector() Selector { return n } func (n nothingSelector) RequiresExactMatch(label string) (value string, found bool) { return "", false } // Sharing this saves 1 alloc per use; this is safe because it's immutable. var sharedNothingSelector Selector = nothingSelector{} // Nothing returns a selector that matches no labels func Nothing() Selector { return sharedNothingSelector } // NewSelector returns a nil selector func NewSelector() Selector { return internalSelector(nil) } type internalSelector []Requirement func (s internalSelector) DeepCopy() internalSelector { if s == nil { return nil } result := make([]Requirement, len(s)) for i := range s { s[i].DeepCopyInto(&result[i]) } return result } func (s internalSelector) DeepCopySelector() Selector { return s.DeepCopy() } // ByKey sorts requirements by key to obtain deterministic parser type ByKey []Requirement func (a ByKey) Len() int { return len(a) } func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByKey) Less(i, j int) bool { return a[i].key < a[j].key } // Requirement contains values, a key, and an operator that relates the key and values. // The zero value of Requirement is invalid. // Requirement implements both set based match and exact match // Requirement should be initialized via NewRequirement constructor for creating a valid Requirement. // +k8s:deepcopy-gen=true type Requirement struct { key string operator selection.Operator // In huge majority of cases we have at most one value here. // It is generally faster to operate on a single-element slice // than on a single-element map, so we have a slice here. strValues []string } // NewRequirement is the constructor for a Requirement. // If any of these rules is violated, an error is returned: // 1. The operator can only be In, NotIn, Equals, DoubleEquals, Gt, Lt, NotEquals, Exists, or DoesNotExist. // 2. If the operator is In or NotIn, the values set must be non-empty. // 3. If the operator is Equals, DoubleEquals, or NotEquals, the values set must contain one value. // 4. If the operator is Exists or DoesNotExist, the value set must be empty. // 5. If the operator is Gt or Lt, the values set must contain only one value, which will be interpreted as an integer. // 6. The key is invalid due to its length, or sequence of characters. See validateLabelKey for more details. // // The empty string is a valid value in the input values set. // Returned error, if not nil, is guaranteed to be an aggregated field.ErrorList func NewRequirement(key string, op selection.Operator, vals []string, opts ...field.PathOption) (*Requirement, error) { var allErrs field.ErrorList path := field.ToPath(opts...) if err := validateLabelKey(key, path.Child("key")); err != nil { allErrs = append(allErrs, err) } valuePath := path.Child("values") switch op { case selection.In, selection.NotIn: if len(vals) == 0 { allErrs = append(allErrs, field.Invalid(valuePath, vals, "for 'in', 'notin' operators, values set can't be empty")) } case selection.Equals, selection.DoubleEquals, selection.NotEquals: if len(vals) != 1 { allErrs = append(allErrs, field.Invalid(valuePath, vals, "exact-match compatibility requires one single value")) } case selection.Exists, selection.DoesNotExist: if len(vals) != 0 { allErrs = append(allErrs, field.Invalid(valuePath, vals, "values set must be empty for exists and does not exist")) } case selection.GreaterThan, selection.LessThan: if len(vals) != 1 { allErrs = append(allErrs, field.Invalid(valuePath, vals, "for 'Gt', 'Lt' operators, exactly one value is required")) } for i := range vals { if _, err := strconv.ParseInt(vals[i], 10, 64); err != nil { allErrs = append(allErrs, field.Invalid(valuePath.Index(i), vals[i], "for 'Gt', 'Lt' operators, the value must be an integer")) } } default: allErrs = append(allErrs, field.NotSupported(path.Child("operator"), op, validRequirementOperators)) } for i := range vals { if err := validateLabelValue(key, vals[i], valuePath.Index(i)); err != nil { allErrs = append(allErrs, err) } } return &Requirement{key: key, operator: op, strValues: vals}, allErrs.ToAggregate() } func (r *Requirement) hasValue(value string) bool { for i := range r.strValues { if r.strValues[i] == value { return true } } return false } // Matches returns true if the Requirement matches the input Labels. // There is a match in the following cases: // 1. The operator is Exists and Labels has the Requirement's key. // 2. The operator is In, Labels has the Requirement's key and Labels' // value for that key is in Requirement's value set. // 3. The operator is NotIn, Labels has the Requirement's key and // Labels' value for that key is not in Requirement's value set. // 4. The operator is DoesNotExist or NotIn and Labels does not have the // Requirement's key. // 5. The operator is GreaterThanOperator or LessThanOperator, and Labels has // the Requirement's key and the corresponding value satisfies mathematical inequality. func (r *Requirement) Matches(ls Labels) bool { switch r.operator { case selection.In, selection.Equals, selection.DoubleEquals: if !ls.Has(r.key) { return false } return r.hasValue(ls.Get(r.key)) case selection.NotIn, selection.NotEquals: if !ls.Has(r.key) { return true } return !r.hasValue(ls.Get(r.key)) case selection.Exists: return ls.Has(r.key) case selection.DoesNotExist: return !ls.Has(r.key) case selection.GreaterThan, selection.LessThan: if !ls.Has(r.key) { return false } lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64) if err != nil { klog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err) return false } // There should be only one strValue in r.strValues, and can be converted to an integer. if len(r.strValues) != 1 { klog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r) return false } var rValue int64 for i := range r.strValues { rValue, err = strconv.ParseInt(r.strValues[i], 10, 64) if err != nil { klog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r) return false } } return (r.operator == selection.GreaterThan && lsValue > rValue) || (r.operator == selection.LessThan && lsValue < rValue) default: return false } } // Key returns requirement key func (r *Requirement) Key() string { return r.key } // Operator returns requirement operator func (r *Requirement) Operator() selection.Operator { return r.operator } // Values returns requirement values func (r *Requirement) Values() sets.String { ret := sets.String{} for i := range r.strValues { ret.Insert(r.strValues[i]) } return ret } // ValuesUnsorted returns a copy of requirement values as passed to NewRequirement without sorting. func (r *Requirement) ValuesUnsorted() []string { ret := make([]string, 0, len(r.strValues)) ret = append(ret, r.strValues...) return ret } // Equal checks the equality of requirement. func (r Requirement) Equal(x Requirement) bool { if r.key != x.key { return false } if r.operator != x.operator { return false } return slices.Equal(r.strValues, x.strValues) } // Empty returns true if the internalSelector doesn't restrict selection space func (s internalSelector) Empty() bool { if s == nil { return true } return len(s) == 0 } // String returns a human-readable string that represents this // Requirement. If called on an invalid Requirement, an error is // returned. See NewRequirement for creating a valid Requirement. func (r *Requirement) String() string { var sb strings.Builder sb.Grow( // length of r.key len(r.key) + // length of 'r.operator' + 2 spaces for the worst case ('in' and 'notin') len(r.operator) + 2 + // length of 'r.strValues' slice times. Heuristically 5 chars per word +5*len(r.strValues)) if r.operator == selection.DoesNotExist { sb.WriteString("!") } sb.WriteString(r.key) switch r.operator { case selection.Equals: sb.WriteString("=") case selection.DoubleEquals: sb.WriteString("==") case selection.NotEquals: sb.WriteString("!=") case selection.In: sb.WriteString(" in ") case selection.NotIn: sb.WriteString(" notin ") case selection.GreaterThan: sb.WriteString(">") case selection.LessThan: sb.WriteString("<") case selection.Exists, selection.DoesNotExist: return sb.String() } switch r.operator { case selection.In, selection.NotIn: sb.WriteString("(") } if len(r.strValues) == 1 { sb.WriteString(r.strValues[0]) } else { // only > 1 since == 0 prohibited by NewRequirement // normalizes value order on output, without mutating the in-memory selector representation // also avoids normalization when it is not required, and ensures we do not mutate shared data sb.WriteString(strings.Join(safeSort(r.strValues), ",")) } switch r.operator { case selection.In, selection.NotIn: sb.WriteString(")") } return sb.String() } // safeSort sorts input strings without modification func safeSort(in []string) []string { if sort.StringsAreSorted(in) { return in } out := make([]string, len(in)) copy(out, in) sort.Strings(out) return out } // Add adds requirements to the selector. It copies the current selector returning a new one func (s internalSelector) Add(reqs ...Requirement) Selector { ret := make(internalSelector, 0, len(s)+len(reqs)) ret = append(ret, s...) ret = append(ret, reqs...) sort.Sort(ByKey(ret)) return ret } // Matches for a internalSelector returns true if all // its Requirements match the input Labels. If any // Requirement does not match, false is returned. func (s internalSelector) Matches(l Labels) bool { for ix := range s { if matches := s[ix].Matches(l); !matches { return false } } return true } func (s internalSelector) Requirements() (Requirements, bool) { return Requirements(s), true } // String returns a comma-separated string of all // the internalSelector Requirements' human-readable strings. func (s internalSelector) String() string { var reqs []string for ix := range s { reqs = append(reqs, s[ix].String()) } return strings.Join(reqs, ",") } // RequiresExactMatch introspects whether a given selector requires a single specific field // to be set, and if so returns the value it requires. func (s internalSelector) RequiresExactMatch(label string) (value string, found bool) { for ix := range s { if s[ix].key == label { switch s[ix].operator { case selection.Equals, selection.DoubleEquals, selection.In: if len(s[ix].strValues) == 1 { return s[ix].strValues[0], true } } return "", false } } return "", false } // Token represents constant definition for lexer token type Token int const ( // ErrorToken represents scan error ErrorToken Token = iota // EndOfStringToken represents end of string EndOfStringToken // ClosedParToken represents close parenthesis ClosedParToken // CommaToken represents the comma CommaToken // DoesNotExistToken represents logic not DoesNotExistToken // DoubleEqualsToken represents double equals DoubleEqualsToken // EqualsToken represents equal EqualsToken // GreaterThanToken represents greater than GreaterThanToken // IdentifierToken represents identifier, e.g. keys and values IdentifierToken // InToken represents in InToken // LessThanToken represents less than LessThanToken // NotEqualsToken represents not equal NotEqualsToken // NotInToken represents not in NotInToken // OpenParToken represents open parenthesis OpenParToken ) // string2token contains the mapping between lexer Token and token literal // (except IdentifierToken, EndOfStringToken and ErrorToken since it makes no sense) var string2token = map[string]Token{ ")": ClosedParToken, ",": CommaToken, "!": DoesNotExistToken, "==": DoubleEqualsToken, "=": EqualsToken, ">": GreaterThanToken, "in": InToken, "<": LessThanToken, "!=": NotEqualsToken, "notin": NotInToken, "(": OpenParToken, } // ScannedItem contains the Token and the literal produced by the lexer. type ScannedItem struct { tok Token literal string } // isWhitespace returns true if the rune is a space, tab, or newline. func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' } // isSpecialSymbol detects if the character ch can be an operator func isSpecialSymbol(ch byte) bool { switch ch { case '=', '!', '(', ')', ',', '>', '<': return true } return false } // Lexer represents the Lexer struct for label selector. // It contains necessary informationt to tokenize the input string type Lexer struct { // s stores the string to be tokenized s string // pos is the position currently tokenized pos int } // read returns the character currently lexed // increment the position and check the buffer overflow func (l *Lexer) read() (b byte) { b = 0 if l.pos < len(l.s) { b = l.s[l.pos] l.pos++ } return b } // unread 'undoes' the last read character func (l *Lexer) unread() { l.pos-- } // scanIDOrKeyword scans string to recognize literal token (for example 'in') or an identifier. func (l *Lexer) scanIDOrKeyword() (tok Token, lit string) { var buffer []byte IdentifierLoop: for { switch ch := l.read(); { case ch == 0: break IdentifierLoop case isSpecialSymbol(ch) || isWhitespace(ch): l.unread() break IdentifierLoop default: buffer = append(buffer, ch) } } s := string(buffer) if val, ok := string2token[s]; ok { // is a literal token? return val, s } return IdentifierToken, s // otherwise is an identifier } // scanSpecialSymbol scans string starting with special symbol. // special symbol identify non literal operators. "!=", "==", "=" func (l *Lexer) scanSpecialSymbol() (Token, string) { lastScannedItem := ScannedItem{} var buffer []byte SpecialSymbolLoop: for { switch ch := l.read(); { case ch == 0: break SpecialSymbolLoop case isSpecialSymbol(ch): buffer = append(buffer, ch) if token, ok := string2token[string(buffer)]; ok { lastScannedItem = ScannedItem{tok: token, literal: string(buffer)} } else if lastScannedItem.tok != 0 { l.unread() break SpecialSymbolLoop } default: l.unread() break SpecialSymbolLoop } } if lastScannedItem.tok == 0 { return ErrorToken, fmt.Sprintf("error expected: keyword found '%s'", buffer) } return lastScannedItem.tok, lastScannedItem.literal } // skipWhiteSpaces consumes all blank characters // returning the first non blank character func (l *Lexer) skipWhiteSpaces(ch byte) byte { for { if !isWhitespace(ch) { return ch } ch = l.read() } } // Lex returns a pair of Token and the literal // literal is meaningfull only for IdentifierToken token func (l *Lexer) Lex() (tok Token, lit string) { switch ch := l.skipWhiteSpaces(l.read()); { case ch == 0: return EndOfStringToken, "" case isSpecialSymbol(ch): l.unread() return l.scanSpecialSymbol() default: l.unread() return l.scanIDOrKeyword() } } // Parser data structure contains the label selector parser data structure type Parser struct { l *Lexer scannedItems []ScannedItem position int path *field.Path } // ParserContext represents context during parsing: // some literal for example 'in' and 'notin' can be // recognized as operator for example 'x in (a)' but // it can be recognized as value for example 'value in (in)' type ParserContext int const ( // KeyAndOperator represents key and operator KeyAndOperator ParserContext = iota // Values represents values Values ) // lookahead func returns the current token and string. No increment of current position func (p *Parser) lookahead(context ParserContext) (Token, string) { tok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal if context == Values { switch tok { case InToken, NotInToken: tok = IdentifierToken } } return tok, lit } // consume returns current token and string. Increments the position func (p *Parser) consume(context ParserContext) (Token, string) { p.position++ tok, lit := p.scannedItems[p.position-1].tok, p.scannedItems[p.position-1].literal if context == Values { switch tok { case InToken, NotInToken: tok = IdentifierToken } } return tok, lit } // scan runs through the input string and stores the ScannedItem in an array // Parser can now lookahead and consume the tokens func (p *Parser) scan() { for { token, literal := p.l.Lex() p.scannedItems = append(p.scannedItems, ScannedItem{token, literal}) if token == EndOfStringToken { break } } } // parse runs the left recursive descending algorithm // on input string. It returns a list of Requirement objects. func (p *Parser) parse() (internalSelector, error) { p.scan() // init scannedItems var requirements internalSelector for { tok, lit := p.lookahead(Values) switch tok { case IdentifierToken, DoesNotExistToken: r, err := p.parseRequirement() if err != nil { return nil, fmt.Errorf("unable to parse requirement: %v", err) } requirements = append(requirements, *r) t, l := p.consume(Values) switch t { case EndOfStringToken: return requirements, nil case CommaToken: t2, l2 := p.lookahead(Values) if t2 != IdentifierToken && t2 != DoesNotExistToken { return nil, fmt.Errorf("found '%s', expected: identifier after ','", l2) } default: return nil, fmt.Errorf("found '%s', expected: ',' or 'end of string'", l) } case EndOfStringToken: return requirements, nil default: return nil, fmt.Errorf("found '%s', expected: !, identifier, or 'end of string'", lit) } } } func (p *Parser) parseRequirement() (*Requirement, error) { key, operator, err := p.parseKeyAndInferOperator() if err != nil { return nil, err } if operator == selection.Exists || operator == selection.DoesNotExist { // operator found lookahead set checked return NewRequirement(key, operator, []string{}, field.WithPath(p.path)) } operator, err = p.parseOperator() if err != nil { return nil, err } var values sets.String switch operator { case selection.In, selection.NotIn: values, err = p.parseValues() case selection.Equals, selection.DoubleEquals, selection.NotEquals, selection.GreaterThan, selection.LessThan: values, err = p.parseExactValue() } if err != nil { return nil, err } return NewRequirement(key, operator, values.List(), field.WithPath(p.path)) } // parseKeyAndInferOperator parses literals. // in case of no operator '!, in, notin, ==, =, !=' are found // the 'exists' operator is inferred func (p *Parser) parseKeyAndInferOperator() (string, selection.Operator, error) { var operator selection.Operator tok, literal := p.consume(Values) if tok == DoesNotExistToken { operator = selection.DoesNotExist tok, literal = p.consume(Values) } if tok != IdentifierToken { err := fmt.Errorf("found '%s', expected: identifier", literal) return "", "", err } if err := validateLabelKey(literal, p.path); err != nil { return "", "", err } if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken { if operator != selection.DoesNotExist { operator = selection.Exists } } return literal, operator, nil } // parseOperator returns operator and eventually matchType // matchType can be exact func (p *Parser) parseOperator() (op selection.Operator, err error) { tok, lit := p.consume(KeyAndOperator) switch tok { // DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator case InToken: op = selection.In case EqualsToken: op = selection.Equals case DoubleEqualsToken: op = selection.DoubleEquals case GreaterThanToken: op = selection.GreaterThan case LessThanToken: op = selection.LessThan case NotInToken: op = selection.NotIn case NotEqualsToken: op = selection.NotEquals default: return "", fmt.Errorf("found '%s', expected: %v", lit, strings.Join(binaryOperators, ", ")) } return op, nil } // parseValues parses the values for set based matching (x,y,z) func (p *Parser) parseValues() (sets.String, error) { tok, lit := p.consume(Values) if tok != OpenParToken { return nil, fmt.Errorf("found '%s' expected: '('", lit) } tok, lit = p.lookahead(Values) switch tok { case IdentifierToken, CommaToken: s, err := p.parseIdentifiersList() // handles general cases if err != nil { return s, err } if tok, _ = p.consume(Values); tok != ClosedParToken { return nil, fmt.Errorf("found '%s', expected: ')'", lit) } return s, nil case ClosedParToken: // handles "()" p.consume(Values) return sets.NewString(""), nil default: return nil, fmt.Errorf("found '%s', expected: ',', ')' or identifier", lit) } } // parseIdentifiersList parses a (possibly empty) list of // of comma separated (possibly empty) identifiers func (p *Parser) parseIdentifiersList() (sets.String, error) { s := sets.NewString() for { tok, lit := p.consume(Values) switch tok { case IdentifierToken: s.Insert(lit) tok2, lit2 := p.lookahead(Values) switch tok2 { case CommaToken: continue case ClosedParToken: return s, nil default: return nil, fmt.Errorf("found '%s', expected: ',' or ')'", lit2) } case CommaToken: // handled here since we can have "(," if s.Len() == 0 { s.Insert("") // to handle (, } tok2, _ := p.lookahead(Values) if tok2 == ClosedParToken { s.Insert("") // to handle ,) Double "" removed by StringSet return s, nil } if tok2 == CommaToken { p.consume(Values) s.Insert("") // to handle ,, Double "" removed by StringSet } default: // it can be operator return s, fmt.Errorf("found '%s', expected: ',', or identifier", lit) } } } // parseExactValue parses the only value for exact match style func (p *Parser) parseExactValue() (sets.String, error) { s := sets.NewString() tok, _ := p.lookahead(Values) if tok == EndOfStringToken || tok == CommaToken { s.Insert("") return s, nil } tok, lit := p.consume(Values) if tok == IdentifierToken { s.Insert(lit) return s, nil } return nil, fmt.Errorf("found '%s', expected: identifier", lit) } // Parse takes a string representing a selector and returns a selector // object, or an error. This parsing function differs from ParseSelector // as they parse different selectors with different syntaxes. // The input will cause an error if it does not follow this form: // // <selector-syntax> ::= <requirement> | <requirement> "," <selector-syntax> // <requirement> ::= [!] KEY [ <set-based-restriction> | <exact-match-restriction> ] // <set-based-restriction> ::= "" | <inclusion-exclusion> <value-set> // <inclusion-exclusion> ::= <inclusion> | <exclusion> // <exclusion> ::= "notin" // <inclusion> ::= "in" // <value-set> ::= "(" <values> ")" // <values> ::= VALUE | VALUE "," <values> // <exact-match-restriction> ::= ["="|"=="|"!="] VALUE // // KEY is a sequence of one or more characters following [ DNS_SUBDOMAIN "/" ] DNS_LABEL. Max length is 63 characters. // VALUE is a sequence of zero or more characters "([A-Za-z0-9_-\.])". Max length is 63 characters. // Delimiter is white space: (' ', '\t') // Example of valid syntax: // // "x in (foo,,baz),y,z notin ()" // // Note: // 1. Inclusion - " in " - denotes that the KEY exists and is equal to any of the // VALUEs in its requirement // 2. Exclusion - " notin " - denotes that the KEY is not equal to any // of the VALUEs in its requirement or does not exist // 3. The empty string is a valid VALUE // 4. A requirement with just a KEY - as in "y" above - denotes that // the KEY exists and can be any VALUE. // 5. A requirement with just !KEY requires that the KEY not exist. func Parse(selector string, opts ...field.PathOption) (Selector, error) { parsedSelector, err := parse(selector, field.ToPath(opts...)) if err == nil { return parsedSelector, nil } return nil, err } // parse parses the string representation of the selector and returns the internalSelector struct. // The callers of this method can then decide how to return the internalSelector struct to their // callers. This function has two callers now, one returns a Selector interface and the other // returns a list of requirements. func parse(selector string, path *field.Path) (internalSelector, error) { p := &Parser{l: &Lexer{s: selector, pos: 0}, path: path} items, err := p.parse() if err != nil { return nil, err } sort.Sort(ByKey(items)) // sort to grant determistic parsing return internalSelector(items), err } func validateLabelKey(k string, path *field.Path) *field.Error { if errs := validation.IsQualifiedName(k); len(errs) != 0 { return field.Invalid(path, k, strings.Join(errs, "; ")) } return nil } func validateLabelValue(k, v string, path *field.Path) *field.Error { if errs := validation.IsValidLabelValue(v); len(errs) != 0 { return field.Invalid(path.Key(k), v, strings.Join(errs, "; ")) } return nil } // SelectorFromSet returns a Selector which will match exactly the given Set. A // nil and empty Sets are considered equivalent to Everything(). // It does not perform any validation, which means the server will reject // the request if the Set contains invalid values. func SelectorFromSet(ls Set) Selector { return SelectorFromValidatedSet(ls) } // ValidatedSelectorFromSet returns a Selector which will match exactly the given Set. A // nil and empty Sets are considered equivalent to Everything(). // The Set is validated client-side, which allows to catch errors early. func ValidatedSelectorFromSet(ls Set) (Selector, error) { if ls == nil || len(ls) == 0 { return internalSelector{}, nil } requirements := make([]Requirement, 0, len(ls)) for label, value := range ls { r, err := NewRequirement(label, selection.Equals, []string{value}) if err != nil { return nil, err } requirements = append(requirements, *r) } // sort to have deterministic string representation sort.Sort(ByKey(requirements)) return internalSelector(requirements), nil } // SelectorFromValidatedSet returns a Selector which will match exactly the given Set. // A nil and empty Sets are considered equivalent to Everything(). // It assumes that Set is already validated and doesn't do any validation. // Note: this method copies the Set; if the Set is immutable, consider wrapping it with ValidatedSetSelector // instead, which does not copy. func SelectorFromValidatedSet(ls Set) Selector { if ls == nil || len(ls) == 0 { return internalSelector{} } requirements := make([]Requirement, 0, len(ls)) for label, value := range ls { requirements = append(requirements, Requirement{key: label, operator: selection.Equals, strValues: []string{value}}) } // sort to have deterministic string representation sort.Sort(ByKey(requirements)) return internalSelector(requirements) } // ParseToRequirements takes a string representing a selector and returns a list of // requirements. This function is suitable for those callers that perform additional // processing on selector requirements. // See the documentation for Parse() function for more details. // TODO: Consider exporting the internalSelector type instead. func ParseToRequirements(selector string, opts ...field.PathOption) ([]Requirement, error) { return parse(selector, field.ToPath(opts...)) } // ValidatedSetSelector wraps a Set, allowing it to implement the Selector interface. Unlike // Set.AsSelectorPreValidated (which copies the input Set), this type simply wraps the underlying // Set. As a result, it is substantially more efficient. A nil and empty Sets are considered // equivalent to Everything(). // // Callers MUST ensure the underlying Set is not mutated, and that it is already validated. If these // constraints are not met, Set.AsValidatedSelector should be preferred // // None of the Selector methods mutate the underlying Set, but Add() and Requirements() convert to // the less optimized version. type ValidatedSetSelector Set func (s ValidatedSetSelector) Matches(labels Labels) bool { for k, v := range s { if !labels.Has(k) || v != labels.Get(k) { return false } } return true } func (s ValidatedSetSelector) Empty() bool { return len(s) == 0 } func (s ValidatedSetSelector) String() string { keys := make([]string, 0, len(s)) for k := range s { keys = append(keys, k) } // Ensure deterministic output sort.Strings(keys) b := strings.Builder{} for i, key := range keys { v := s[key] b.Grow(len(key) + 2 + len(v)) if i != 0 { b.WriteString(",") } b.WriteString(key) b.WriteString("=") b.WriteString(v) } return b.String() } func (s ValidatedSetSelector) Add(r ...Requirement) Selector { return s.toFullSelector().Add(r...) } func (s ValidatedSetSelector) Requirements() (requirements Requirements, selectable bool) { return s.toFullSelector().Requirements() } func (s ValidatedSetSelector) DeepCopySelector() Selector { res := make(ValidatedSetSelector, len(s)) for k, v := range s { res[k] = v } return res } func (s ValidatedSetSelector) RequiresExactMatch(label string) (value string, found bool) { v, f := s[label]
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/zz_generated.deepcopy.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by deepcopy-gen. DO NOT EDIT. package labels // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Requirement) DeepCopyInto(out *Requirement) { *out = *in if in.strValues != nil { in, out := &in.strValues, &out.strValues *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Requirement. func (in *Requirement) DeepCopy() *Requirement { if in == nil { return nil } out := new(Requirement) in.DeepCopyInto(out) return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/labels.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/labels.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package labels import ( "fmt" "sort" "strings" "k8s.io/apimachinery/pkg/util/validation/field" ) // Labels allows you to present labels independently from their storage. type Labels interface { // Has returns whether the provided label exists. Has(label string) (exists bool) // Get returns the value for the provided label. Get(label string) (value string) } // Set is a map of label:value. It implements Labels. type Set map[string]string // String returns all labels listed as a human readable string. // Conveniently, exactly the format that ParseSelector takes. func (ls Set) String() string { selector := make([]string, 0, len(ls)) for key, value := range ls { selector = append(selector, key+"="+value) } // Sort for determinism. sort.StringSlice(selector).Sort() return strings.Join(selector, ",") } // Has returns whether the provided label exists in the map. func (ls Set) Has(label string) bool { _, exists := ls[label] return exists } // Get returns the value in the map for the provided label. func (ls Set) Get(label string) string { return ls[label] } // AsSelector converts labels into a selectors. It does not // perform any validation, which means the server will reject // the request if the Set contains invalid values. func (ls Set) AsSelector() Selector { return SelectorFromSet(ls) } // AsValidatedSelector converts labels into a selectors. // The Set is validated client-side, which allows to catch errors early. func (ls Set) AsValidatedSelector() (Selector, error) { return ValidatedSelectorFromSet(ls) } // AsSelectorPreValidated converts labels into a selector, but // assumes that labels are already validated and thus doesn't // perform any validation. // According to our measurements this is significantly faster // in codepaths that matter at high scale. // Note: this method copies the Set; if the Set is immutable, consider wrapping it with ValidatedSetSelector // instead, which does not copy. func (ls Set) AsSelectorPreValidated() Selector { return SelectorFromValidatedSet(ls) } // FormatLabels converts label map into plain string func FormatLabels(labelMap map[string]string) string { l := Set(labelMap).String() if l == "" { l = "<none>" } return l } // Conflicts takes 2 maps and returns true if there a key match between // the maps but the value doesn't match, and returns false in other cases func Conflicts(labels1, labels2 Set) bool { small := labels1 big := labels2 if len(labels2) < len(labels1) { small = labels2 big = labels1 } for k, v := range small { if val, match := big[k]; match { if val != v { return true } } } return false } // Merge combines given maps, and does not check for any conflicts // between the maps. In case of conflicts, second map (labels2) wins func Merge(labels1, labels2 Set) Set { mergedMap := Set{} for k, v := range labels1 { mergedMap[k] = v } for k, v := range labels2 { mergedMap[k] = v } return mergedMap } // Equals returns true if the given maps are equal func Equals(labels1, labels2 Set) bool { if len(labels1) != len(labels2) { return false } for k, v := range labels1 { value, ok := labels2[k] if !ok { return false } if value != v { return false } } return true } // ConvertSelectorToLabelsMap converts selector string to labels map // and validates keys and values func ConvertSelectorToLabelsMap(selector string, opts ...field.PathOption) (Set, error) { labelsMap := Set{} if len(selector) == 0 { return labelsMap, nil } labels := strings.Split(selector, ",") for _, label := range labels { l := strings.Split(label, "=") if len(l) != 2 { return labelsMap, fmt.Errorf("invalid selector: %s", l) } key := strings.TrimSpace(l[0]) if err := validateLabelKey(key, field.ToPath(opts...)); err != nil { return labelsMap, err } value := strings.TrimSpace(l[1]) if err := validateLabelValue(key, value, field.ToPath(opts...)); err != nil { return labelsMap, err } labelsMap[key] = value } return labelsMap, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/labels/doc.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package labels implements a simple label system, parsing and matching // selectors with sets of labels. package labels // import "k8s.io/apimachinery/pkg/labels"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/types.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/types.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 version // Info contains versioning information. // TODO: Add []string of api versions supported? It's still unclear // how we'll want to distribute that information. type Info struct { Major string `json:"major"` Minor string `json:"minor"` GitVersion string `json:"gitVersion"` GitCommit string `json:"gitCommit"` GitTreeState string `json:"gitTreeState"` BuildDate string `json:"buildDate"` GoVersion string `json:"goVersion"` Compiler string `json:"compiler"` Platform string `json:"platform"` } // String returns info as a human-friendly version string. func (info Info) String() string { return info.GitVersion }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/doc.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // +k8s:openapi-gen=true // Package version supplies the type for version information collected at build time. package version // import "k8s.io/apimachinery/pkg/version"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/helpers.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/version/helpers.go
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 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 version import ( "regexp" "strconv" "strings" ) type versionType int const ( // Bigger the version type number, higher priority it is versionTypeAlpha versionType = iota versionTypeBeta versionTypeGA ) var kubeVersionRegex = regexp.MustCompile("^v([\\d]+)(?:(alpha|beta)([\\d]+))?$") func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool) { var err error submatches := kubeVersionRegex.FindStringSubmatch(v) if len(submatches) != 4 { return 0, 0, 0, false } switch submatches[2] { case "alpha": vType = versionTypeAlpha case "beta": vType = versionTypeBeta case "": vType = versionTypeGA default: return 0, 0, 0, false } if majorVersion, err = strconv.Atoi(submatches[1]); err != nil { return 0, 0, 0, false } if vType != versionTypeGA { if minorVersion, err = strconv.Atoi(submatches[3]); err != nil { return 0, 0, 0, false } } return majorVersion, vType, minorVersion, true } // CompareKubeAwareVersionStrings compares two kube-like version strings. // Kube-like version strings are starting with a v, followed by a major version, optional "alpha" or "beta" strings // followed by a minor version (e.g. v1, v2beta1). Versions will be sorted based on GA/alpha/beta first and then major // and minor versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1. func CompareKubeAwareVersionStrings(v1, v2 string) int { if v1 == v2 { return 0 } v1major, v1type, v1minor, ok1 := parseKubeVersion(v1) v2major, v2type, v2minor, ok2 := parseKubeVersion(v2) switch { case !ok1 && !ok2: return strings.Compare(v2, v1) case !ok1 && ok2: return -1 case ok1 && !ok2: return 1 } if v1type != v2type { return int(v1type) - int(v2type) } if v1major != v2major { return v1major - v2major } return v1minor - v2minor }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "fmt" "reflect" "strings" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/naming" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" ) // Scheme defines methods for serializing and deserializing API objects, a type // registry for converting group, version, and kind information to and from Go // schemas, and mappings between Go schemas of different versions. A scheme is the // foundation for a versioned API and versioned configuration over time. // // In a Scheme, a Type is a particular Go struct, a Version is a point-in-time // identifier for a particular representation of that Type (typically backwards // compatible), a Kind is the unique name for that Type within the Version, and a // Group identifies a set of Versions, Kinds, and Types that evolve over time. An // Unversioned Type is one that is not yet formally bound to a type and is promised // to be backwards compatible (effectively a "v1" of a Type that does not expect // to break in the future). // // Schemes are not expected to change at runtime and are only threadsafe after // registration is complete. type Scheme struct { // gvkToType allows one to figure out the go type of an object with // the given version and name. gvkToType map[schema.GroupVersionKind]reflect.Type // typeToGVK allows one to find metadata for a given go object. // The reflect.Type we index by should *not* be a pointer. typeToGVK map[reflect.Type][]schema.GroupVersionKind // unversionedTypes are transformed without conversion in ConvertToVersion. unversionedTypes map[reflect.Type]schema.GroupVersionKind // unversionedKinds are the names of kinds that can be created in the context of any group // or version // TODO: resolve the status of unversioned types. unversionedKinds map[string]reflect.Type // Map from version and resource to the corresponding func to convert // resource field labels in that version to internal version. fieldLabelConversionFuncs map[schema.GroupVersionKind]FieldLabelConversionFunc // defaulterFuncs is a map to funcs to be called with an object to provide defaulting // the provided object must be a pointer. defaulterFuncs map[reflect.Type]func(interface{}) // converter stores all registered conversion functions. It also has // default converting behavior. converter *conversion.Converter // versionPriority is a map of groups to ordered lists of versions for those groups indicating the // default priorities of these versions as registered in the scheme versionPriority map[string][]string // observedVersions keeps track of the order we've seen versions during type registration observedVersions []schema.GroupVersion // schemeName is the name of this scheme. If you don't specify a name, the stack of the NewScheme caller will be used. // This is useful for error reporting to indicate the origin of the scheme. schemeName string } // FieldLabelConversionFunc converts a field selector to internal representation. type FieldLabelConversionFunc func(label, value string) (internalLabel, internalValue string, err error) // NewScheme creates a new Scheme. This scheme is pluggable by default. func NewScheme() *Scheme { s := &Scheme{ gvkToType: map[schema.GroupVersionKind]reflect.Type{}, typeToGVK: map[reflect.Type][]schema.GroupVersionKind{}, unversionedTypes: map[reflect.Type]schema.GroupVersionKind{}, unversionedKinds: map[string]reflect.Type{}, fieldLabelConversionFuncs: map[schema.GroupVersionKind]FieldLabelConversionFunc{}, defaulterFuncs: map[reflect.Type]func(interface{}){}, versionPriority: map[string][]string{}, schemeName: naming.GetNameFromCallsite(internalPackages...), } s.converter = conversion.NewConverter(nil) // Enable couple default conversions by default. utilruntime.Must(RegisterEmbeddedConversions(s)) utilruntime.Must(RegisterStringConversions(s)) return s } // Converter allows access to the converter for the scheme func (s *Scheme) Converter() *conversion.Converter { return s.converter } // AddUnversionedTypes registers the provided types as "unversioned", which means that they follow special rules. // Whenever an object of this type is serialized, it is serialized with the provided group version and is not // converted. Thus unversioned objects are expected to remain backwards compatible forever, as if they were in an // API group and version that would never be updated. // // TODO: there is discussion about removing unversioned and replacing it with objects that are manifest into // every version with particular schemas. Resolve this method at that point. func (s *Scheme) AddUnversionedTypes(version schema.GroupVersion, types ...Object) { s.addObservedVersion(version) s.AddKnownTypes(version, types...) for _, obj := range types { t := reflect.TypeOf(obj).Elem() gvk := version.WithKind(t.Name()) s.unversionedTypes[t] = gvk if old, ok := s.unversionedKinds[gvk.Kind]; ok && t != old { panic(fmt.Sprintf("%v.%v has already been registered as unversioned kind %q - kind name must be unique in scheme %q", old.PkgPath(), old.Name(), gvk, s.schemeName)) } s.unversionedKinds[gvk.Kind] = t } } // AddKnownTypes registers all types passed in 'types' as being members of version 'version'. // All objects passed to types should be pointers to structs. The name that go reports for // the struct becomes the "kind" field when encoding. Version may not be empty - use the // APIVersionInternal constant if you have a type that does not have a formal version. func (s *Scheme) AddKnownTypes(gv schema.GroupVersion, types ...Object) { s.addObservedVersion(gv) for _, obj := range types { t := reflect.TypeOf(obj) if t.Kind() != reflect.Pointer { panic("All types must be pointers to structs.") } t = t.Elem() s.AddKnownTypeWithName(gv.WithKind(t.Name()), obj) } } // AddKnownTypeWithName is like AddKnownTypes, but it lets you specify what this type should // be encoded as. Useful for testing when you don't want to make multiple packages to define // your structs. Version may not be empty - use the APIVersionInternal constant if you have a // type that does not have a formal version. func (s *Scheme) AddKnownTypeWithName(gvk schema.GroupVersionKind, obj Object) { s.addObservedVersion(gvk.GroupVersion()) t := reflect.TypeOf(obj) if len(gvk.Version) == 0 { panic(fmt.Sprintf("version is required on all types: %s %v", gvk, t)) } if t.Kind() != reflect.Pointer { panic("All types must be pointers to structs.") } t = t.Elem() if t.Kind() != reflect.Struct { panic("All types must be pointers to structs.") } if oldT, found := s.gvkToType[gvk]; found && oldT != t { panic(fmt.Sprintf("Double registration of different types for %v: old=%v.%v, new=%v.%v in scheme %q", gvk, oldT.PkgPath(), oldT.Name(), t.PkgPath(), t.Name(), s.schemeName)) } s.gvkToType[gvk] = t for _, existingGvk := range s.typeToGVK[t] { if existingGvk == gvk { return } } s.typeToGVK[t] = append(s.typeToGVK[t], gvk) // if the type implements DeepCopyInto(<obj>), register a self-conversion if m := reflect.ValueOf(obj).MethodByName("DeepCopyInto"); m.IsValid() && m.Type().NumIn() == 1 && m.Type().NumOut() == 0 && m.Type().In(0) == reflect.TypeOf(obj) { if err := s.AddGeneratedConversionFunc(obj, obj, func(a, b interface{}, scope conversion.Scope) error { // copy a to b reflect.ValueOf(a).MethodByName("DeepCopyInto").Call([]reflect.Value{reflect.ValueOf(b)}) // clear TypeMeta to match legacy reflective conversion b.(Object).GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) return nil }); err != nil { panic(err) } } } // KnownTypes returns the types known for the given version. func (s *Scheme) KnownTypes(gv schema.GroupVersion) map[string]reflect.Type { types := make(map[string]reflect.Type) for gvk, t := range s.gvkToType { if gv != gvk.GroupVersion() { continue } types[gvk.Kind] = t } return types } // VersionsForGroupKind returns the versions that a particular GroupKind can be converted to within the given group. // A GroupKind might be converted to a different group. That information is available in EquivalentResourceMapper. func (s *Scheme) VersionsForGroupKind(gk schema.GroupKind) []schema.GroupVersion { availableVersions := []schema.GroupVersion{} for gvk := range s.gvkToType { if gk != gvk.GroupKind() { continue } availableVersions = append(availableVersions, gvk.GroupVersion()) } // order the return for stability ret := []schema.GroupVersion{} for _, version := range s.PrioritizedVersionsForGroup(gk.Group) { for _, availableVersion := range availableVersions { if version != availableVersion { continue } ret = append(ret, availableVersion) } } return ret } // AllKnownTypes returns the all known types. func (s *Scheme) AllKnownTypes() map[schema.GroupVersionKind]reflect.Type { return s.gvkToType } // ObjectKinds returns all possible group,version,kind of the go object, true if the // object is considered unversioned, or an error if it's not a pointer or is unregistered. func (s *Scheme) ObjectKinds(obj Object) ([]schema.GroupVersionKind, bool, error) { // Unstructured objects are always considered to have their declared GVK if _, ok := obj.(Unstructured); ok { // we require that the GVK be populated in order to recognize the object gvk := obj.GetObjectKind().GroupVersionKind() if len(gvk.Kind) == 0 { return nil, false, NewMissingKindErr("unstructured object has no kind") } if len(gvk.Version) == 0 { return nil, false, NewMissingVersionErr("unstructured object has no version") } return []schema.GroupVersionKind{gvk}, false, nil } v, err := conversion.EnforcePtr(obj) if err != nil { return nil, false, err } t := v.Type() gvks, ok := s.typeToGVK[t] if !ok { return nil, false, NewNotRegisteredErrForType(s.schemeName, t) } _, unversionedType := s.unversionedTypes[t] return gvks, unversionedType, nil } // Recognizes returns true if the scheme is able to handle the provided group,version,kind // of an object. func (s *Scheme) Recognizes(gvk schema.GroupVersionKind) bool { _, exists := s.gvkToType[gvk] return exists } func (s *Scheme) IsUnversioned(obj Object) (bool, bool) { v, err := conversion.EnforcePtr(obj) if err != nil { return false, false } t := v.Type() if _, ok := s.typeToGVK[t]; !ok { return false, false } _, ok := s.unversionedTypes[t] return ok, true } // New returns a new API object of the given version and name, or an error if it hasn't // been registered. The version and kind fields must be specified. func (s *Scheme) New(kind schema.GroupVersionKind) (Object, error) { if t, exists := s.gvkToType[kind]; exists { return reflect.New(t).Interface().(Object), nil } if t, exists := s.unversionedKinds[kind.Kind]; exists { return reflect.New(t).Interface().(Object), nil } return nil, NewNotRegisteredErrForKind(s.schemeName, kind) } // AddIgnoredConversionType identifies a pair of types that should be skipped by // conversion (because the data inside them is explicitly dropped during // conversion). func (s *Scheme) AddIgnoredConversionType(from, to interface{}) error { return s.converter.RegisterIgnoredConversion(from, to) } // AddConversionFunc registers a function that converts between a and b by passing objects of those // types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce // any other guarantee. func (s *Scheme) AddConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error { return s.converter.RegisterUntypedConversionFunc(a, b, fn) } // AddGeneratedConversionFunc registers a function that converts between a and b by passing objects of those // types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce // any other guarantee. func (s *Scheme) AddGeneratedConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error { return s.converter.RegisterGeneratedUntypedConversionFunc(a, b, fn) } // AddFieldLabelConversionFunc adds a conversion function to convert field selectors // of the given kind from the given version to internal version representation. func (s *Scheme) AddFieldLabelConversionFunc(gvk schema.GroupVersionKind, conversionFunc FieldLabelConversionFunc) error { s.fieldLabelConversionFuncs[gvk] = conversionFunc return nil } // AddTypeDefaultingFunc registers a function that is passed a pointer to an // object and can default fields on the object. These functions will be invoked // when Default() is called. The function will never be called unless the // defaulted object matches srcType. If this function is invoked twice with the // same srcType, the fn passed to the later call will be used instead. func (s *Scheme) AddTypeDefaultingFunc(srcType Object, fn func(interface{})) { s.defaulterFuncs[reflect.TypeOf(srcType)] = fn } // Default sets defaults on the provided Object. func (s *Scheme) Default(src Object) { if fn, ok := s.defaulterFuncs[reflect.TypeOf(src)]; ok { fn(src) } } // Convert will attempt to convert in into out. Both must be pointers. For easy // testing of conversion functions. Returns an error if the conversion isn't // possible. You can call this with types that haven't been registered (for example, // a to test conversion of types that are nested within registered types). The // context interface is passed to the convertor. Convert also supports Unstructured // types and will convert them intelligently. func (s *Scheme) Convert(in, out interface{}, context interface{}) error { unstructuredIn, okIn := in.(Unstructured) unstructuredOut, okOut := out.(Unstructured) switch { case okIn && okOut: // converting unstructured input to an unstructured output is a straight copy - unstructured // is a "smart holder" and the contents are passed by reference between the two objects unstructuredOut.SetUnstructuredContent(unstructuredIn.UnstructuredContent()) return nil case okOut: // if the output is an unstructured object, use the standard Go type to unstructured // conversion. The object must not be internal. obj, ok := in.(Object) if !ok { return fmt.Errorf("unable to convert object type %T to Unstructured, must be a runtime.Object", in) } gvks, unversioned, err := s.ObjectKinds(obj) if err != nil { return err } gvk := gvks[0] // if no conversion is necessary, convert immediately if unversioned || gvk.Version != APIVersionInternal { content, err := DefaultUnstructuredConverter.ToUnstructured(in) if err != nil { return err } unstructuredOut.SetUnstructuredContent(content) unstructuredOut.GetObjectKind().SetGroupVersionKind(gvk) return nil } // attempt to convert the object to an external version first. target, ok := context.(GroupVersioner) if !ok { return fmt.Errorf("unable to convert the internal object type %T to Unstructured without providing a preferred version to convert to", in) } // Convert is implicitly unsafe, so we don't need to perform a safe conversion versioned, err := s.UnsafeConvertToVersion(obj, target) if err != nil { return err } content, err := DefaultUnstructuredConverter.ToUnstructured(versioned) if err != nil { return err } unstructuredOut.SetUnstructuredContent(content) return nil case okIn: // converting an unstructured object to any type is modeled by first converting // the input to a versioned type, then running standard conversions typed, err := s.unstructuredToTyped(unstructuredIn) if err != nil { return err } in = typed } meta := s.generateConvertMeta(in) meta.Context = context return s.converter.Convert(in, out, meta) } // ConvertFieldLabel alters the given field label and value for an kind field selector from // versioned representation to an unversioned one or returns an error. func (s *Scheme) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) { conversionFunc, ok := s.fieldLabelConversionFuncs[gvk] if !ok { return DefaultMetaV1FieldSelectorConversion(label, value) } return conversionFunc(label, value) } // ConvertToVersion attempts to convert an input object to its matching Kind in another // version within this scheme. Will return an error if the provided version does not // contain the inKind (or a mapping by name defined with AddKnownTypeWithName). Will also // return an error if the conversion does not result in a valid Object being // returned. Passes target down to the conversion methods as the Context on the scope. func (s *Scheme) ConvertToVersion(in Object, target GroupVersioner) (Object, error) { return s.convertToVersion(true, in, target) } // UnsafeConvertToVersion will convert in to the provided target if such a conversion is possible, // but does not guarantee the output object does not share fields with the input object. It attempts to be as // efficient as possible when doing conversion. func (s *Scheme) UnsafeConvertToVersion(in Object, target GroupVersioner) (Object, error) { return s.convertToVersion(false, in, target) } // convertToVersion handles conversion with an optional copy. func (s *Scheme) convertToVersion(copy bool, in Object, target GroupVersioner) (Object, error) { var t reflect.Type if u, ok := in.(Unstructured); ok { typed, err := s.unstructuredToTyped(u) if err != nil { return nil, err } in = typed // unstructuredToTyped returns an Object, which must be a pointer to a struct. t = reflect.TypeOf(in).Elem() } else { // determine the incoming kinds with as few allocations as possible. t = reflect.TypeOf(in) if t.Kind() != reflect.Pointer { return nil, fmt.Errorf("only pointer types may be converted: %v", t) } t = t.Elem() if t.Kind() != reflect.Struct { return nil, fmt.Errorf("only pointers to struct types may be converted: %v", t) } } kinds, ok := s.typeToGVK[t] if !ok || len(kinds) == 0 { return nil, NewNotRegisteredErrForType(s.schemeName, t) } gvk, ok := target.KindForGroupVersionKinds(kinds) if !ok { // try to see if this type is listed as unversioned (for legacy support) // TODO: when we move to server API versions, we should completely remove the unversioned concept if unversionedKind, ok := s.unversionedTypes[t]; ok { if gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{unversionedKind}); ok { return copyAndSetTargetKind(copy, in, gvk) } return copyAndSetTargetKind(copy, in, unversionedKind) } return nil, NewNotRegisteredErrForTarget(s.schemeName, t, target) } // target wants to use the existing type, set kind and return (no conversion necessary) for _, kind := range kinds { if gvk == kind { return copyAndSetTargetKind(copy, in, gvk) } } // type is unversioned, no conversion necessary if unversionedKind, ok := s.unversionedTypes[t]; ok { if gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{unversionedKind}); ok { return copyAndSetTargetKind(copy, in, gvk) } return copyAndSetTargetKind(copy, in, unversionedKind) } out, err := s.New(gvk) if err != nil { return nil, err } if copy { in = in.DeepCopyObject() } meta := s.generateConvertMeta(in) meta.Context = target if err := s.converter.Convert(in, out, meta); err != nil { return nil, err } setTargetKind(out, gvk) return out, nil } // unstructuredToTyped attempts to transform an unstructured object to a typed // object if possible. It will return an error if conversion is not possible, or the versioned // Go form of the object. Note that this conversion will lose fields. func (s *Scheme) unstructuredToTyped(in Unstructured) (Object, error) { // the type must be something we recognize gvks, _, err := s.ObjectKinds(in) if err != nil { return nil, err } typed, err := s.New(gvks[0]) if err != nil { return nil, err } if err := DefaultUnstructuredConverter.FromUnstructured(in.UnstructuredContent(), typed); err != nil { return nil, fmt.Errorf("unable to convert unstructured object to %v: %v", gvks[0], err) } return typed, nil } // generateConvertMeta constructs the meta value we pass to Convert. func (s *Scheme) generateConvertMeta(in interface{}) *conversion.Meta { return s.converter.DefaultMeta(reflect.TypeOf(in)) } // copyAndSetTargetKind performs a conditional copy before returning the object, or an error if copy was not successful. func copyAndSetTargetKind(copy bool, obj Object, kind schema.GroupVersionKind) (Object, error) { if copy { obj = obj.DeepCopyObject() } setTargetKind(obj, kind) return obj, nil } // setTargetKind sets the kind on an object, taking into account whether the target kind is the internal version. func setTargetKind(obj Object, kind schema.GroupVersionKind) { if kind.Version == APIVersionInternal { // internal is a special case // TODO: look at removing the need to special case this obj.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) return } obj.GetObjectKind().SetGroupVersionKind(kind) } // SetVersionPriority allows specifying a precise order of priority. All specified versions must be in the same group, // and the specified order overwrites any previously specified order for this group func (s *Scheme) SetVersionPriority(versions ...schema.GroupVersion) error { groups := sets.String{} order := []string{} for _, version := range versions { if len(version.Version) == 0 || version.Version == APIVersionInternal { return fmt.Errorf("internal versions cannot be prioritized: %v", version) } groups.Insert(version.Group) order = append(order, version.Version) } if len(groups) != 1 { return fmt.Errorf("must register versions for exactly one group: %v", strings.Join(groups.List(), ", ")) } s.versionPriority[groups.List()[0]] = order return nil } // PrioritizedVersionsForGroup returns versions for a single group in priority order func (s *Scheme) PrioritizedVersionsForGroup(group string) []schema.GroupVersion { ret := []schema.GroupVersion{} for _, version := range s.versionPriority[group] { ret = append(ret, schema.GroupVersion{Group: group, Version: version}) } for _, observedVersion := range s.observedVersions { if observedVersion.Group != group { continue } found := false for _, existing := range ret { if existing == observedVersion { found = true break } } if !found { ret = append(ret, observedVersion) } } return ret } // PrioritizedVersionsAllGroups returns all known versions in their priority order. Groups are random, but // versions for a single group are prioritized func (s *Scheme) PrioritizedVersionsAllGroups() []schema.GroupVersion { ret := []schema.GroupVersion{} for group, versions := range s.versionPriority { for _, version := range versions { ret = append(ret, schema.GroupVersion{Group: group, Version: version}) } } for _, observedVersion := range s.observedVersions { found := false for _, existing := range ret { if existing == observedVersion { found = true break } } if !found { ret = append(ret, observedVersion) } } return ret } // PreferredVersionAllGroups returns the most preferred version for every group. // group ordering is random. func (s *Scheme) PreferredVersionAllGroups() []schema.GroupVersion { ret := []schema.GroupVersion{} for group, versions := range s.versionPriority { for _, version := range versions { ret = append(ret, schema.GroupVersion{Group: group, Version: version}) break } } for _, observedVersion := range s.observedVersions { found := false for _, existing := range ret { if existing.Group == observedVersion.Group { found = true break } } if !found { ret = append(ret, observedVersion) } } return ret } // IsGroupRegistered returns true if types for the group have been registered with the scheme func (s *Scheme) IsGroupRegistered(group string) bool { for _, observedVersion := range s.observedVersions { if observedVersion.Group == group { return true } } return false } // IsVersionRegistered returns true if types for the version have been registered with the scheme func (s *Scheme) IsVersionRegistered(version schema.GroupVersion) bool { for _, observedVersion := range s.observedVersions { if observedVersion == version { return true } } return false } func (s *Scheme) addObservedVersion(version schema.GroupVersion) { if len(version.Version) == 0 || version.Version == APIVersionInternal { return } for _, observedVersion := range s.observedVersions { if observedVersion == version { return } } s.observedVersions = append(s.observedVersions, version) } func (s *Scheme) Name() string { return s.schemeName } // internalPackages are packages that ignored when creating a default reflector name. These packages are in the common // call chains to NewReflector, so they'd be low entropy names for reflectors var internalPackages = []string{"k8s.io/apimachinery/pkg/runtime/scheme.go"}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/helper.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/helper.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "fmt" "io" "reflect" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/errors" ) // unsafeObjectConvertor implements ObjectConvertor using the unsafe conversion path. type unsafeObjectConvertor struct { *Scheme } var _ ObjectConvertor = unsafeObjectConvertor{} // ConvertToVersion converts in to the provided outVersion without copying the input first, which // is only safe if the output object is not mutated or reused. func (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion GroupVersioner) (Object, error) { return c.Scheme.UnsafeConvertToVersion(in, outVersion) } // UnsafeObjectConvertor performs object conversion without copying the object structure, // for use when the converted object will not be reused or mutated. Primarily for use within // versioned codecs, which use the external object for serialization but do not return it. func UnsafeObjectConvertor(scheme *Scheme) ObjectConvertor { return unsafeObjectConvertor{scheme} } // SetField puts the value of src, into fieldName, which must be a member of v. // The value of src must be assignable to the field. func SetField(src interface{}, v reflect.Value, fieldName string) error { field := v.FieldByName(fieldName) if !field.IsValid() { return fmt.Errorf("couldn't find %v field in %T", fieldName, v.Interface()) } srcValue := reflect.ValueOf(src) if srcValue.Type().AssignableTo(field.Type()) { field.Set(srcValue) return nil } if srcValue.Type().ConvertibleTo(field.Type()) { field.Set(srcValue.Convert(field.Type())) return nil } return fmt.Errorf("couldn't assign/convert %v to %v", srcValue.Type(), field.Type()) } // Field puts the value of fieldName, which must be a member of v, into dest, // which must be a variable to which this field's value can be assigned. func Field(v reflect.Value, fieldName string, dest interface{}) error { field := v.FieldByName(fieldName) if !field.IsValid() { return fmt.Errorf("couldn't find %v field in %T", fieldName, v.Interface()) } destValue, err := conversion.EnforcePtr(dest) if err != nil { return err } if field.Type().AssignableTo(destValue.Type()) { destValue.Set(field) return nil } if field.Type().ConvertibleTo(destValue.Type()) { destValue.Set(field.Convert(destValue.Type())) return nil } return fmt.Errorf("couldn't assign/convert %v to %v", field.Type(), destValue.Type()) } // FieldPtr puts the address of fieldName, which must be a member of v, // into dest, which must be an address of a variable to which this field's // address can be assigned. func FieldPtr(v reflect.Value, fieldName string, dest interface{}) error { field := v.FieldByName(fieldName) if !field.IsValid() { return fmt.Errorf("couldn't find %v field in %T", fieldName, v.Interface()) } v, err := conversion.EnforcePtr(dest) if err != nil { return err } field = field.Addr() if field.Type().AssignableTo(v.Type()) { v.Set(field) return nil } if field.Type().ConvertibleTo(v.Type()) { v.Set(field.Convert(v.Type())) return nil } return fmt.Errorf("couldn't assign/convert %v to %v", field.Type(), v.Type()) } // EncodeList ensures that each object in an array is converted to a Unknown{} in serialized form. // TODO: accept a content type. func EncodeList(e Encoder, objects []Object) error { var errs []error for i := range objects { data, err := Encode(e, objects[i]) if err != nil { errs = append(errs, err) continue } // TODO: Set ContentEncoding and ContentType. objects[i] = &Unknown{Raw: data} } return errors.NewAggregate(errs) } func decodeListItem(obj *Unknown, decoders []Decoder) (Object, error) { for _, decoder := range decoders { // TODO: Decode based on ContentType. obj, err := Decode(decoder, obj.Raw) if err != nil { if IsNotRegisteredError(err) { continue } return nil, err } return obj, nil } // could not decode, so leave the object as Unknown, but give the decoders the // chance to set Unknown.TypeMeta if it is available. for _, decoder := range decoders { if err := DecodeInto(decoder, obj.Raw, obj); err == nil { return obj, nil } } return obj, nil } // DecodeList alters the list in place, attempting to decode any objects found in // the list that have the Unknown type. Any errors that occur are returned // after the entire list is processed. Decoders are tried in order. func DecodeList(objects []Object, decoders ...Decoder) []error { errs := []error(nil) for i, obj := range objects { switch t := obj.(type) { case *Unknown: decoded, err := decodeListItem(t, decoders) if err != nil { errs = append(errs, err) break } objects[i] = decoded } } return errs } // MultiObjectTyper returns the types of objects across multiple schemes in order. type MultiObjectTyper []ObjectTyper var _ ObjectTyper = MultiObjectTyper{} func (m MultiObjectTyper) ObjectKinds(obj Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error) { for _, t := range m { gvks, unversionedType, err = t.ObjectKinds(obj) if err == nil { return } } return } func (m MultiObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool { for _, t := range m { if t.Recognizes(gvk) { return true } } return false } // SetZeroValue would set the object of objPtr to zero value of its type. func SetZeroValue(objPtr Object) error { v, err := conversion.EnforcePtr(objPtr) if err != nil { return err } v.Set(reflect.Zero(v.Type())) return nil } // DefaultFramer is valid for any stream that can read objects serially without // any separation in the stream. var DefaultFramer = defaultFramer{} type defaultFramer struct{} func (defaultFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser { return r } func (defaultFramer) NewFrameWriter(w io.Writer) io.Writer { return w } // WithVersionEncoder serializes an object and ensures the GVK is set. type WithVersionEncoder struct { Version GroupVersioner Encoder ObjectTyper } // Encode does not do conversion. It sets the gvk during serialization. func (e WithVersionEncoder) Encode(obj Object, stream io.Writer) error { gvks, _, err := e.ObjectTyper.ObjectKinds(obj) if err != nil { if IsNotRegisteredError(err) { return e.Encoder.Encode(obj, stream) } return err } kind := obj.GetObjectKind() oldGVK := kind.GroupVersionKind() gvk := gvks[0] if e.Version != nil { preferredGVK, ok := e.Version.KindForGroupVersionKinds(gvks) if ok { gvk = preferredGVK } } // The gvk only needs to be set if not already as desired. if gvk != oldGVK { kind.SetGroupVersionKind(gvk) defer kind.SetGroupVersionKind(oldGVK) } return e.Encoder.Encode(obj, stream) } // WithoutVersionDecoder clears the group version kind of a deserialized object. type WithoutVersionDecoder struct { Decoder } // Decode does not do conversion. It removes the gvk during deserialization. func (d WithoutVersionDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) { obj, gvk, err := d.Decoder.Decode(data, defaults, into) if obj != nil { kind := obj.GetObjectKind() // clearing the gvk is just a convention of a codec kind.SetGroupVersionKind(schema.GroupVersionKind{}) } return obj, gvk, err } type encoderWithAllocator struct { encoder EncoderWithAllocator memAllocator MemoryAllocator } // NewEncoderWithAllocator returns a new encoder func NewEncoderWithAllocator(e EncoderWithAllocator, a MemoryAllocator) Encoder { return &encoderWithAllocator{ encoder: e, memAllocator: a, } } // Encode writes the provided object to the nested writer func (e *encoderWithAllocator) Encode(obj Object, w io.Writer) error { return e.encoder.EncodeWithAllocator(obj, w, e.memAllocator) } // Identifier returns identifier of this encoder. func (e *encoderWithAllocator) Identifier() Identifier { return e.encoder.Identifier() } type nondeterministicEncoderToEncoderAdapter struct { NondeterministicEncoder } func (e nondeterministicEncoderToEncoderAdapter) Encode(obj Object, w io.Writer) error { return e.EncodeNondeterministic(obj, w) } // UseNondeterministicEncoding returns an Encoder that encodes objects using the provided Encoder's // EncodeNondeterministic method if it implements NondeterministicEncoder, otherwise it returns the // provided Encoder as-is. func UseNondeterministicEncoding(encoder Encoder) Encoder { if nondeterministic, ok := encoder.(NondeterministicEncoder); ok { return nondeterministicEncoderToEncoderAdapter{nondeterministic} } return encoder }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/zz_generated.deepcopy.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by deepcopy-gen. DO NOT EDIT. package runtime // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RawExtension) DeepCopyInto(out *RawExtension) { *out = *in if in.Raw != nil { in, out := &in.Raw, &out.Raw *out = make([]byte, len(*in)) copy(*out, *in) } if in.Object != nil { out.Object = in.Object.DeepCopyObject() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RawExtension. func (in *RawExtension) DeepCopy() *RawExtension { if in == nil { return nil } out := new(RawExtension) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Unknown) DeepCopyInto(out *Unknown) { *out = *in out.TypeMeta = in.TypeMeta 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 Unknown. func (in *Unknown) DeepCopy() *Unknown { if in == nil { return nil } out := new(Unknown) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new Object. func (in *Unknown) DeepCopyObject() Object { if c := in.DeepCopy(); c != nil { return c } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/error.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/error.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "fmt" "reflect" "strings" "k8s.io/apimachinery/pkg/runtime/schema" ) type notRegisteredErr struct { schemeName string gvk schema.GroupVersionKind target GroupVersioner t reflect.Type } func NewNotRegisteredErrForKind(schemeName string, gvk schema.GroupVersionKind) error { return &notRegisteredErr{schemeName: schemeName, gvk: gvk} } func NewNotRegisteredErrForType(schemeName string, t reflect.Type) error { return &notRegisteredErr{schemeName: schemeName, t: t} } func NewNotRegisteredErrForTarget(schemeName string, t reflect.Type, target GroupVersioner) error { return &notRegisteredErr{schemeName: schemeName, t: t, target: target} } func NewNotRegisteredGVKErrForTarget(schemeName string, gvk schema.GroupVersionKind, target GroupVersioner) error { return &notRegisteredErr{schemeName: schemeName, gvk: gvk, target: target} } func (k *notRegisteredErr) Error() string { if k.t != nil && k.target != nil { return fmt.Sprintf("%v is not suitable for converting to %q in scheme %q", k.t, k.target, k.schemeName) } nullGVK := schema.GroupVersionKind{} if k.gvk != nullGVK && k.target != nil { return fmt.Sprintf("%q is not suitable for converting to %q in scheme %q", k.gvk.GroupVersion(), k.target, k.schemeName) } if k.t != nil { return fmt.Sprintf("no kind is registered for the type %v in scheme %q", k.t, k.schemeName) } if len(k.gvk.Kind) == 0 { return fmt.Sprintf("no version %q has been registered in scheme %q", k.gvk.GroupVersion(), k.schemeName) } if k.gvk.Version == APIVersionInternal { return fmt.Sprintf("no kind %q is registered for the internal version of group %q in scheme %q", k.gvk.Kind, k.gvk.Group, k.schemeName) } return fmt.Sprintf("no kind %q is registered for version %q in scheme %q", k.gvk.Kind, k.gvk.GroupVersion(), k.schemeName) } // IsNotRegisteredError returns true if the error indicates the provided // object or input data is not registered. func IsNotRegisteredError(err error) bool { if err == nil { return false } _, ok := err.(*notRegisteredErr) return ok } type missingKindErr struct { data string } func NewMissingKindErr(data string) error { return &missingKindErr{data} } func (k *missingKindErr) Error() string { return fmt.Sprintf("Object 'Kind' is missing in '%s'", k.data) } // IsMissingKind returns true if the error indicates that the provided object // is missing a 'Kind' field. func IsMissingKind(err error) bool { if err == nil { return false } _, ok := err.(*missingKindErr) return ok } type missingVersionErr struct { data string } func NewMissingVersionErr(data string) error { return &missingVersionErr{data} } func (k *missingVersionErr) Error() string { return fmt.Sprintf("Object 'apiVersion' is missing in '%s'", k.data) } // IsMissingVersion returns true if the error indicates that the provided object // is missing a 'Version' field. func IsMissingVersion(err error) bool { if err == nil { return false } _, ok := err.(*missingVersionErr) return ok } // strictDecodingError is a base error type that is returned by a strict Decoder such // as UniversalStrictDecoder. type strictDecodingError struct { errors []error } // NewStrictDecodingError creates a new strictDecodingError object. func NewStrictDecodingError(errors []error) error { return &strictDecodingError{ errors: errors, } } func (e *strictDecodingError) Error() string { var s strings.Builder s.WriteString("strict decoding error: ") for i, err := range e.errors { if i != 0 { s.WriteString(", ") } s.WriteString(err.Error()) } return s.String() } func (e *strictDecodingError) Errors() []error { return e.errors } // IsStrictDecodingError returns true if the error indicates that the provided object // strictness violations. func IsStrictDecodingError(err error) bool { if err == nil { return false } _, ok := err.(*strictDecodingError) return ok } // AsStrictDecodingError returns a strict decoding error // containing all the strictness violations. func AsStrictDecodingError(err error) (*strictDecodingError, bool) { if err == nil { return nil, false } strictErr, ok := err.(*strictDecodingError) return strictErr, ok }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/types.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/types.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime // Note that the types provided in this file are not versioned and are intended to be // safe to use from within all versions of every API object. // TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type, // like this: // // type MyAwesomeAPIObject struct { // runtime.TypeMeta `json:",inline"` // ... // other fields // } // // func (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind // // TypeMeta is provided here for convenience. You may use it directly from this package or define // your own with the same fields. // // +k8s:deepcopy-gen=false // +protobuf=true // +k8s:openapi-gen=true type TypeMeta struct { // +optional APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty" protobuf:"bytes,1,opt,name=apiVersion"` // +optional Kind string `json:"kind,omitempty" yaml:"kind,omitempty" protobuf:"bytes,2,opt,name=kind"` } const ( ContentTypeJSON string = "application/json" ContentTypeYAML string = "application/yaml" ContentTypeProtobuf string = "application/vnd.kubernetes.protobuf" ContentTypeCBOR string = "application/cbor" // RFC 8949 ContentTypeCBORSequence string = "application/cbor-seq" // RFC 8742 ) // RawExtension is used to hold extensions in external versions. // // To use this, make a field which has RawExtension as its type in your external, versioned // struct, and Object in your internal struct. You also need to register your // various plugin types. // // // Internal package: // // type MyAPIObject struct { // runtime.TypeMeta `json:",inline"` // MyPlugin runtime.Object `json:"myPlugin"` // } // // type PluginA struct { // AOption string `json:"aOption"` // } // // // External package: // // type MyAPIObject struct { // runtime.TypeMeta `json:",inline"` // MyPlugin runtime.RawExtension `json:"myPlugin"` // } // // type PluginA struct { // AOption string `json:"aOption"` // } // // // On the wire, the JSON will look something like this: // // { // "kind":"MyAPIObject", // "apiVersion":"v1", // "myPlugin": { // "kind":"PluginA", // "aOption":"foo", // }, // } // // So what happens? Decode first uses json or yaml to unmarshal the serialized data into // your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked. // The next step is to copy (using pkg/conversion) into the internal struct. The runtime // package's DefaultScheme has conversion functions installed which will unpack the // JSON stored in RawExtension, turning it into the correct object type, and storing it // in the Object. (TODO: In the case where the object is of an unknown type, a // runtime.Unknown object will be created and stored.) // // +k8s:deepcopy-gen=true // +protobuf=true // +k8s:openapi-gen=true type RawExtension struct { // Raw is the underlying serialization of this object. // // TODO: Determine how to detect ContentType and ContentEncoding of 'Raw' data. Raw []byte `json:"-" protobuf:"bytes,1,opt,name=raw"` // Object can hold a representation of this extension - useful for working with versioned // structs. Object Object `json:"-"` } // Unknown allows api objects with unknown types to be passed-through. This can be used // to deal with the API objects from a plug-in. Unknown objects still have functioning // TypeMeta features-- kind, version, etc. // TODO: Make this object have easy access to field based accessors and settors for // metadata and field mutatation. // // +k8s:deepcopy-gen=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +protobuf=true // +k8s:openapi-gen=true type Unknown struct { TypeMeta `json:",inline" protobuf:"bytes,1,opt,name=typeMeta"` // Raw will hold the complete serialized object which couldn't be matched // with a registered type. Most likely, nothing should be done with this // except for passing it through the system. Raw []byte `json:"-" protobuf:"bytes,2,opt,name=raw"` // ContentEncoding is encoding used to encode 'Raw' data. // Unspecified means no encoding. ContentEncoding string `protobuf:"bytes,3,opt,name=contentEncoding"` // ContentType is serialization method used to serialize 'Raw'. // Unspecified means ContentTypeJSON. ContentType string `protobuf:"bytes,4,opt,name=contentType"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "io" "net/url" "k8s.io/apimachinery/pkg/runtime/schema" ) const ( // APIVersionInternal may be used if you are registering a type that should not // be considered stable or serialized - it is a convention only and has no // special behavior in this package. APIVersionInternal = "__internal" ) // GroupVersioner refines a set of possible conversion targets into a single option. type GroupVersioner interface { // KindForGroupVersionKinds returns a desired target group version kind for the given input, or returns ok false if no // target is known. In general, if the return target is not in the input list, the caller is expected to invoke // Scheme.New(target) and then perform a conversion between the current Go type and the destination Go type. // Sophisticated implementations may use additional information about the input kinds to pick a destination kind. KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (target schema.GroupVersionKind, ok bool) // Identifier returns string representation of the object. // Identifiers of two different encoders should be equal only if for every input // kinds they return the same result. Identifier() string } // Identifier represents an identifier. // Identitier of two different objects should be equal if and only if for every // input the output they produce is exactly the same. type Identifier string // Encoder writes objects to a serialized form type Encoder interface { // Encode writes an object to a stream. Implementations may return errors if the versions are // incompatible, or if no conversion is defined. Encode(obj Object, w io.Writer) error // Identifier returns an identifier of the encoder. // Identifiers of two different encoders should be equal if and only if for every input // object it will be encoded to the same representation by both of them. // // Identifier is intended for use with CacheableObject#CacheEncode method. In order to // correctly handle CacheableObject, Encode() method should look similar to below, where // doEncode() is the encoding logic of implemented encoder: // func (e *MyEncoder) Encode(obj Object, w io.Writer) error { // if co, ok := obj.(CacheableObject); ok { // return co.CacheEncode(e.Identifier(), e.doEncode, w) // } // return e.doEncode(obj, w) // } Identifier() Identifier } // NondeterministicEncoder is implemented by Encoders that can serialize objects more efficiently in // cases where the output does not need to be deterministic. type NondeterministicEncoder interface { Encoder // EncodeNondeterministic writes an object to the stream. Unlike the Encode method of // Encoder, EncodeNondeterministic does not guarantee that any two invocations will write // the same sequence of bytes to the io.Writer. Any differences will not be significant to a // generic decoder. For example, map entries and struct fields might be encoded in any // order. EncodeNondeterministic(Object, io.Writer) error } // MemoryAllocator is responsible for allocating memory. // By encapsulating memory allocation into its own interface, we can reuse the memory // across many operations in places we know it can significantly improve the performance. type MemoryAllocator interface { // Allocate reserves memory for n bytes. // Note that implementations of this method are not required to zero the returned array. // It is the caller's responsibility to clean the memory if needed. Allocate(n uint64) []byte } // EncoderWithAllocator serializes objects in a way that allows callers to manage any additional memory allocations. type EncoderWithAllocator interface { Encoder // EncodeWithAllocator writes an object to a stream as Encode does. // In addition, it allows for providing a memory allocator for efficient memory usage during object serialization EncodeWithAllocator(obj Object, w io.Writer, memAlloc MemoryAllocator) error } // Decoder attempts to load an object from data. type Decoder interface { // Decode attempts to deserialize the provided data using either the innate typing of the scheme or the // default kind, group, and version provided. It returns a decoded object as well as the kind, group, and // version from the serialized data, or an error. If into is non-nil, it will be used as the target type // and implementations may choose to use it rather than reallocating an object. However, the object is not // guaranteed to be populated. The returned object is not guaranteed to match into. If defaults are // provided, they are applied to the data by default. If no defaults or partial defaults are provided, the // type of the into may be used to guide conversion decisions. Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) } // Serializer is the core interface for transforming objects into a serialized format and back. // Implementations may choose to perform conversion of the object, but no assumptions should be made. type Serializer interface { Encoder Decoder } // Codec is a Serializer that deals with the details of versioning objects. It offers the same // interface as Serializer, so this is a marker to consumers that care about the version of the objects // they receive. type Codec Serializer // ParameterCodec defines methods for serializing and deserializing API objects to url.Values and // performing any necessary conversion. Unlike the normal Codec, query parameters are not self describing // and the desired version must be specified. type ParameterCodec interface { // DecodeParameters takes the given url.Values in the specified group version and decodes them // into the provided object, or returns an error. DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error // EncodeParameters encodes the provided object as query parameters or returns an error. EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) } // Framer is a factory for creating readers and writers that obey a particular framing pattern. type Framer interface { NewFrameReader(r io.ReadCloser) io.ReadCloser NewFrameWriter(w io.Writer) io.Writer } // SerializerInfo contains information about a specific serialization format type SerializerInfo struct { // MediaType is the value that represents this serializer over the wire. MediaType string // MediaTypeType is the first part of the MediaType ("application" in "application/json"). MediaTypeType string // MediaTypeSubType is the second part of the MediaType ("json" in "application/json"). MediaTypeSubType string // EncodesAsText indicates this serializer can be encoded to UTF-8 safely. EncodesAsText bool // Serializer is the individual object serializer for this media type. Serializer Serializer // PrettySerializer, if set, can serialize this object in a form biased towards // readability. PrettySerializer Serializer // StrictSerializer, if set, deserializes this object strictly, // erring on unknown fields. StrictSerializer Serializer // StreamSerializer, if set, describes the streaming serialization format // for this media type. StreamSerializer *StreamSerializerInfo } // StreamSerializerInfo contains information about a specific stream serialization format type StreamSerializerInfo struct { // EncodesAsText indicates this serializer can be encoded to UTF-8 safely. EncodesAsText bool // Serializer is the top level object serializer for this type when streaming Serializer // Framer is the factory for retrieving streams that separate objects on the wire Framer } // NegotiatedSerializer is an interface used for obtaining encoders, decoders, and serializers // for multiple supported media types. This would commonly be accepted by a server component // that performs HTTP content negotiation to accept multiple formats. type NegotiatedSerializer interface { // SupportedMediaTypes is the media types supported for reading and writing single objects. SupportedMediaTypes() []SerializerInfo // EncoderForVersion returns an encoder that ensures objects being written to the provided // serializer are in the provided group version. EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder // DecoderToVersion returns a decoder that ensures objects being read by the provided // serializer are in the provided group version by default. DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder } // ClientNegotiator handles turning an HTTP content type into the appropriate encoder. // Use NewClientNegotiator or NewVersionedClientNegotiator to create this interface from // a NegotiatedSerializer. type ClientNegotiator interface { // Encoder returns the appropriate encoder for the provided contentType (e.g. application/json) // and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found // a NegotiateError will be returned. The current client implementations consider params to be // optional modifiers to the contentType and will ignore unrecognized parameters. Encoder(contentType string, params map[string]string) (Encoder, error) // Decoder returns the appropriate decoder for the provided contentType (e.g. application/json) // and any optional mediaType parameters (e.g. pretty=1), or an error. If no serializer is found // a NegotiateError will be returned. The current client implementations consider params to be // optional modifiers to the contentType and will ignore unrecognized parameters. Decoder(contentType string, params map[string]string) (Decoder, error) // StreamDecoder returns the appropriate stream decoder for the provided contentType (e.g. // application/json) and any optional mediaType parameters (e.g. pretty=1), or an error. If no // serializer is found a NegotiateError will be returned. The Serializer and Framer will always // be returned if a Decoder is returned. The current client implementations consider params to be // optional modifiers to the contentType and will ignore unrecognized parameters. StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error) } // StorageSerializer is an interface used for obtaining encoders, decoders, and serializers // that can read and write data at rest. This would commonly be used by client tools that must // read files, or server side storage interfaces that persist restful objects. type StorageSerializer interface { // SupportedMediaTypes are the media types supported for reading and writing objects. SupportedMediaTypes() []SerializerInfo // UniversalDeserializer returns a Serializer that can read objects in multiple supported formats // by introspecting the data at rest. UniversalDeserializer() Decoder // EncoderForVersion returns an encoder that ensures objects being written to the provided // serializer are in the provided group version. EncoderForVersion(serializer Encoder, gv GroupVersioner) Encoder // DecoderForVersion returns a decoder that ensures objects being read by the provided // serializer are in the provided group version by default. DecoderToVersion(serializer Decoder, gv GroupVersioner) Decoder } // NestedObjectEncoder is an optional interface that objects may implement to be given // an opportunity to encode any nested Objects / RawExtensions during serialization. type NestedObjectEncoder interface { EncodeNestedObjects(e Encoder) error } // NestedObjectDecoder is an optional interface that objects may implement to be given // an opportunity to decode any nested Objects / RawExtensions during serialization. // It is possible for DecodeNestedObjects to return a non-nil error but for the decoding // to have succeeded in the case of strict decoding errors (e.g. unknown/duplicate fields). // As such it is important for callers of DecodeNestedObjects to check to confirm whether // an error is a runtime.StrictDecodingError before short circuiting. // Similarly, implementations of DecodeNestedObjects should ensure that a runtime.StrictDecodingError // is only returned when the rest of decoding has succeeded. type NestedObjectDecoder interface { DecodeNestedObjects(d Decoder) error } /////////////////////////////////////////////////////////////////////////////// // Non-codec interfaces type ObjectDefaulter interface { // Default takes an object (must be a pointer) and applies any default values. // Defaulters may not error. Default(in Object) } type ObjectVersioner interface { ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error) } // ObjectConvertor converts an object to a different version. type ObjectConvertor interface { // Convert attempts to convert one object into another, or returns an error. This // method does not mutate the in object, but the in and out object might share data structures, // i.e. the out object cannot be mutated without mutating the in object as well. // The context argument will be passed to all nested conversions. Convert(in, out, context interface{}) error // ConvertToVersion takes the provided object and converts it the provided version. This // method does not mutate the in object, but the in and out object might share data structures, // i.e. the out object cannot be mutated without mutating the in object as well. // This method is similar to Convert() but handles specific details of choosing the correct // output version. ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) } // ObjectTyper contains methods for extracting the APIVersion and Kind // of objects. type ObjectTyper interface { // ObjectKinds returns the all possible group,version,kind of the provided object, true if // the object is unversioned, or an error if the object is not recognized // (IsNotRegisteredError will return true). ObjectKinds(Object) ([]schema.GroupVersionKind, bool, error) // Recognizes returns true if the scheme is able to handle the provided version and kind, // or more precisely that the provided version is a possible conversion or decoding // target. Recognizes(gvk schema.GroupVersionKind) bool } // ObjectCreater contains methods for instantiating an object by kind and version. type ObjectCreater interface { New(kind schema.GroupVersionKind) (out Object, err error) } // EquivalentResourceMapper provides information about resources that address the same underlying data as a specified resource type EquivalentResourceMapper interface { // EquivalentResourcesFor returns a list of resources that address the same underlying data as resource. // If subresource is specified, only equivalent resources which also have the same subresource are included. // The specified resource can be included in the returned list. EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource // KindFor returns the kind expected by the specified resource[/subresource]. // A zero value is returned if the kind is unknown. KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind } // EquivalentResourceRegistry provides an EquivalentResourceMapper interface, // and allows registering known resource[/subresource] -> kind type EquivalentResourceRegistry interface { EquivalentResourceMapper // RegisterKindFor registers the existence of the specified resource[/subresource] along with its expected kind. RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind) } // ResourceVersioner provides methods for setting and retrieving // the resource version from an API object. type ResourceVersioner interface { SetResourceVersion(obj Object, version string) error ResourceVersion(obj Object) (string, error) } // Namer provides methods for retrieving name and namespace of an API object. type Namer interface { // Name returns the name of a given object. Name(obj Object) (string, error) // Namespace returns the name of a given object. Namespace(obj Object) (string, error) } // Object interface must be supported by all API types registered with Scheme. Since objects in a scheme are // expected to be serialized to the wire, the interface an Object must provide to the Scheme allows // serializers to set the kind, version, and group the object is represented as. An Object may choose // to return a no-op ObjectKindAccessor in cases where it is not expected to be serialized. type Object interface { GetObjectKind() schema.ObjectKind DeepCopyObject() Object } // CacheableObject allows an object to cache its different serializations // to avoid performing the same serialization multiple times. type CacheableObject interface { // CacheEncode writes an object to a stream. The <encode> function will // be used in case of cache miss. The <encode> function takes ownership // of the object. // If CacheableObject is a wrapper, then deep-copy of the wrapped object // should be passed to <encode> function. // CacheEncode assumes that for two different calls with the same <id>, // <encode> function will also be the same. CacheEncode(id Identifier, encode func(Object, io.Writer) error, w io.Writer) error // GetObject returns a deep-copy of an object to be encoded - the caller of // GetObject() is the owner of returned object. The reason for making a copy // is to avoid bugs, where caller modifies the object and forgets to copy it, // thus modifying the object for everyone. // The object returned by GetObject should be the same as the one that is supposed // to be passed to <encode> function in CacheEncode method. // If CacheableObject is a wrapper, the copy of wrapped object should be returned. GetObject() Object } // Unstructured objects store values as map[string]interface{}, with only values that can be serialized // to JSON allowed. type Unstructured interface { Object // NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data. // This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info. NewEmptyInstance() Unstructured // UnstructuredContent returns a non-nil map with this object's contents. Values may be // []interface{}, map[string]interface{}, or any primitive type. Contents are typically serialized to // and from JSON. SetUnstructuredContent should be used to mutate the contents. UnstructuredContent() map[string]interface{} // SetUnstructuredContent updates the object content to match the provided map. SetUnstructuredContent(map[string]interface{}) // IsList returns true if this type is a list or matches the list convention - has an array called "items". IsList() bool // EachListItem should pass a single item out of the list as an Object to the provided function. Any // error should terminate the iteration. If IsList() returns false, this method should return an error // instead of calling the provided function. EachListItem(func(Object) error) error // EachListItemWithAlloc works like EachListItem, but avoids retaining references to a slice of items. // It does this by making a shallow copy of non-pointer items before passing them to fn. // // If the items passed to fn are not retained, or are retained for the same duration, use EachListItem instead for memory efficiency. EachListItemWithAlloc(func(Object) error) error }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/register.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/register.go
/* 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 runtime import "k8s.io/apimachinery/pkg/runtime/schema" // SetGroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta func (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind) { obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() } // GroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta func (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind { return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) } func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/conversion.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package runtime defines conversions between generic types and structs to map query strings // to struct objects. package runtime import ( "fmt" "reflect" "strconv" "strings" "k8s.io/apimachinery/pkg/conversion" ) // DefaultMetaV1FieldSelectorConversion auto-accepts metav1 values for name and namespace. // A cluster scoped resource specifying namespace empty works fine and specifying a particular // namespace will return no results, as expected. func DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, error) { switch label { case "metadata.name": return label, value, nil case "metadata.namespace": return label, value, nil default: return "", "", fmt.Errorf("%q is not a known field selector: only %q, %q", label, "metadata.name", "metadata.namespace") } } // JSONKeyMapper uses the struct tags on a conversion to determine the key value for // the other side. Use when mapping from a map[string]* to a struct or vice versa. func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) { if s := destTag.Get("json"); len(s) > 0 { return strings.SplitN(s, ",", 2)[0], key } if s := sourceTag.Get("json"); len(s) > 0 { return key, strings.SplitN(s, ",", 2)[0] } return key, key } func Convert_Slice_string_To_string(in *[]string, out *string, s conversion.Scope) error { if len(*in) == 0 { *out = "" return nil } *out = (*in)[0] return nil } func Convert_Slice_string_To_int(in *[]string, out *int, s conversion.Scope) error { if len(*in) == 0 { *out = 0 return nil } str := (*in)[0] i, err := strconv.Atoi(str) if err != nil { return err } *out = i return nil } // Convert_Slice_string_To_bool will convert a string parameter to boolean. // Only the absence of a value (i.e. zero-length slice), a value of "false", or a // value of "0" resolve to false. // Any other value (including empty string) resolves to true. func Convert_Slice_string_To_bool(in *[]string, out *bool, s conversion.Scope) error { if len(*in) == 0 { *out = false return nil } switch { case (*in)[0] == "0", strings.EqualFold((*in)[0], "false"): *out = false default: *out = true } return nil } // Convert_Slice_string_To_bool will convert a string parameter to boolean. // Only the absence of a value (i.e. zero-length slice), a value of "false", or a // value of "0" resolve to false. // Any other value (including empty string) resolves to true. func Convert_Slice_string_To_Pointer_bool(in *[]string, out **bool, s conversion.Scope) error { if len(*in) == 0 { boolVar := false *out = &boolVar return nil } switch { case (*in)[0] == "0", strings.EqualFold((*in)[0], "false"): boolVar := false *out = &boolVar default: boolVar := true *out = &boolVar } return nil } func string_to_int64(in string) (int64, error) { return strconv.ParseInt(in, 10, 64) } func Convert_string_To_int64(in *string, out *int64, s conversion.Scope) error { if in == nil { *out = 0 return nil } i, err := string_to_int64(*in) if err != nil { return err } *out = i return nil } func Convert_Slice_string_To_int64(in *[]string, out *int64, s conversion.Scope) error { if len(*in) == 0 { *out = 0 return nil } i, err := string_to_int64((*in)[0]) if err != nil { return err } *out = i return nil } func Convert_string_To_Pointer_int64(in *string, out **int64, s conversion.Scope) error { if in == nil { *out = nil return nil } i, err := string_to_int64(*in) if err != nil { return err } *out = &i return nil } func Convert_Slice_string_To_Pointer_int64(in *[]string, out **int64, s conversion.Scope) error { if len(*in) == 0 { *out = nil return nil } i, err := string_to_int64((*in)[0]) if err != nil { return err } *out = &i return nil } func RegisterStringConversions(s *Scheme) error { if err := s.AddConversionFunc((*[]string)(nil), (*string)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_Slice_string_To_string(a.(*[]string), b.(*string), scope) }); err != nil { return err } if err := s.AddConversionFunc((*[]string)(nil), (*int)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_Slice_string_To_int(a.(*[]string), b.(*int), scope) }); err != nil { return err } if err := s.AddConversionFunc((*[]string)(nil), (*bool)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_Slice_string_To_bool(a.(*[]string), b.(*bool), scope) }); err != nil { return err } if err := s.AddConversionFunc((*[]string)(nil), (*int64)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_Slice_string_To_int64(a.(*[]string), b.(*int64), scope) }); err != nil { return err } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/codec_check.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/codec_check.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "fmt" "reflect" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/json" ) // CheckCodec makes sure that the codec can encode objects like internalType, // decode all of the external types listed, and also decode them into the given // object. (Will modify internalObject.) (Assumes JSON serialization.) // TODO: verify that the correct external version is chosen on encode... func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error { if _, err := Encode(c, internalType); err != nil { return fmt.Errorf("internal type not encodable: %v", err) } for _, et := range externalTypes { typeMeta := TypeMeta{ Kind: et.Kind, APIVersion: et.GroupVersion().String(), } exBytes, err := json.Marshal(&typeMeta) if err != nil { return err } obj, err := Decode(c, exBytes) if err != nil { return fmt.Errorf("external type %s not interpretable: %v", et, err) } if reflect.TypeOf(obj) != reflect.TypeOf(internalType) { return fmt.Errorf("decode of external type %s produced: %#v", et, obj) } if err = DecodeInto(c, exBytes, internalType); err != nil { return fmt.Errorf("external type %s not convertible to internal type: %v", et, err) } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/extension.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/extension.go
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "bytes" "errors" "fmt" cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct" "k8s.io/apimachinery/pkg/util/json" ) // RawExtension intentionally avoids implementing value.UnstructuredConverter for now because the // signature of ToUnstructured does not allow returning an error value in cases where the conversion // is not possible (content type is unrecognized or bytes don't match content type). func rawToUnstructured(raw []byte, contentType string) (interface{}, error) { switch contentType { case ContentTypeJSON: var u interface{} if err := json.Unmarshal(raw, &u); err != nil { return nil, fmt.Errorf("failed to parse RawExtension bytes as JSON: %w", err) } return u, nil case ContentTypeCBOR: var u interface{} if err := cbor.Unmarshal(raw, &u); err != nil { return nil, fmt.Errorf("failed to parse RawExtension bytes as CBOR: %w", err) } return u, nil default: return nil, fmt.Errorf("cannot convert RawExtension with unrecognized content type to unstructured") } } func (re RawExtension) guessContentType() string { switch { case bytes.HasPrefix(re.Raw, cborSelfDescribed): return ContentTypeCBOR case len(re.Raw) > 0: switch re.Raw[0] { case '\t', '\r', '\n', ' ', '{', '[', 'n', 't', 'f', '"', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': // Prefixes for the four whitespace characters, objects, arrays, strings, numbers, true, false, and null. return ContentTypeJSON } } return "" } func (re *RawExtension) UnmarshalJSON(in []byte) error { if re == nil { return errors.New("runtime.RawExtension: UnmarshalJSON on nil pointer") } if bytes.Equal(in, []byte("null")) { return nil } re.Raw = append(re.Raw[0:0], in...) return nil } var ( cborNull = []byte{0xf6} cborSelfDescribed = []byte{0xd9, 0xd9, 0xf7} ) func (re *RawExtension) UnmarshalCBOR(in []byte) error { if re == nil { return errors.New("runtime.RawExtension: UnmarshalCBOR on nil pointer") } if !bytes.Equal(in, cborNull) { if !bytes.HasPrefix(in, cborSelfDescribed) { // The self-described CBOR tag doesn't change the interpretation of the data // item it encloses, but it is useful as a magic number. Its encoding is // also what is used to implement the CBOR RecognizingDecoder. re.Raw = append(re.Raw[:0], cborSelfDescribed...) } re.Raw = append(re.Raw, in...) } return nil } // 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 (re RawExtension) MarshalJSON() ([]byte, error) { if re.Raw == nil { // TODO: this is to support legacy behavior of JSONPrinter and YAMLPrinter, which // expect to call json.Marshal on arbitrary versioned objects (even those not in // the scheme). pkg/kubectl/resource#AsVersionedObjects and its interaction with // kubectl get on objects not in the scheme needs to be updated to ensure that the // objects that are not part of the scheme are correctly put into the right form. if re.Object != nil { return json.Marshal(re.Object) } return []byte("null"), nil } contentType := re.guessContentType() if contentType == ContentTypeJSON { return re.Raw, nil } u, err := rawToUnstructured(re.Raw, contentType) if err != nil { return nil, err } return json.Marshal(u) } func (re RawExtension) MarshalCBOR() ([]byte, error) { if re.Raw == nil { if re.Object != nil { return cbor.Marshal(re.Object) } return cbor.Marshal(nil) } contentType := re.guessContentType() if contentType == ContentTypeCBOR { return re.Raw, nil } u, err := rawToUnstructured(re.Raw, contentType) if err != nil { return nil, err } return cbor.Marshal(u) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/negotiate.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/negotiate.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "fmt" "k8s.io/apimachinery/pkg/runtime/schema" ) // NegotiateError is returned when a ClientNegotiator is unable to locate // a serializer for the requested operation. type NegotiateError struct { ContentType string Stream bool } func (e NegotiateError) Error() string { if e.Stream { return fmt.Sprintf("no stream serializers registered for %s", e.ContentType) } return fmt.Sprintf("no serializers registered for %s", e.ContentType) } type clientNegotiator struct { serializer NegotiatedSerializer encode, decode GroupVersioner } func (n *clientNegotiator) Encoder(contentType string, params map[string]string) (Encoder, error) { // TODO: `pretty=1` is handled in NegotiateOutputMediaType, consider moving it to this method // if client negotiators truly need to use it mediaTypes := n.serializer.SupportedMediaTypes() info, ok := SerializerInfoForMediaType(mediaTypes, contentType) if !ok { if len(contentType) != 0 || len(mediaTypes) == 0 { return nil, NegotiateError{ContentType: contentType} } info = mediaTypes[0] } return n.serializer.EncoderForVersion(info.Serializer, n.encode), nil } func (n *clientNegotiator) Decoder(contentType string, params map[string]string) (Decoder, error) { mediaTypes := n.serializer.SupportedMediaTypes() info, ok := SerializerInfoForMediaType(mediaTypes, contentType) if !ok { if len(contentType) != 0 || len(mediaTypes) == 0 { return nil, NegotiateError{ContentType: contentType} } info = mediaTypes[0] } return n.serializer.DecoderToVersion(info.Serializer, n.decode), nil } func (n *clientNegotiator) StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error) { mediaTypes := n.serializer.SupportedMediaTypes() info, ok := SerializerInfoForMediaType(mediaTypes, contentType) if !ok { if len(contentType) != 0 || len(mediaTypes) == 0 { return nil, nil, nil, NegotiateError{ContentType: contentType, Stream: true} } info = mediaTypes[0] } if info.StreamSerializer == nil { return nil, nil, nil, NegotiateError{ContentType: info.MediaType, Stream: true} } return n.serializer.DecoderToVersion(info.Serializer, n.decode), info.StreamSerializer.Serializer, info.StreamSerializer.Framer, nil } // NewClientNegotiator will attempt to retrieve the appropriate encoder, decoder, or // stream decoder for a given content type. Does not perform any conversion, but will // encode the object to the desired group, version, and kind. Use when creating a client. func NewClientNegotiator(serializer NegotiatedSerializer, gv schema.GroupVersion) ClientNegotiator { return &clientNegotiator{ serializer: serializer, encode: gv, } } type simpleNegotiatedSerializer struct { info SerializerInfo } func NewSimpleNegotiatedSerializer(info SerializerInfo) NegotiatedSerializer { return &simpleNegotiatedSerializer{info: info} } func (n *simpleNegotiatedSerializer) SupportedMediaTypes() []SerializerInfo { return []SerializerInfo{n.info} } func (n *simpleNegotiatedSerializer) EncoderForVersion(e Encoder, _ GroupVersioner) Encoder { return e } func (n *simpleNegotiatedSerializer) DecoderToVersion(d Decoder, _gv GroupVersioner) Decoder { return d }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/mapper.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/apimachinery/pkg/runtime/mapper.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package runtime import ( "sync" "k8s.io/apimachinery/pkg/runtime/schema" ) type equivalentResourceRegistry struct { // keyFunc computes a key for the specified resource (this allows honoring colocated resources across API groups). // if null, or if "" is returned, resource.String() is used as the key keyFunc func(resource schema.GroupResource) string // resources maps key -> subresource -> equivalent resources (subresource is not included in the returned resources). // main resources are stored with subresource="". resources map[string]map[string][]schema.GroupVersionResource // kinds maps resource -> subresource -> kind kinds map[schema.GroupVersionResource]map[string]schema.GroupVersionKind // keys caches the computed key for each GroupResource keys map[schema.GroupResource]string mutex sync.RWMutex } var _ EquivalentResourceMapper = (*equivalentResourceRegistry)(nil) var _ EquivalentResourceRegistry = (*equivalentResourceRegistry)(nil) // NewEquivalentResourceRegistry creates a resource registry that considers all versions of a GroupResource to be equivalent. func NewEquivalentResourceRegistry() EquivalentResourceRegistry { return &equivalentResourceRegistry{} } // NewEquivalentResourceRegistryWithIdentity creates a resource mapper with a custom identity function. // If "" is returned by the function, GroupResource#String is used as the identity. // GroupResources with the same identity string are considered equivalent. func NewEquivalentResourceRegistryWithIdentity(keyFunc func(schema.GroupResource) string) EquivalentResourceRegistry { return &equivalentResourceRegistry{keyFunc: keyFunc} } func (r *equivalentResourceRegistry) EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource { r.mutex.RLock() defer r.mutex.RUnlock() return r.resources[r.keys[resource.GroupResource()]][subresource] } func (r *equivalentResourceRegistry) KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind { r.mutex.RLock() defer r.mutex.RUnlock() return r.kinds[resource][subresource] } func (r *equivalentResourceRegistry) RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind) { r.mutex.Lock() defer r.mutex.Unlock() if r.kinds == nil { r.kinds = map[schema.GroupVersionResource]map[string]schema.GroupVersionKind{} } if r.kinds[resource] == nil { r.kinds[resource] = map[string]schema.GroupVersionKind{} } r.kinds[resource][subresource] = kind // get the shared key of the parent resource key := "" gr := resource.GroupResource() if r.keyFunc != nil { key = r.keyFunc(gr) } if key == "" { key = gr.String() } if r.keys == nil { r.keys = map[schema.GroupResource]string{} } r.keys[gr] = key if r.resources == nil { r.resources = map[string]map[string][]schema.GroupVersionResource{} } if r.resources[key] == nil { r.resources[key] = map[string][]schema.GroupVersionResource{} } r.resources[key][subresource] = append(r.resources[key][subresource], resource) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false