-
Notifications
You must be signed in to change notification settings - Fork 114
/
helpers.go
104 lines (96 loc) · 2.37 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package v1alpha1
import (
"context"
"encoding/json"
"fmt"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
func AddFinalizer(ctx context.Context, c client.Client, obj client.Object) error {
if controllerutil.AddFinalizer(obj, FinalizerName) {
patchBytes := []byte(`{"metadata":{"finalizers":[`)
for i, finalizer := range obj.GetFinalizers() {
if i > 0 {
patchBytes = append(patchBytes, ',')
}
patchBytes = append(patchBytes, fmt.Sprintf("%q", finalizer)...)
}
patchBytes = append(patchBytes, "]}}"...)
if err := c.Patch(
ctx,
obj,
client.RawPatch(types.MergePatchType, patchBytes),
); err != nil {
return fmt.Errorf("patch annotation: %w", err)
}
return nil
}
return nil
}
func ClearAnnotations(ctx context.Context, c client.Client, obj client.Object, keys ...string) error {
kvs := make(map[string]*string, len(keys))
for _, k := range keys {
kvs[k] = nil
}
return patchAnnotations(ctx, c, obj, kvs)
}
func patchAnnotation(ctx context.Context, c client.Client, obj client.Object, key, value string) error {
return patchAnnotations(ctx, c, obj, map[string]*string{
key: ptr.To(value),
})
}
func patchAnnotations(
ctx context.Context,
c client.Client,
obj client.Object,
kvs map[string]*string,
) error {
type objectMeta struct {
Annotations map[string]*string `json:"annotations"`
}
type patch struct {
ObjectMeta objectMeta `json:"metadata"`
}
if len(kvs) == 0 {
// Do nothing if there are no kv pairs to patch.
return nil
}
data, err := json.Marshal(patch{
ObjectMeta: objectMeta{
Annotations: kvs,
},
})
if err != nil {
return fmt.Errorf("marshal patch data: %w", err)
}
if err := c.Patch(
ctx,
obj,
client.RawPatch(types.MergePatchType, data),
); err != nil {
return fmt.Errorf("patch annotation: %w", err)
}
return nil
}
func IsV06Compatible(obj client.Object) bool {
return obj.GetLabels()[V06CompatibilityLabelKey] == LabelTrueValue
}
func EnsureV06CompatibilityLabel(
ctx context.Context,
c client.Client,
obj client.Object,
) error {
if IsV06Compatible(obj) {
return nil
}
patchBytes := []byte(
fmt.Sprintf(
`{"metadata":{"labels":{"%s":"true"}}}`,
V06CompatibilityLabelKey,
),
)
patch := client.RawPatch(types.MergePatchType, patchBytes)
return c.Patch(ctx, obj, patch)
}