forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ownerref.go
60 lines (53 loc) · 1.96 KB
/
ownerref.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
package controller
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kapihelper "k8s.io/kubernetes/pkg/apis/core/helper"
)
// EnsureOwnerRef adds the ownerref if needed. Removes ownerrefs with conflicting UIDs.
// Returns true if the input is mutated.
func EnsureOwnerRef(metadata metav1.Object, newOwnerRef metav1.OwnerReference) bool {
foundButNotEqual := false
for _, existingOwnerRef := range metadata.GetOwnerReferences() {
if existingOwnerRef.APIVersion == newOwnerRef.APIVersion &&
existingOwnerRef.Kind == newOwnerRef.Kind &&
existingOwnerRef.Name == newOwnerRef.Name {
// if we're completely the same, there's nothing to do
if kapihelper.Semantic.DeepEqual(existingOwnerRef, newOwnerRef) {
return false
}
foundButNotEqual = true
break
}
}
// if we weren't found, then we just need to add ourselves
if !foundButNotEqual {
metadata.SetOwnerReferences(append(metadata.GetOwnerReferences(), newOwnerRef))
return true
}
// if we need to remove an existing ownerRef, just do the easy thing and build it back from scratch
newOwnerRefs := []metav1.OwnerReference{newOwnerRef}
for i := range metadata.GetOwnerReferences() {
existingOwnerRef := metadata.GetOwnerReferences()[i]
if existingOwnerRef.APIVersion == newOwnerRef.APIVersion &&
existingOwnerRef.Kind == newOwnerRef.Kind &&
existingOwnerRef.Name == newOwnerRef.Name {
continue
}
newOwnerRefs = append(newOwnerRefs, existingOwnerRef)
}
metadata.SetOwnerReferences(newOwnerRefs)
return true
}
// HasOwnerRef checks to see if an object has a particular owner. It is not opinionated about
// the bool fields
func HasOwnerRef(metadata metav1.Object, needle metav1.OwnerReference) bool {
for _, existingOwnerRef := range metadata.GetOwnerReferences() {
if existingOwnerRef.APIVersion == needle.APIVersion &&
existingOwnerRef.Kind == needle.Kind &&
existingOwnerRef.Name == needle.Name &&
existingOwnerRef.UID == needle.UID {
return true
}
}
return false
}