github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/controller/handler/handler_builder.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  
    25  	"sigs.k8s.io/controller-runtime/pkg/client"
    26  	"sigs.k8s.io/controller-runtime/pkg/handler"
    27  	"sigs.k8s.io/controller-runtime/pkg/reconcile"
    28  
    29  	"github.com/1aal/kubeblocks/pkg/controller/model"
    30  )
    31  
    32  // Builder defines an EventHandler builder
    33  type Builder interface {
    34  	AddFinder(Finder) Builder
    35  	Build() handler.EventHandler
    36  }
    37  
    38  type realBuilder struct {
    39  	ctx     *FinderContext
    40  	finders []Finder
    41  }
    42  
    43  var _ Builder = &realBuilder{}
    44  
    45  func NewBuilder(ctx *FinderContext) Builder {
    46  	return &realBuilder{ctx: ctx}
    47  }
    48  
    49  func (builder *realBuilder) AddFinder(finder Finder) Builder {
    50  	builder.finders = append(builder.finders, finder)
    51  	return builder
    52  }
    53  
    54  func (builder *realBuilder) Build() handler.EventHandler {
    55  	fn := func(ctx context.Context, obj client.Object) []reconcile.Request {
    56  		var key *model.GVKNObjKey
    57  		for i, finder := range builder.finders {
    58  			key = finder.Find(builder.ctx, obj)
    59  			if key == nil {
    60  				return nil
    61  			}
    62  			if i < len(builder.finders)-1 {
    63  				obj = getObjectFromKey(builder.ctx, key)
    64  				if obj == nil {
    65  					return nil
    66  				}
    67  			}
    68  		}
    69  		if key == nil {
    70  			return nil
    71  		}
    72  		return []reconcile.Request{{NamespacedName: key.ObjectKey}}
    73  	}
    74  
    75  	return handler.EnqueueRequestsFromMapFunc(fn)
    76  }