...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package k8s
16
17 import (
18 "encoding/json"
19 "fmt"
20 "strings"
21
22 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
23 )
24
25 func GenerateMutableButUnreadableFieldsAnnotation(resource *Resource, mutableButUnreadablePaths [][]string) (string, error) {
26 state, err := GenerateMutableButUnreadableFieldsState(resource, mutableButUnreadablePaths)
27 if err != nil {
28 return "", err
29 }
30 b, err := json.Marshal(state)
31 if err != nil {
32 return "", err
33 }
34 return string(b), nil
35 }
36
37 func GenerateMutableButUnreadableFieldsState(resource *Resource, mutableButUnreadablePaths [][]string) (map[string]interface{}, error) {
38 state := make(map[string]interface{})
39 for _, path := range mutableButUnreadablePaths {
40 krmPath := append([]string{"spec"}, path...)
41 krmField := strings.Join(krmPath, ".")
42 val, found, err := unstructured.NestedFieldCopy(resource.Spec, krmPath[1:]...)
43 if err != nil {
44 return nil, fmt.Errorf("error reading %v: %v", krmField, err)
45 }
46 if !found {
47 continue
48 }
49 if err := unstructured.SetNestedField(state, val, krmPath...); err != nil {
50 return nil, fmt.Errorf("error saving %v: %v", krmField, err)
51 }
52 }
53 return state, nil
54 }
55
56 func GetMutableButUnreadableFieldsFromAnnotations(resource *Resource, mutableButUnreadablePaths [][]string) (map[string]interface{}, error) {
57 mutableButUnreadableFields := make(map[string]interface{})
58 if len(mutableButUnreadablePaths) == 0 {
59
60 return mutableButUnreadableFields, nil
61 }
62
63 var err error
64 annotationVal, ok := GetAnnotation(MutableButUnreadableFieldsAnnotation, resource)
65 if !ok {
66
67
68
69
70
71
72
73
74
75
76
77 annotationVal, err = GenerateMutableButUnreadableFieldsAnnotation(resource, mutableButUnreadablePaths)
78 if err != nil {
79 return nil, fmt.Errorf("error ensuring resource '%v' which can have mutable-but-unreadable fields has a value for %v: %w",
80 resource.GetNamespace(), MutableButUnreadableFieldsAnnotation, err)
81 }
82 }
83
84 if err := json.Unmarshal([]byte(annotationVal), &mutableButUnreadableFields); err != nil {
85 return nil, fmt.Errorf("error unmarshalling value of %v: %w", MutableButUnreadableFieldsAnnotation, err)
86 }
87 return mutableButUnreadableFields, nil
88 }
89
View as plain text