github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/controller/handler/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  	"context"
    24  	"sync"
    25  
    26  	"k8s.io/apimachinery/pkg/runtime"
    27  	"k8s.io/apimachinery/pkg/runtime/schema"
    28  	"sigs.k8s.io/controller-runtime/pkg/client"
    29  
    30  	"github.com/1aal/kubeblocks/pkg/controller/model"
    31  )
    32  
    33  type FinderContext struct {
    34  	context.Context
    35  	client.Reader
    36  	Scheme runtime.Scheme
    37  }
    38  
    39  // Finder finds a new object by an old object
    40  type Finder interface {
    41  	Find(*FinderContext, client.Object) *model.GVKNObjKey
    42  }
    43  
    44  type baseFinder struct {
    45  	objectType runtime.Object
    46  	gvkMutex   sync.Mutex
    47  	gvkCache   *schema.GroupVersionKind
    48  }
    49  
    50  func getObjectFromKey(ctx *FinderContext, key *model.GVKNObjKey) client.Object {
    51  	objectRT, err := ctx.Scheme.New(key.GroupVersionKind)
    52  	if err != nil {
    53  		return nil
    54  	}
    55  	object, ok := objectRT.(client.Object)
    56  	if !ok {
    57  		return nil
    58  	}
    59  	if err = ctx.Reader.Get(ctx, key.ObjectKey, object); err != nil {
    60  		return nil
    61  	}
    62  	return object
    63  }
    64  
    65  func (finder *baseFinder) getGroupVersionKind(scheme *runtime.Scheme) *schema.GroupVersionKind {
    66  	finder.gvkMutex.Lock()
    67  	defer finder.gvkMutex.Unlock()
    68  	if finder.gvkCache == nil {
    69  		// Get the kinds of the type
    70  		kinds, _, err := scheme.ObjectKinds(finder.objectType)
    71  		if err != nil {
    72  			return nil
    73  		}
    74  		// Expect only 1 kind.  If there is more than one kind this is probably an edge case such as ListOptions.
    75  		if len(kinds) != 1 {
    76  			// expected exactly 1 kind for object
    77  			return nil
    78  		}
    79  		finder.gvkCache = &kinds[0]
    80  	}
    81  	return finder.gvkCache
    82  }