blob: 15b45ffa84b82bbba3e972e686b12e60cf816057 [file] [log] [blame]
Matteo Scandoloa4285862020-12-01 18:10:10 -08001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package v1
18
19import (
20 "k8s.io/apimachinery/pkg/runtime/schema"
21)
22
23// IsControlledBy checks if the object has a controllerRef set to the given owner
24func IsControlledBy(obj Object, owner Object) bool {
25 ref := GetControllerOfNoCopy(obj)
26 if ref == nil {
27 return false
28 }
29 return ref.UID == owner.GetUID()
30}
31
32// GetControllerOf returns a pointer to a copy of the controllerRef if controllee has a controller
33func GetControllerOf(controllee Object) *OwnerReference {
34 ref := GetControllerOfNoCopy(controllee)
35 if ref == nil {
36 return nil
37 }
38 cp := *ref
39 return &cp
40}
41
42// GetControllerOf returns a pointer to the controllerRef if controllee has a controller
43func GetControllerOfNoCopy(controllee Object) *OwnerReference {
44 refs := controllee.GetOwnerReferences()
45 for i := range refs {
46 if refs[i].Controller != nil && *refs[i].Controller {
47 return &refs[i]
48 }
49 }
50 return nil
51}
52
53// NewControllerRef creates an OwnerReference pointing to the given owner.
54func NewControllerRef(owner Object, gvk schema.GroupVersionKind) *OwnerReference {
55 blockOwnerDeletion := true
56 isController := true
57 return &OwnerReference{
58 APIVersion: gvk.GroupVersion().String(),
59 Kind: gvk.Kind,
60 Name: owner.GetName(),
61 UID: owner.GetUID(),
62 BlockOwnerDeletion: &blockOwnerDeletion,
63 Controller: &isController,
64 }
65}