-
Notifications
You must be signed in to change notification settings - Fork 2
/
reconciler.go
356 lines (320 loc) · 11.6 KB
/
reconciler.go
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
Copyright 2020 Noah Kantrowitz
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package core
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/go-logr/logr"
"github.com/pkg/errors"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// Supporting mocking out functions for testing
var getGvk = apiutil.GVKForObject
// Avoid an import loop. Sighs in Go.
var NewRandomSecretComponent func(string, ...string) Component
var NewReadyStatusComponent func(...string) Component
var NewTemplateComponent func(string, string) Component
type Reconciler struct {
name string
mgr ctrl.Manager
controllerBuilder *ctrl.Builder
controller controller.Controller
apiType client.Object
components []*reconcilerComponent
log logr.Logger
client client.Client
uncachedClient client.Client
templates http.FileSystem
events record.EventRecorder
webhook bool
finalizerBaseName string
}
// Concrete component instance.
type reconcilerComponent struct {
name string
comp Component
// Same component as comp but as a finalizer if possible, otherwise nil.
finalizer FinalizerComponent
finalizerName string
// Tracking data for status conditions.
readyCondition string
errorConditionStatus metav1.ConditionStatus
}
func NewReconciler(mgr ctrl.Manager) *Reconciler {
rawClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: mgr.GetScheme()})
if err != nil {
panic(err)
}
return &Reconciler{
mgr: mgr,
controllerBuilder: builder.ControllerManagedBy(mgr),
components: []*reconcilerComponent{},
client: mgr.GetClient(),
uncachedClient: rawClient,
}
}
func (r *Reconciler) For(apiType client.Object, opts ...builder.ForOption) *Reconciler {
r.apiType = apiType
r.controllerBuilder = r.controllerBuilder.For(apiType, opts...)
return r
}
func (r *Reconciler) Watches(src source.Source, eventhandler handler.EventHandler, opts ...builder.WatchesOption) *Reconciler {
r.controllerBuilder = r.controllerBuilder.Watches(src, eventhandler, opts...)
return r
}
func (r *Reconciler) Templates(t http.FileSystem) *Reconciler {
r.templates = t
return r
}
func (r *Reconciler) Webhook() *Reconciler {
r.webhook = true
return r
}
func (r *Reconciler) Component(name string, comp Component) *Reconciler {
rc := &reconcilerComponent{name: name, comp: comp}
finalizer, ok := comp.(FinalizerComponent)
if ok {
rc.finalizer = finalizer
}
readyCond, ok := comp.(ReadyConditionComponent)
if ok {
rc.readyCondition = readyCond.GetReadyCondition()
rc.errorConditionStatus = metav1.ConditionFalse
// If the first character is !, trim it off and invert the error status.
if rc.readyCondition != "" && rc.readyCondition[0] == '!' {
rc.readyCondition = rc.readyCondition[1:]
rc.errorConditionStatus = metav1.ConditionTrue
}
}
r.components = append(r.components, rc)
return r
}
func (r *Reconciler) TemplateComponent(template string, conditionType string) *Reconciler {
name := template[:strings.LastIndex(template, ".")]
return r.Component(name, NewTemplateComponent(template, conditionType))
}
func (r *Reconciler) RandomSecretComponent(keys ...string) *Reconciler {
// TODO This is super awkward. Maybe just provisionally set r.name from For()?
controllerName, err := r.getControllerName()
if err != nil {
panic(err)
}
nameTemplate := fmt.Sprintf("%%s-%s", controllerName)
return r.Component("randomSecret", NewRandomSecretComponent(nameTemplate, keys...))
}
func (r *Reconciler) ReadyStatusComponent(keys ...string) *Reconciler {
return r.Component("readyStatus", NewReadyStatusComponent(keys...))
}
func (r *Reconciler) Complete() error {
_, err := r.Build()
return err
}
func (r *Reconciler) getControllerName() (string, error) {
if r.name != "" {
return r.name, nil
}
gvk, err := getGvk(r.apiType, r.mgr.GetScheme())
if err != nil {
return "", err
}
return strings.ToLower(gvk.Kind), nil
}
func (r *Reconciler) Build() (controller.Controller, error) {
name, err := r.getControllerName()
if err != nil {
return nil, errors.Wrap(err, "error computing controller name")
}
r.name = name
r.log = ctrl.Log.WithName("controllers").WithName(name)
// Work out a default finalizer base name.
if r.finalizerBaseName == "" {
gvk, err := apiutil.GVKForObject(r.apiType, r.mgr.GetScheme())
if err != nil {
return nil, errors.Wrapf(err, "error getting GVK for object %#v", r.apiType)
}
r.finalizerBaseName = fmt.Sprintf("%s.%s/", name, gvk.Group)
}
// Check if we have more than component with the same name.
compMap := map[string]Component{}
for _, rc := range r.components {
first, ok := compMap[rc.name]
if ok {
return nil, errors.Errorf("found duplicate component using name %s: %#v %#v", rc.name, first, rc.comp)
}
compMap[rc.name] = rc.comp
}
setupCtx := &Context{
Context: context.Background(),
Client: r.client,
UncachedClient: r.uncachedClient,
Templates: r.templates,
Scheme: r.mgr.GetScheme(),
Object: r.apiType.DeepCopyObject().(client.Object),
}
// Provide some bare minimum data
setupObj := setupCtx.Object.(metav1.Object)
setupObj.SetName("setup")
setupObj.SetNamespace("setup")
log := r.log.WithName("components")
for _, rc := range r.components {
rc.finalizerName = r.finalizerBaseName + rc.name
setupComp, ok := rc.comp.(InitializerComponent)
if !ok {
continue
}
setupCtx.Log = log.WithName(rc.name)
setupCtx.FieldManager = fmt.Sprintf("%s/%s", r.name, rc.name)
err := setupComp.Setup(setupCtx, r.controllerBuilder)
if err != nil {
return nil, errors.Wrapf(err, "error initializing component %s in controller %s", rc.name, r.name)
}
}
controller, err := r.controllerBuilder.Build(r)
if err != nil {
return nil, errors.Wrapf(err, "error building controller %s", r.name)
}
r.controller = controller
r.events = r.mgr.GetEventRecorderFor(r.name + "-controller")
// If requested, set up a webhook runable too.
if r.webhook {
err := ctrl.NewWebhookManagedBy(r.mgr).For(r.apiType).Complete()
if err != nil {
return nil, errors.Wrap(err, "error initializing webhook")
}
}
return controller, nil
}
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.log.WithValues("object", req)
log.Info("Starting reconcile")
recCtx := &Context{
Context: ctx,
Client: r.client,
UncachedClient: r.uncachedClient,
Templates: r.templates,
Scheme: r.mgr.GetScheme(),
Events: r.events,
Data: ContextData{},
}
obj := r.apiType.DeepCopyObject().(client.Object)
err := r.client.Get(recCtx, req.NamespacedName, obj)
if err != nil {
if kerrors.IsNotFound(err) {
// Object not found, likely already deleted, just silenty bail.
log.Info("Aborting reconcile, object already deleted")
return reconcile.Result{}, nil
}
return reconcile.Result{Requeue: true}, errors.Wrap(err, "error getting reconcile object")
}
recCtx.Object = obj.(client.Object)
recCtx.Conditions = NewConditionsHelper(recCtx.Object)
cleanObj := obj.DeepCopyObject().(client.Object)
// Check for annotation that blocks reconciles, exit early if found.
annotations := recCtx.Object.GetAnnotations()
reconcileBlocked, ok := annotations["controller-utils/skip-reconcile"]
if ok && reconcileBlocked == "true" {
log.Info("Skipping reconcile due to annotation")
return reconcile.Result{}, nil
}
// Reconcile the components.
compLog := log.WithName("components")
for _, rc := range r.components {
// Create the per-component logger.
recCtx.Log = compLog.WithName(rc.name)
recCtx.FieldManager = fmt.Sprintf("%s/%s", r.name, rc.name)
isAlive := recCtx.Object.GetDeletionTimestamp() == nil
if rc.readyCondition != "" {
recCtx.Conditions.SetUnknown(rc.readyCondition, "Unknown")
}
var res Result
if isAlive {
log.V(1).Info("Reconciling component", "component", rc.name)
res, err = rc.comp.Reconcile(recCtx)
if rc.finalizer != nil {
controllerutil.AddFinalizer(recCtx.Object, rc.finalizerName)
}
} else if rc.finalizer != nil && controllerutil.ContainsFinalizer(recCtx.Object, rc.finalizerName) {
log.V(1).Info("Finalizing component", "component", rc.name)
var done bool
res, done, err = rc.finalizer.Finalize(recCtx)
if done {
controllerutil.RemoveFinalizer(recCtx.Object, rc.finalizerName)
}
}
if err != nil && rc.readyCondition != "" {
// Mark the status condition for this component as bad.
recCtx.Conditions.Set(rc.readyCondition, rc.errorConditionStatus, "Error", err.Error())
}
recCtx.mergeResult(rc.name, res, err)
if err != nil {
log.Error(err, "error in component reconcile", "component", rc.name)
}
if res.SkipRemaining {
// Abort reconcile to skip remaining components.
log.V(1).Info("Skipping remaining components")
break
}
}
// Check if we need to patch metadata, only looking at labels, annotations, and finalizers.
currentMeta := r.apiType.DeepCopyObject().(client.Object)
currentMeta.SetName(recCtx.Object.GetName())
currentMeta.SetNamespace(recCtx.Object.GetNamespace())
currentMeta.SetLabels(recCtx.Object.GetLabels())
currentMeta.SetAnnotations(recCtx.Object.GetAnnotations())
currentMeta.SetFinalizers(recCtx.Object.GetFinalizers())
cleanMeta := r.apiType.DeepCopyObject().(client.Object)
cleanMeta.SetName(cleanObj.GetName())
cleanMeta.SetNamespace(cleanObj.GetNamespace())
cleanMeta.SetLabels(cleanObj.GetLabels())
cleanMeta.SetAnnotations(cleanObj.GetAnnotations())
cleanMeta.SetFinalizers(cleanObj.GetFinalizers())
err = r.client.Patch(recCtx, currentMeta, client.MergeFrom(cleanMeta), &client.PatchOptions{FieldManager: r.name})
if err != nil && !kerrors.IsNotFound(err) {
// If it was a NotFound error, the object was probably already deleted so just ignore the error and return the existing result.
return recCtx.result, errors.Wrap(err, "error patching metadata")
}
// Save the object status.
err = r.client.Status().Patch(recCtx, recCtx.Object, client.MergeFrom(cleanObj), &client.PatchOptions{FieldManager: r.name})
if err != nil && !kerrors.IsNotFound(err) {
// If it was a NotFound error, the object was probably already deleted so just ignore the error and return the existing result.
return recCtx.result, errors.Wrap(err, "error patching status")
}
// Build up the final error to be logged.
err = nil
if len(recCtx.errors) == 1 {
err = recCtx.errors[0]
} else if len(recCtx.errors) > 1 {
msg := strings.Builder{}
msg.WriteString("Multiple errors:\n")
for _, e := range recCtx.errors {
msg.WriteString(" ")
msg.WriteString(e.Error())
msg.WriteString("\n")
}
err = errors.New(msg.String())
}
return recCtx.result, err
}