-
Notifications
You must be signed in to change notification settings - Fork 4
/
ownership.go
84 lines (70 loc) · 1.94 KB
/
ownership.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
package helper
import (
"github.com/puppetlabs/leg/k8sutil/pkg/controller/obj/lifecycle"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func Own(target client.Object, owner lifecycle.TypedObject) error {
if !Exists(owner.Object) {
return &OwnerNotPersistedError{
Owner: owner,
Target: target,
}
}
if target.GetNamespace() != owner.Object.GetNamespace() {
return &OwnerInOtherNamespaceError{
Owner: owner,
Target: target,
}
}
ref := metav1.NewControllerRef(owner.Object, owner.GVK)
targetOwners := target.GetOwnerReferences()
for i, c := range targetOwners {
if equality.Semantic.DeepEqual(c, *ref) {
return nil
} else if c.Controller != nil && *c.Controller {
c.Controller = func(b bool) *bool { return &b }(false)
klog.Warningf(
"%T %s is stealing controller for %T %s from %s %s/%s",
owner.Object, client.ObjectKeyFromObject(owner.Object),
target, client.ObjectKeyFromObject(target),
c.Kind, target.GetNamespace(), c.Name,
)
targetOwners[i] = c
}
}
targetOwners = append(targetOwners, *ref)
target.SetOwnerReferences(targetOwners)
return nil
}
func OwnUncontrolled(target client.Object, owner lifecycle.TypedObject) error {
if !Exists(owner.Object) {
return &OwnerNotPersistedError{
Owner: owner,
Target: target,
}
}
if target.GetNamespace() != owner.Object.GetNamespace() {
return &OwnerInOtherNamespaceError{
Owner: owner,
Target: target,
}
}
ref := metav1.OwnerReference{
APIVersion: owner.GVK.GroupVersion().String(),
Kind: owner.GVK.Kind,
Name: owner.Object.GetName(),
UID: owner.Object.GetUID(),
}
targetOwners := target.GetOwnerReferences()
for _, c := range targetOwners {
if equality.Semantic.DeepEqual(c, ref) {
return nil
}
}
targetOwners = append(targetOwners, ref)
target.SetOwnerReferences(targetOwners)
return nil
}