Skip to content

Commit 2533444

Browse files
committed
Add public functions to add/remove OwnerReferences without the referenced object (closes #2989)
1 parent 685db56 commit 2533444

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

pkg/controller/controllerutil/controllerutil.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,36 @@ func RemoveOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) e
168168
return nil
169169
}
170170

171+
// AppendOwnerReference is a helper method to make sure the given object contains a provided owner reference.
172+
// This allows you to declare that owner has a dependency on the object without specifying it as a controller.
173+
// If a reference already exists, it'll be overwritten with the newly provided version.
174+
func AppendOwnerReference(owner metav1.OwnerReference, object metav1.Object) {
175+
upsertOwnerRef(owner, object)
176+
}
177+
178+
// DropOwnerReference is a helper method to make sure the given object removes a provided owner reference.
179+
// This allows you to remove the owner to establish a new owner of the object in a subsequent call.
180+
func DropOwnerReference(owner metav1.OwnerReference, object metav1.Object) error {
181+
ownerRefs := object.GetOwnerReferences()
182+
index := indexOwnerRef(ownerRefs, metav1.OwnerReference{
183+
APIVersion: owner.APIVersion,
184+
Name: owner.Name,
185+
Kind: owner.Kind,
186+
})
187+
188+
if index == -1 {
189+
return fmt.Errorf("%T does not have an controller reference for %T", object, owner)
190+
}
191+
192+
if ownerRefs[index].Controller == nil || !*ownerRefs[index].Controller {
193+
return fmt.Errorf("%T owner is not the controller reference for %T", owner, object)
194+
}
195+
196+
ownerRefs = append(ownerRefs[:index], ownerRefs[index+1:]...)
197+
object.SetOwnerReferences(ownerRefs)
198+
return nil
199+
}
200+
171201
// HasControllerReference returns true if the object
172202
// has an owner ref with controller equal to true
173203
func HasControllerReference(object metav1.Object) bool {

0 commit comments

Comments
 (0)