sigs.k8s.io/cluster-api@v1.7.1/internal/topology/ownerrefs/ownerref.go (about)

     1  /*
     2  Copyright 2023 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package ownerrefs contains ownerref utils.
    18  package ownerrefs
    19  
    20  import (
    21  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    22  	"k8s.io/apimachinery/pkg/runtime/schema"
    23  	"sigs.k8s.io/controller-runtime/pkg/client"
    24  )
    25  
    26  // OwnerReferenceTo converts an object to an OwnerReference.
    27  // Note: We pass in gvk explicitly as we can't rely on GVK being set on all objects
    28  // (only on Unstructured).
    29  func OwnerReferenceTo(obj client.Object, gvk schema.GroupVersionKind) *metav1.OwnerReference {
    30  	return &metav1.OwnerReference{
    31  		APIVersion: gvk.GroupVersion().String(),
    32  		Kind:       gvk.Kind,
    33  		Name:       obj.GetName(),
    34  		UID:        obj.GetUID(),
    35  	}
    36  }
    37  
    38  // HasOwnerReferenceFrom checks if obj has an ownerRef pointing to owner.
    39  func HasOwnerReferenceFrom(obj, owner client.Object) bool {
    40  	for _, o := range obj.GetOwnerReferences() {
    41  		if o.Kind == owner.GetObjectKind().GroupVersionKind().Kind && o.Name == owner.GetName() {
    42  			return true
    43  		}
    44  	}
    45  	return false
    46  }