Debian Codegraph @

pkg/apis/meta/v1/unstructured/helpers.go

raw
1 /*
2 Copyright 2015 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package unstructured
18
19 import (
20 gojson "encoding/json"
21 "fmt"
22 "io"
23 "math/big"
24 "strings"
25
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/apimachinery/pkg/runtime/schema"
29 "k8s.io/apimachinery/pkg/types"
30 "k8s.io/apimachinery/pkg/util/json"
31 "k8s.io/klog/v2"
32 )
33
34 // NestedFieldCopy returns a deep copy of the value of a nested field.
35 // Returns false if the value is missing.
36 // No error is returned for a nil field.
37 //
38 // Note: fields passed to this function are treated as keys within the passed
39 // object; no array/slice syntax is supported.
40 func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
41 val, found, err := NestedFieldNoCopy(obj, fields...)
42 if !found || err != nil {
43 return nil, found, err
44 }
45 return runtime.DeepCopyJSONValue(val), true, nil
46 }
47
48 // NestedFieldNoCopy returns a reference to a nested field.
49 // Returns false if value is not found and an error if unable
50 // to traverse obj.
51 //
52 // Note: fields passed to this function are treated as keys within the passed
53 // object; no array/slice syntax is supported.
54 func NestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
55 var val interface{} = obj
56
57 for i, field := range fields {
58 if val == nil {
59 return nil, false, nil
60 }
61 if m, ok := val.(map[string]interface{}); ok {
62 val, ok = m[field]
63 if !ok {
64 return nil, false, nil
65 }
66 } else {
67 return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields[:i+1]), val, val)
68 }
69 }
70 return val, true, nil
71 }
72
73 // NestedString returns the string value of a nested field.
74 // Returns false if value is not found and an error if not a string.
75 func NestedString(obj map[string]interface{}, fields ...string) (string, bool, error) {
76 val, found, err := NestedFieldNoCopy(obj, fields...)
77 if !found || err != nil {
78 return "", found, err
79 }
80 s, ok := val.(string)
81 if !ok {
82 return "", false, fmt.Errorf("%v accessor error: %v is of the type %T, expected string", jsonPath(fields), val, val)
83 }
84 return s, true, nil
85 }
86
87 // NestedBool returns the bool value of a nested field.
88 // Returns false if value is not found and an error if not a bool.
89 func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error) {
90 val, found, err := NestedFieldNoCopy(obj, fields...)
91 if !found || err != nil {
92 return false, found, err
93 }
94 b, ok := val.(bool)
95 if !ok {
96 return false, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected bool", jsonPath(fields), val, val)
97 }
98 return b, true, nil
99 }
100
101 // NestedFloat64 returns the float64 value of a nested field.
102 // Returns false if value is not found and an error if not a float64.
103 func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {
104 val, found, err := NestedFieldNoCopy(obj, fields...)
105 if !found || err != nil {
106 return 0, found, err
107 }
108 f, ok := val.(float64)
109 if !ok {
110 return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected float64", jsonPath(fields), val, val)
111 }
112 return f, true, nil
113 }
114
115 // NestedInt64 returns the int64 value of a nested field.
116 // Returns false if value is not found and an error if not an int64.
117 func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error) {
118 val, found, err := NestedFieldNoCopy(obj, fields...)
119 if !found || err != nil {
120 return 0, found, err
121 }
122 i, ok := val.(int64)
123 if !ok {
124 return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected int64", jsonPath(fields), val, val)
125 }
126 return i, true, nil
127 }
128
129 // NestedNumberAsFloat64 returns the float64 value of a nested field. If the field's value is a
130 // float64, it is returned. If the field's value is an int64 that can be losslessly converted to
131 // float64, it will be converted and returned. Returns false if value is not found and an error if
132 // not a float64 or an int64 that can be accurately represented as a float64.
133 func NestedNumberAsFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {
134 val, found, err := NestedFieldNoCopy(obj, fields...)
135 if !found || err != nil {
136 return 0, found, err
137 }
138 switch x := val.(type) {
139 case int64:
140 f, accuracy := big.NewInt(x).Float64()
141 if accuracy != big.Exact {
142 return 0, false, fmt.Errorf("%v accessor error: int64 value %v cannot be losslessly converted to float64", jsonPath(fields), x)
143 }
144 return f, true, nil
145 case float64:
146 return x, true, nil
147 default:
148 return 0, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected float64 or int64", jsonPath(fields), val, val)
149 }
150 }
151
152 // NestedStringSlice returns a copy of []string value of a nested field.
153 // Returns false if value is not found and an error if not a []interface{} or contains non-string items in the slice.
154 func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error) {
155 val, found, err := NestedFieldNoCopy(obj, fields...)
156 if !found || err != nil {
157 return nil, found, err
158 }
159 m, ok := val.([]interface{})
160 if !ok {
161 return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
162 }
163 strSlice := make([]string, 0, len(m))
164 for _, v := range m {
165 if str, ok := v.(string); ok {
166 strSlice = append(strSlice, str)
167 } else {
168 return nil, false, fmt.Errorf("%v accessor error: contains non-string key in the slice: %v is of the type %T, expected string", jsonPath(fields), v, v)
169 }
170 }
171 return strSlice, true, nil
172 }
173
174 // NestedSlice returns a deep copy of []interface{} value of a nested field.
175 // Returns false if value is not found and an error if not a []interface{}.
176 func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) {
177 val, found, err := NestedFieldNoCopy(obj, fields...)
178 if !found || err != nil {
179 return nil, found, err
180 }
181 _, ok := val.([]interface{})
182 if !ok {
183 return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", jsonPath(fields), val, val)
184 }
185 return runtime.DeepCopyJSONValue(val).([]interface{}), true, nil
186 }
187
188 // NestedStringMap returns a copy of map[string]string value of a nested field.
189 // Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map.
190 func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {
191 m, found, err := nestedMapNoCopy(obj, false, fields...)
192 if !found || err != nil {
193 return nil, found, err
194 }
195 strMap := make(map[string]string, len(m))
196 for k, v := range m {
197 if str, ok := v.(string); ok {
198 strMap[k] = str
199 } else {
200 return nil, false, fmt.Errorf("%v accessor error: contains non-string value in the map under key %q: %v is of the type %T, expected string", jsonPath(fields), k, v, v)
201 }
202 }
203 return strMap, true, nil
204 }
205
206 // NestedNullCoercingStringMap returns a copy of map[string]string value of a nested field.
207 // Returns `nil, true, nil` if the value exists and is explicitly null.
208 // Returns `nil, false, err` if the value is not a map or a null value, or is a map and contains non-string non-null values.
209 // Null values in the map are coerced to "" to match json decoding behavior.
210 func NestedNullCoercingStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {
211 m, found, err := nestedMapNoCopy(obj, true, fields...)
212 if !found || err != nil || m == nil {
213 return nil, found, err
214 }
215 strMap := make(map[string]string, len(m))
216 for k, v := range m {
217 if str, ok := v.(string); ok {
218 strMap[k] = str
219 } else if v == nil {
220 strMap[k] = ""
221 } else {
222 return nil, false, fmt.Errorf("%v accessor error: contains non-string value in the map under key %q: %v is of the type %T, expected string", jsonPath(fields), k, v, v)
223 }
224 }
225 return strMap, true, nil
226 }
227
228 // NestedMap returns a deep copy of map[string]interface{} value of a nested field.
229 // Returns false if value is not found and an error if not a map[string]interface{}.
230 func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
231 m, found, err := nestedMapNoCopy(obj, false, fields...)
232 if !found || err != nil {
233 return nil, found, err
234 }
235 return runtime.DeepCopyJSON(m), true, nil
236 }
237
238 // nestedMapNoCopy returns a map[string]interface{} value of a nested field.
239 // Returns false if value is not found and an error if not a map[string]interface{}.
240 func nestedMapNoCopy(obj map[string]interface{}, tolerateNil bool, fields ...string) (map[string]interface{}, bool, error) {
241 val, found, err := NestedFieldNoCopy(obj, fields...)
242 if !found || err != nil {
243 return nil, found, err
244 }
245 if val == nil && tolerateNil {
246 return nil, true, nil
247 }
248 m, ok := val.(map[string]interface{})
249 if !ok {
250 return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields), val, val)
251 }
252 return m, true, nil
253 }
254
255 // SetNestedField sets the value of a nested field to a deep copy of the value provided.
256 // Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
257 func SetNestedField(obj map[string]interface{}, value interface{}, fields ...string) error {
258 return setNestedFieldNoCopy(obj, runtime.DeepCopyJSONValue(value), fields...)
259 }
260
261 func setNestedFieldNoCopy(obj map[string]interface{}, value interface{}, fields ...string) error {
262 m := obj
263
264 for i, field := range fields[:len(fields)-1] {
265 if val, ok := m[field]; ok {
266 if valMap, ok := val.(map[string]interface{}); ok {
267 m = valMap
268 } else {
269 return fmt.Errorf("value cannot be set because %v is not a map[string]interface{}", jsonPath(fields[:i+1]))
270 }
271 } else {
272 newVal := make(map[string]interface{})
273 m[field] = newVal
274 m = newVal
275 }
276 }
277 m[fields[len(fields)-1]] = value
278 return nil
279 }
280
281 // SetNestedStringSlice sets the string slice value of a nested field.
282 // Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
283 func SetNestedStringSlice(obj map[string]interface{}, value []string, fields ...string) error {
284 m := make([]interface{}, 0, len(value)) // convert []string into []interface{}
285 for _, v := range value {
286 m = append(m, v)
287 }
288 return setNestedFieldNoCopy(obj, m, fields...)
289 }
290
291 // SetNestedSlice sets the slice value of a nested field.
292 // Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
293 func SetNestedSlice(obj map[string]interface{}, value []interface{}, fields ...string) error {
294 return SetNestedField(obj, value, fields...)
295 }
296
297 // SetNestedStringMap sets the map[string]string value of a nested field.
298 // Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
299 func SetNestedStringMap(obj map[string]interface{}, value map[string]string, fields ...string) error {
300 m := make(map[string]interface{}, len(value)) // convert map[string]string into map[string]interface{}
301 for k, v := range value {
302 m[k] = v
303 }
304 return setNestedFieldNoCopy(obj, m, fields...)
305 }
306
307 // SetNestedMap sets the map[string]interface{} value of a nested field.
308 // Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.
309 func SetNestedMap(obj map[string]interface{}, value map[string]interface{}, fields ...string) error {
310 return SetNestedField(obj, value, fields...)
311 }
312
313 // RemoveNestedField removes the nested field from the obj.
314 func RemoveNestedField(obj map[string]interface{}, fields ...string) {
315 m := obj
316 for _, field := range fields[:len(fields)-1] {
317 if x, ok := m[field].(map[string]interface{}); ok {
318 m = x
319 } else {
320 return
321 }
322 }
323 delete(m, fields[len(fields)-1])
324 }
325
326 func getNestedString(obj map[string]interface{}, fields ...string) string {
327 val, found, err := NestedString(obj, fields...)
328 if !found || err != nil {
329 return ""
330 }
331 return val
332 }
333
334 func getNestedInt64Pointer(obj map[string]interface{}, fields ...string) *int64 {
335 val, found, err := NestedInt64(obj, fields...)
336 if !found || err != nil {
337 return nil
338 }
339 return &val
340 }
341
342 func jsonPath(fields []string) string {
343 return "." + strings.Join(fields, ".")
344 }
345
346 func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference {
347 // though this field is a *bool, but when decoded from JSON, it's
348 // unmarshalled as bool.
349 var controllerPtr *bool
350 if controller, found, err := NestedBool(v, "controller"); err == nil && found {
351 controllerPtr = &controller
352 }
353 var blockOwnerDeletionPtr *bool
354 if blockOwnerDeletion, found, err := NestedBool(v, "blockOwnerDeletion"); err == nil && found {
355 blockOwnerDeletionPtr = &blockOwnerDeletion
356 }
357 return metav1.OwnerReference{
358 Kind: getNestedString(v, "kind"),
359 Name: getNestedString(v, "name"),
360 APIVersion: getNestedString(v, "apiVersion"),
361 UID: types.UID(getNestedString(v, "uid")),
362 Controller: controllerPtr,
363 BlockOwnerDeletion: blockOwnerDeletionPtr,
364 }
365 }
366
367 // UnstructuredJSONScheme is capable of converting JSON data into the Unstructured
368 // type, which can be used for generic access to objects without a predefined scheme.
369 // TODO: move into serializer/json.
370 var UnstructuredJSONScheme runtime.Codec = unstructuredJSONScheme{}
371
372 type unstructuredJSONScheme struct{}
373
374 const unstructuredJSONSchemeIdentifier runtime.Identifier = "unstructuredJSON"
375
376 func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
377 var err error
378 if obj != nil {
379 err = s.decodeInto(data, obj)
380 } else {
381 obj, err = s.decode(data)
382 }
383
384 if err != nil {
385 return nil, nil, err
386 }
387
388 gvk := obj.GetObjectKind().GroupVersionKind()
389 if len(gvk.Kind) == 0 {
390 return nil, &gvk, runtime.NewMissingKindErr(string(data))
391 }
392 // TODO(109023): require apiVersion here as well
393
394 return obj, &gvk, nil
395 }
396
397 func (s unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error {
398 if co, ok := obj.(runtime.CacheableObject); ok {
399 return co.CacheEncode(s.Identifier(), s.doEncode, w)
400 }
401 return s.doEncode(obj, w)
402 }
403
404 func (unstructuredJSONScheme) doEncode(obj runtime.Object, w io.Writer) error {
405 switch t := obj.(type) {
406 case *Unstructured:
407 return json.NewEncoder(w).Encode(t.Object)
408 case *UnstructuredList:
409 items := make([]interface{}, 0, len(t.Items))
410 for _, i := range t.Items {
411 items = append(items, i.Object)
412 }
413 listObj := make(map[string]interface{}, len(t.Object)+1)
414 for k, v := range t.Object { // Make a shallow copy
415 listObj[k] = v
416 }
417 listObj["items"] = items
418 return json.NewEncoder(w).Encode(listObj)
419 case *runtime.Unknown:
420 // TODO: Unstructured needs to deal with ContentType.
421 _, err := w.Write(t.Raw)
422 return err
423 default:
424 return json.NewEncoder(w).Encode(t)
425 }
426 }
427
428 // Identifier implements runtime.Encoder interface.
429 func (unstructuredJSONScheme) Identifier() runtime.Identifier {
430 return unstructuredJSONSchemeIdentifier
431 }
432
433 func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error) {
434 type detector struct {
435 Items gojson.RawMessage `json:"items"`
436 }
437 var det detector
438 if err := json.Unmarshal(data, &det); err != nil {
439 return nil, err
440 }
441
442 if det.Items != nil {
443 list := &UnstructuredList{}
444 err := s.decodeToList(data, list)
445 return list, err
446 }
447
448 // No Items field, so it wasn't a list.
449 unstruct := &Unstructured{}
450 err := s.decodeToUnstructured(data, unstruct)
451 return unstruct, err
452 }
453
454 func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error {
455 switch x := obj.(type) {
456 case *Unstructured:
457 return s.decodeToUnstructured(data, x)
458 case *UnstructuredList:
459 return s.decodeToList(data, x)
460 default:
461 return json.Unmarshal(data, x)
462 }
463 }
464
465 func (unstructuredJSONScheme) decodeToUnstructured(data []byte, unstruct *Unstructured) error {
466 m := make(map[string]interface{})
467 if err := json.Unmarshal(data, &m); err != nil {
468 return err
469 }
470
471 unstruct.Object = m
472
473 return nil
474 }
475
476 func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList) error {
477 type decodeList struct {
478 Items []gojson.RawMessage `json:"items"`
479 }
480
481 var dList decodeList
482 if err := json.Unmarshal(data, &dList); err != nil {
483 return err
484 }
485
486 if err := json.Unmarshal(data, &list.Object); err != nil {
487 return err
488 }
489
490 // For typed lists, e.g., a PodList, API server doesn't set each item's
491 // APIVersion and Kind. We need to set it.
492 listAPIVersion := list.GetAPIVersion()
493 listKind := list.GetKind()
494 itemKind := strings.TrimSuffix(listKind, "List")
495
496 delete(list.Object, "items")
497 list.Items = make([]Unstructured, 0, len(dList.Items))
498 for _, i := range dList.Items {
499 unstruct := &Unstructured{}
500 if err := s.decodeToUnstructured([]byte(i), unstruct); err != nil {
501 return err
502 }
503 // This is hacky. Set the item's Kind and APIVersion to those inferred
504 // from the List.
505 if len(unstruct.GetKind()) == 0 && len(unstruct.GetAPIVersion()) == 0 {
506 unstruct.SetKind(itemKind)
507 unstruct.SetAPIVersion(listAPIVersion)
508 }
509 list.Items = append(list.Items, *unstruct)
510 }
511 return nil
512 }
513
514 type jsonFallbackEncoder struct {
515 encoder runtime.Encoder
516 identifier runtime.Identifier
517 }
518
519 func NewJSONFallbackEncoder(encoder runtime.Encoder) runtime.Encoder {
520 result := map[string]string{
521 "name": "fallback",
522 "base": string(encoder.Identifier()),
523 }
524 identifier, err := gojson.Marshal(result)
525 if err != nil {
526 klog.Fatalf("Failed marshaling identifier for jsonFallbackEncoder: %v", err)
527 }
528 return &jsonFallbackEncoder{
529 encoder: encoder,
530 identifier: runtime.Identifier(identifier),
531 }
532 }
533
534 func (c *jsonFallbackEncoder) Encode(obj runtime.Object, w io.Writer) error {
535 // There is no need to handle runtime.CacheableObject, as we only
536 // fallback to other encoders here.
537 err := c.encoder.Encode(obj, w)
538 if runtime.IsNotRegisteredError(err) {
539 switch obj.(type) {
540 case *Unstructured, *UnstructuredList:
541 return UnstructuredJSONScheme.Encode(obj, w)
542 }
543 }
544 return err
545 }
546
547 // Identifier implements runtime.Encoder interface.
548 func (c *jsonFallbackEncoder) Identifier() runtime.Identifier {
549 return c.identifier
550 }