...
1
2
3
4 package mutation
5
6 import (
7 "errors"
8 "fmt"
9
10 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
11 "k8s.io/klog/v2"
12 "sigs.k8s.io/cli-utils/pkg/object"
13 "sigs.k8s.io/yaml"
14 )
15
16 const (
17 Annotation = "config.kubernetes.io/apply-time-mutation"
18 )
19
20 func HasAnnotation(u *unstructured.Unstructured) bool {
21 if u == nil {
22 return false
23 }
24 _, found := u.GetAnnotations()[Annotation]
25 return found
26 }
27
28
29
30 func ReadAnnotation(obj *unstructured.Unstructured) (ApplyTimeMutation, error) {
31 mutation := ApplyTimeMutation{}
32 if obj == nil {
33 return mutation, nil
34 }
35 mutationYaml, found := obj.GetAnnotations()[Annotation]
36 if !found {
37 return mutation, nil
38 }
39 if klog.V(5).Enabled() {
40 klog.Infof("object (%v) has apply-time-mutation annotation:\n%s", ResourceReferenceFromUnstructured(obj), mutationYaml)
41 }
42
43 err := yaml.Unmarshal([]byte(mutationYaml), &mutation)
44 if err != nil {
45 return mutation, object.InvalidAnnotationError{
46 Annotation: Annotation,
47 Cause: err,
48 }
49 }
50 return mutation, nil
51 }
52
53
54
55 func WriteAnnotation(obj *unstructured.Unstructured, mutation ApplyTimeMutation) error {
56 if obj == nil {
57 return errors.New("object is nil")
58 }
59 if mutation.Equal(ApplyTimeMutation{}) {
60 return errors.New("mutation is empty")
61 }
62 yamlBytes, err := yaml.Marshal(mutation)
63 if err != nil {
64 return fmt.Errorf("failed to format apply-time-mutation annotation: %v", err)
65 }
66 a := obj.GetAnnotations()
67 if a == nil {
68 a = map[string]string{}
69 }
70 a[Annotation] = string(yamlBytes)
71 obj.SetAnnotations(a)
72 return nil
73 }
74
View as plain text