...

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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package controller
    17  
    18  import (
    19  	"fmt"
    20  
    21  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    22  	"k8s.io/apimachinery/pkg/runtime"
    23  	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
    24  )
    25  
    26  func SetOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) error {
    27  	ro, ok := owner.(runtime.Object)
    28  	if !ok {
    29  		return fmt.Errorf("%T is not a runtime.Object, cannot call SetControllerReference", owner)
    30  	}
    31  
    32  	gvk, err := apiutil.GVKForObject(ro, scheme)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	// Create a new ref
    38  	isController := false
    39  	blockOwnerDeletion := true
    40  	ref := metav1.OwnerReference{
    41  		APIVersion:         gvk.GroupVersion().String(),
    42  		Kind:               gvk.Kind,
    43  		Name:               owner.GetName(),
    44  		UID:                owner.GetUID(),
    45  		BlockOwnerDeletion: &blockOwnerDeletion,
    46  		Controller:         &isController,
    47  	}
    48  
    49  	existingRefs := object.GetOwnerReferences()
    50  	fi := -1
    51  
    52  	for i, r := range existingRefs {
    53  		if ref.UID == r.UID {
    54  			fi = i
    55  		}
    56  	}
    57  	if fi == -1 {
    58  		existingRefs = append(existingRefs, ref)
    59  	} else {
    60  		existingRefs[fi] = ref
    61  	}
    62  
    63  	// Update owner references
    64  	object.SetOwnerReferences(existingRefs)
    65  	return nil
    66  }
    67