...

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  	"github.com/pkg/errors"
    20  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    21  	"k8s.io/apimachinery/pkg/runtime"
    22  	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
    23  )
    24  
    25  func SetOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) error {
    26  	ro, ok := owner.(runtime.Object)
    27  	if !ok {
    28  		return errors.Errorf("%T is not a runtime.Object, cannot call SetControllerReference", owner)
    29  	}
    30  
    31  	gvk, err := apiutil.GVKForObject(ro, scheme)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	// Create a new ref
    37  	isController := false
    38  	blockOwnerDeletion := true
    39  	ref := metav1.OwnerReference{
    40  		APIVersion:         gvk.GroupVersion().String(),
    41  		Kind:               gvk.Kind,
    42  		Name:               owner.GetName(),
    43  		UID:                owner.GetUID(),
    44  		BlockOwnerDeletion: &blockOwnerDeletion,
    45  		Controller:         &isController,
    46  	}
    47  
    48  	existingRefs := object.GetOwnerReferences()
    49  	fi := -1
    50  
    51  	for i, r := range existingRefs {
    52  		if ref.UID == r.UID {
    53  			fi = i
    54  		}
    55  	}
    56  	if fi == -1 {
    57  		existingRefs = append(existingRefs, ref)
    58  	} else {
    59  		existingRefs[fi] = ref
    60  	}
    61  
    62  	// Update owner references
    63  	object.SetOwnerReferences(existingRefs)
    64  	return nil
    65  }
    66