github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/controller/handler/delegator_finder.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package handler 21 22 import ( 23 "strings" 24 25 "k8s.io/apimachinery/pkg/runtime" 26 "sigs.k8s.io/controller-runtime/pkg/client" 27 28 "github.com/1aal/kubeblocks/pkg/controller/model" 29 ) 30 31 type delegatorFinder struct { 32 baseFinder 33 34 // nameLabels defines labels should be contained in event source object. 35 // And these labels will be used to build the delegator object's name by concat in order by '-' separator. 36 nameLabels []string 37 } 38 39 var _ Finder = &delegatorFinder{} 40 41 func NewDelegatorFinder(delegatorType runtime.Object, nameLabels []string) Finder { 42 return &delegatorFinder{ 43 nameLabels: nameLabels, 44 baseFinder: baseFinder{ 45 objectType: delegatorType, 46 }, 47 } 48 } 49 50 func (finder *delegatorFinder) Find(ctx *FinderContext, object client.Object) *model.GVKNObjKey { 51 // make sure all labels in NameLabels exist and get the corresponding values in order. 52 labels := object.GetLabels() 53 if labels == nil { 54 return nil 55 } 56 var nameValues []string 57 for _, label := range finder.nameLabels { 58 if value, ok := labels[label]; !ok { 59 return nil 60 } else { 61 nameValues = append(nameValues, value) 62 } 63 } 64 // build the delegator object's name 65 name := strings.Join(nameValues, "-") 66 objKey := client.ObjectKey{ 67 Namespace: object.GetNamespace(), 68 Name: name, 69 } 70 delegatorGVK := finder.getGroupVersionKind(&ctx.Scheme) 71 if delegatorGVK == nil { 72 return nil 73 } 74 return &model.GVKNObjKey{ 75 GroupVersionKind: *delegatorGVK, 76 ObjectKey: objKey, 77 } 78 }