github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/controllers/workloads/replicatedstatemachine_controller.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 workloads
    21  
    22  import (
    23  	"context"
    24  
    25  	appsv1 "k8s.io/api/apps/v1"
    26  	batchv1 "k8s.io/api/batch/v1"
    27  	corev1 "k8s.io/api/core/v1"
    28  	apierrors "k8s.io/apimachinery/pkg/api/errors"
    29  	"k8s.io/apimachinery/pkg/runtime"
    30  	"k8s.io/client-go/tools/record"
    31  	ctrl "sigs.k8s.io/controller-runtime"
    32  	"sigs.k8s.io/controller-runtime/pkg/client"
    33  	"sigs.k8s.io/controller-runtime/pkg/log"
    34  
    35  	workloads "github.com/1aal/kubeblocks/apis/workloads/v1alpha1"
    36  	"github.com/1aal/kubeblocks/pkg/constant"
    37  	"github.com/1aal/kubeblocks/pkg/controller/handler"
    38  	"github.com/1aal/kubeblocks/pkg/controller/model"
    39  	"github.com/1aal/kubeblocks/pkg/controller/rsm"
    40  	intctrlutil "github.com/1aal/kubeblocks/pkg/controllerutil"
    41  	viper "github.com/1aal/kubeblocks/pkg/viperx"
    42  )
    43  
    44  // ReplicatedStateMachineReconciler reconciles a ReplicatedStateMachine object
    45  type ReplicatedStateMachineReconciler struct {
    46  	client.Client
    47  	Scheme   *runtime.Scheme
    48  	Recorder record.EventRecorder
    49  }
    50  
    51  // +kubebuilder:rbac:groups=workloads.kubeblocks.io,resources=replicatedstatemachines,verbs=get;list;watch;create;update;patch;delete
    52  // +kubebuilder:rbac:groups=workloads.kubeblocks.io,resources=replicatedstatemachines/status,verbs=get;update;patch
    53  // +kubebuilder:rbac:groups=workloads.kubeblocks.io,resources=replicatedstatemachines/finalizers,verbs=update
    54  
    55  // Reconcile is part of the main kubernetes reconciliation loop which aims to
    56  // move the current state of the cluster closer to the desired state.
    57  // TODO(user): Modify the Reconcile function to compare the state specified by
    58  // the ReplicatedStateMachine object against the actual cluster state, and then
    59  // perform operations to make the cluster state reflect the state specified by
    60  // the user.
    61  //
    62  // For more details, check Reconcile and its Result here:
    63  // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.14.1/pkg/reconcile
    64  func (r *ReplicatedStateMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    65  	reqCtx := intctrlutil.RequestCtx{
    66  		Ctx:      ctx,
    67  		Req:      req,
    68  		Log:      log.FromContext(ctx).WithValues("ReplicatedStateMachine", req.NamespacedName),
    69  		Recorder: r.Recorder,
    70  	}
    71  
    72  	reqCtx.Log.V(1).Info("reconcile", "ReplicatedStateMachine", req.NamespacedName)
    73  
    74  	requeueError := func(err error) (ctrl.Result, error) {
    75  		if re, ok := err.(model.RequeueError); ok {
    76  			return intctrlutil.RequeueAfter(re.RequeueAfter(), reqCtx.Log, re.Reason())
    77  		}
    78  		if apierrors.IsConflict(err) {
    79  			return intctrlutil.Requeue(reqCtx.Log, err.Error())
    80  		}
    81  		return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log, "")
    82  	}
    83  
    84  	// the RSM reconciliation loop is a two-phase model: plan Build and plan Execute
    85  	// Init stage
    86  	planBuilder := rsm.NewRSMPlanBuilder(reqCtx, r.Client, req)
    87  	if err := planBuilder.Init(); err != nil {
    88  		return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log, "")
    89  	}
    90  
    91  	// Build stage
    92  	// what you should do in most cases is writing your transformer.
    93  	//
    94  	// here are the how-to tips:
    95  	// 1. one transformer for one scenario
    96  	// 2. try not to modify the current transformers, make a new one
    97  	// 3. transformers are independent with each-other, with some exceptions.
    98  	//    Which means transformers' order is not important in most cases.
    99  	//    If you don't know where to put your transformer, append it to the end and that would be ok.
   100  	// 4. don't use client.Client for object write, use client.ReadonlyClient for object read.
   101  	//    If you do need to create/update/delete object, make your intent operation a model.ObjectVertex and put it into the DAG.
   102  	//
   103  	// TODO: transformers are vertices, theirs' dependencies are edges, make plan Build stage a DAG.
   104  	plan, err := planBuilder.
   105  		AddTransformer(
   106  			// fix meta
   107  			&rsm.FixMetaTransformer{},
   108  			// handle deletion
   109  			// handle cluster deletion first
   110  			&rsm.ObjectDeletionTransformer{},
   111  			// handle secondary objects generation
   112  			&rsm.ObjectGenerationTransformer{},
   113  			// handle status
   114  			&rsm.ObjectStatusTransformer{},
   115  			// handle MemberUpdateStrategy
   116  			&rsm.UpdateStrategyTransformer{},
   117  			// handle member reconfiguration
   118  			&rsm.MemberReconfigurationTransformer{},
   119  			// always safe to put your transformer below
   120  		).
   121  		Build()
   122  	if err != nil {
   123  		return requeueError(err)
   124  	}
   125  	// TODO: define error categories in Build stage and handle them here like this:
   126  	// switch errBuild.(type) {
   127  	// case NOTFOUND:
   128  	// case ALREADYEXISY:
   129  	// }
   130  
   131  	// Execute stage
   132  	if err = plan.Execute(); err != nil {
   133  		return requeueError(err)
   134  	}
   135  
   136  	return intctrlutil.Reconciled()
   137  }
   138  
   139  // SetupWithManager sets up the controller with the Manager.
   140  func (r *ReplicatedStateMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {
   141  	ctx := &handler.FinderContext{
   142  		Context: context.Background(),
   143  		Reader:  r.Client,
   144  		Scheme:  *r.Scheme,
   145  	}
   146  
   147  	if viper.GetBool(rsm.FeatureGateRSMCompatibilityMode) {
   148  		nameLabels := []string{constant.AppInstanceLabelKey, constant.KBAppComponentLabelKey}
   149  		delegatorFinder := handler.NewDelegatorFinder(&workloads.ReplicatedStateMachine{}, nameLabels)
   150  		ownerFinder := handler.NewOwnerFinder(&appsv1.StatefulSet{})
   151  		stsHandler := handler.NewBuilder(ctx).AddFinder(delegatorFinder).Build()
   152  		jobHandler := handler.NewBuilder(ctx).AddFinder(delegatorFinder).Build()
   153  		podHandler := handler.NewBuilder(ctx).AddFinder(ownerFinder).AddFinder(delegatorFinder).Build()
   154  
   155  		return ctrl.NewControllerManagedBy(mgr).
   156  			For(&workloads.ReplicatedStateMachine{}).
   157  			Watches(&appsv1.StatefulSet{}, stsHandler).
   158  			Watches(&batchv1.Job{}, jobHandler).
   159  			Watches(&corev1.Pod{}, podHandler).
   160  			Complete(r)
   161  	}
   162  
   163  	stsOwnerFinder := handler.NewOwnerFinder(&appsv1.StatefulSet{})
   164  	rsmOwnerFinder := handler.NewOwnerFinder(&workloads.ReplicatedStateMachine{})
   165  	podHandler := handler.NewBuilder(ctx).AddFinder(stsOwnerFinder).AddFinder(rsmOwnerFinder).Build()
   166  	return ctrl.NewControllerManagedBy(mgr).
   167  		For(&workloads.ReplicatedStateMachine{}).
   168  		Owns(&appsv1.StatefulSet{}).
   169  		Owns(&batchv1.Job{}).
   170  		Watches(&corev1.Pod{}, podHandler).
   171  		Complete(r)
   172  }