...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/utils/controller/ownerReferences.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/utils/controller

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package controller
    15  
    16  import (
    17  	"fmt"
    18  
    19  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    20  	"k8s.io/apimachinery/pkg/runtime"
    21  	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
    22  )
    23  
    24  func SetOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) error {
    25  	ro, ok := owner.(runtime.Object)
    26  	if !ok {
    27  		return fmt.Errorf("%T is not a runtime.Object, cannot call SetControllerReference", owner)
    28  	}
    29  
    30  	gvk, err := apiutil.GVKForObject(ro, scheme)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	// Create a new ref
    36  	isController := false
    37  	blockOwnerDeletion := true
    38  	ref := metav1.OwnerReference{
    39  		APIVersion:         gvk.GroupVersion().String(),
    40  		Kind:               gvk.Kind,
    41  		Name:               owner.GetName(),
    42  		UID:                owner.GetUID(),
    43  		BlockOwnerDeletion: &blockOwnerDeletion,
    44  		Controller:         &isController,
    45  	}
    46  
    47  	existingRefs := object.GetOwnerReferences()
    48  	fi := -1
    49  
    50  	for i, r := range existingRefs {
    51  		if ref.UID == r.UID {
    52  			fi = i
    53  		}
    54  	}
    55  	if fi == -1 {
    56  		existingRefs = append(existingRefs, ref)
    57  	} else {
    58  		existingRefs[fi] = ref
    59  	}
    60  
    61  	// Update owner references
    62  	object.SetOwnerReferences(existingRefs)
    63  	return nil
    64  }
    65