-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathcomponentparameter_controller.go
More file actions
215 lines (189 loc) · 7.98 KB
/
Copy pathcomponentparameter_controller.go
File metadata and controls
215 lines (189 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
Copyright (C) 2022-2025 ApeCloud Co., Ltd
This file is part of KubeBlocks project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package parameters
import (
"context"
"fmt"
"strconv"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1"
"github.com/apecloud/kubeblocks/pkg/constant"
"github.com/apecloud/kubeblocks/pkg/controller/model"
intctrlutil "github.com/apecloud/kubeblocks/pkg/controllerutil"
"github.com/apecloud/kubeblocks/pkg/parameters"
viper "github.com/apecloud/kubeblocks/pkg/viperx"
)
// ComponentParameterReconciler reconciles a ComponentParameter object
type ComponentParameterReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
}
// +kubebuilder:rbac:groups=parameters.kubeblocks.io,resources=componentparameters,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=parameters.kubeblocks.io,resources=componentparameters/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=parameters.kubeblocks.io,resources=componentparameters/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.14.4/pkg/reconcile
func (r *ComponentParameterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
reqCtx := intctrlutil.RequestCtx{
Ctx: ctx,
Req: req,
Recorder: r.Recorder,
Log: log.FromContext(ctx).
WithName("ComponentParameterReconciler").
WithValues("Namespace", req.Namespace, "ComponentParameter", req.Name),
}
componentParam := ¶metersv1alpha1.ComponentParameter{}
if err := r.Client.Get(reqCtx.Ctx, reqCtx.Req.NamespacedName, componentParam); err != nil {
return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log, "")
}
res, err := intctrlutil.HandleCRDeletion(reqCtx, r, componentParam, constant.ConfigFinalizerName, r.deletionHandler(reqCtx, componentParam))
if res != nil {
return *res, err
}
return r.reconcile(reqCtx, componentParam)
}
// SetupWithManager sets up the controller with the Manager.
func (r *ComponentParameterReconciler) SetupWithManager(mgr ctrl.Manager) error {
return intctrlutil.NewControllerManagedBy(mgr).
For(¶metersv1alpha1.ComponentParameter{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: viper.GetInt(constant.CfgKBReconcileWorkers) / 4,
}).
Owns(&corev1.ConfigMap{}).
Complete(r)
}
func (r *ComponentParameterReconciler) reconcile(reqCtx intctrlutil.RequestCtx, componentParameter *parametersv1alpha1.ComponentParameter) (ctrl.Result, error) {
tasks := generateReconcileTasks(reqCtx, componentParameter)
if len(tasks) == 0 {
reqCtx.Log.Info("nothing to reconcile")
return intctrlutil.Reconciled()
}
fetcherTask, err := prepareReconcileTask(reqCtx, r.Client, componentParameter)
if err != nil {
return intctrlutil.RequeueWithError(err, reqCtx.Log, errors.Wrap(err, "failed to get related object").Error())
}
if model.IsObjectDeleting(fetcherTask.ComponentObj) {
reqCtx.Log.Info("cluster is deleting, skip reconcile")
return intctrlutil.Reconciled()
}
if fetcherTask.ClusterComObj == nil || fetcherTask.ComponentObj == nil {
return r.failWithInvalidComponent(componentParameter, reqCtx)
}
taskCtx, err := NewTaskContext(reqCtx.Ctx, r.Client, componentParameter, fetcherTask)
if err != nil {
return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log, errors.Wrap(err, "failed to create task context").Error())
}
if err := r.runTasks(taskCtx, tasks, fetcherTask); err != nil {
return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log,
errors.Wrap(err, "failed to run parameters reconcile task").Error())
}
return intctrlutil.Reconciled()
}
func (r *ComponentParameterReconciler) failWithInvalidComponent(componentParam *parametersv1alpha1.ComponentParameter, reqCtx intctrlutil.RequestCtx) (ctrl.Result, error) {
msg := fmt.Sprintf("not found cluster component: [%s]", componentParam.Spec.ComponentName)
reqCtx.Log.Error(fmt.Errorf("%s", msg), "")
patch := client.MergeFrom(componentParam.DeepCopy())
componentParam.Status.Message = msg
if err := r.Client.Status().Patch(reqCtx.Ctx, componentParam, patch); err != nil {
return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log,
errors.Wrap(err, "failed to update componentParameter status").Error())
}
return intctrlutil.Reconciled()
}
func (r *ComponentParameterReconciler) runTasks(taskCtx *TaskContext, tasks []Task, resource *Task) error {
var (
errs []error
compParameter = taskCtx.componentParameter
)
patch := client.MergeFrom(compParameter.DeepCopy())
revision := strconv.FormatInt(compParameter.GetGeneration(), 10)
for _, task := range tasks {
if err := task.Do(resource, taskCtx, revision); err != nil {
errs = append(errs, err)
continue
}
}
updateCompParamStatus(&compParameter.Status, errs, compParameter.Generation)
if err := r.Client.Status().Patch(taskCtx.ctx, compParameter, patch); err != nil {
errs = append(errs, err)
}
if len(errs) == 0 {
return nil
}
return utilerrors.NewAggregate(errs)
}
func updateCompParamStatus(status *parametersv1alpha1.ComponentParameterStatus, errs []error, generation int64) {
aggregatePhase := func(ss []parametersv1alpha1.ConfigTemplateItemDetailStatus) parametersv1alpha1.ParameterPhase {
var phase = parametersv1alpha1.CFinishedPhase
for _, s := range ss {
switch {
case parameters.IsFailedPhase(s.Phase):
return s.Phase
case !parameters.IsParameterFinished(s.Phase):
phase = parametersv1alpha1.CRunningPhase
}
}
return phase
}
status.ObservedGeneration = generation
status.Message = ""
status.Phase = aggregatePhase(status.ConfigurationItemStatus)
if len(errs) > 0 {
status.Message = utilerrors.NewAggregate(errs).Error()
}
}
func (r *ComponentParameterReconciler) deletionHandler(reqCtx intctrlutil.RequestCtx, componentParameter *parametersv1alpha1.ComponentParameter) func() (*ctrl.Result, error) {
return func() (*ctrl.Result, error) {
cms := &corev1.ConfigMapList{}
listOpts := []client.ListOption{
client.InNamespace(componentParameter.GetNamespace()),
client.MatchingLabels(constant.GetCompLabels(componentParameter.Spec.ClusterName, componentParameter.Spec.ComponentName)),
}
if err := r.Client.List(reqCtx.Ctx, cms, listOpts...); err != nil {
return &reconcile.Result{}, err
}
if err := removeConfigRelatedFinalizer(reqCtx.Ctx, r.Client, cms.Items); err != nil {
return &reconcile.Result{}, err
}
return nil, nil
}
}
func removeConfigRelatedFinalizer(ctx context.Context, cli client.Client, objs []corev1.ConfigMap) error {
for _, obj := range objs {
if !controllerutil.ContainsFinalizer(&obj, constant.ConfigFinalizerName) {
continue
}
patch := client.MergeFrom(obj.DeepCopy())
controllerutil.RemoveFinalizer(&obj, constant.ConfigFinalizerName)
if err := cli.Patch(ctx, &obj, patch); err != nil {
return err
}
}
return nil
}