This repository has been archived by the owner on Dec 11, 2023. It is now read-only.
/
controller.go
652 lines (556 loc) · 18.6 KB
/
controller.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
package controller
import (
"context"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/giantswarm/backoff"
"github.com/giantswarm/k8sclient/v4/pkg/k8sclient"
"github.com/giantswarm/microerror"
"github.com/giantswarm/micrologger"
"github.com/giantswarm/micrologger/loggermeta"
"github.com/giantswarm/to"
"github.com/prometheus/client_golang/prometheus"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
pkgruntime "k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/giantswarm/operatorkit/v2/pkg/controller/collector"
"github.com/giantswarm/operatorkit/v2/pkg/controller/context/cachekeycontext"
"github.com/giantswarm/operatorkit/v2/pkg/controller/context/finalizerskeptcontext"
"github.com/giantswarm/operatorkit/v2/pkg/controller/context/reconciliationcanceledcontext"
"github.com/giantswarm/operatorkit/v2/pkg/controller/context/resourcecanceledcontext"
"github.com/giantswarm/operatorkit/v2/pkg/controller/context/updateallowedcontext"
"github.com/giantswarm/operatorkit/v2/pkg/controller/internal/recorder"
"github.com/giantswarm/operatorkit/v2/pkg/controller/internal/sentry"
"github.com/giantswarm/operatorkit/v2/pkg/resource"
)
const (
DefaultResyncPeriod = 5 * time.Minute
)
const (
DisableMetricsServing = "0"
)
const (
loggerKeyController = "controller"
loggerKeyEvent = "event"
loggerKeyLoop = "loop"
loggerKeyObject = "object"
loggerKeyResource = "resource"
loggerKeyVersion = "version"
)
var (
defaultPauseAnnotations = map[string]string{
"cluster.x-k8s.io/paused": "true",
"operatorkit.giantswarm.io/paused": "true",
}
)
type Config struct {
// InitCtx is deprecated and should not be used anymore.
InitCtx func(ctx context.Context, obj interface{}) (context.Context, error)
// K8sClient is the client collection used to setup and manage certain
// operatorkit primitives. The Controller Client is used to fetch runtime
// objects. It therefore must be properly configured using the AddToScheme
// option. The REST Client is used to patch finalizers on runtime objects.
K8sClient k8sclient.Interface
Logger micrologger.Logger
// NewRuntimeObjectFunc returns a new initialized pointer of a type
// implementing the runtime object interface. The object returned is used with
// the controller-runtime client to fetch the latest version of the object
// itself. That way we can manage all runtime objects in a somewhat generic
// way. See the example below.
//
// func() pkgruntime.Object {
// return new(corev1.ConfigMap)
// }
//
NewRuntimeObjectFunc func() pkgruntime.Object
// Pause is a map of additional pausing annotations, defining their
// key-value pairs. This can be used to stop reconciliation in case the
// configured pausing annotations are present in the reconciled runtime
// object watched by operatorkit.
Pause map[string]string
// Resources is the list of controller resources being executed on runtime
// object reconciliation. Resources are executed in given order.
Resources []resource.Interface
// Selector is used to filter objects before passing them to the controller.
Selector Selector
// Name is the name which the controller uses on finalizers for resources.
// The name used should be unique in the kubernetes cluster, to ensure that
// two operators which handle the same resource add two distinct finalizers.
Name string
// ResyncPeriod is the duration after which a complete sync with all known
// runtime objects the controller watches is performed. Defaults to
// DefaultResyncPeriod.
ResyncPeriod time.Duration
// SentryDSN is the optional URL used to forward runtime errors to the sentry.io service.
// If this field is empty, logs will not be forwarded.
SentryDSN string
}
type Controller struct {
event recorder.Interface
initCtx func(ctx context.Context, obj interface{}) (context.Context, error)
k8sClient k8sclient.Interface
logger micrologger.Logger
newRuntimeObjectFunc func() pkgruntime.Object
pause map[string]string
resources []resource.Interface
selector Selector
backOffFactory func() backoff.Interface
bootOnce sync.Once
booted chan struct{}
collector *collector.Set
loop int64
removedFinalizersCache *stringCache
sentry sentry.Interface
name string
resyncPeriod time.Duration
}
// New creates a new configured operator controller.
func New(config Config) (*Controller, error) {
if config.InitCtx == nil {
config.InitCtx = func(ctx context.Context, obj interface{}) (context.Context, error) {
return ctx, nil
}
}
if config.K8sClient == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.K8sClient must not be empty", config)
}
if config.Logger == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
}
if config.NewRuntimeObjectFunc == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.NewRuntimeObjectFunc must not be empty", config)
}
{
if config.Pause == nil {
config.Pause = map[string]string{}
}
for k, v := range defaultPauseAnnotations {
config.Pause[k] = v
}
}
if len(config.Resources) == 0 {
return nil, microerror.Maskf(invalidConfigError, "%T.Resources must not be empty", config)
}
if config.Selector == nil {
config.Selector = NewSelectorEverything()
}
if config.Name == "" {
return nil, microerror.Maskf(invalidConfigError, "%T.Name must not be empty", config)
}
if config.ResyncPeriod == 0 {
config.ResyncPeriod = DefaultResyncPeriod
}
var err error
var collectorSet *collector.Set
{
c := collector.SetConfig{
Logger: config.Logger,
K8sClient: config.K8sClient,
NewRuntimeObjectFunc: config.NewRuntimeObjectFunc,
Controller: config.Name,
}
collectorSet, err = collector.NewSet(c)
if err != nil {
return nil, microerror.Mask(err)
}
}
var eventRecorder recorder.Interface
{
c := recorder.Config{
K8sClient: config.K8sClient,
Component: config.Name,
}
eventRecorder = recorder.New(c)
}
var sentryClient sentry.Interface
{
c := sentry.Config{
DSN: config.SentryDSN,
}
sentryClient, err = sentry.New(c)
if err != nil {
// Error during sentry initialization.
return nil, microerror.Mask(err)
}
}
c := &Controller{
event: eventRecorder,
initCtx: config.InitCtx,
k8sClient: config.K8sClient,
logger: config.Logger,
newRuntimeObjectFunc: config.NewRuntimeObjectFunc,
pause: config.Pause,
resources: config.Resources,
selector: config.Selector,
backOffFactory: func() backoff.Interface { return backoff.NewMaxRetries(7, 1*time.Second) },
bootOnce: sync.Once{},
booted: make(chan struct{}),
collector: collectorSet,
loop: -1,
removedFinalizersCache: newStringCache(config.ResyncPeriod * 3),
sentry: sentryClient,
name: config.Name,
resyncPeriod: config.ResyncPeriod,
}
return c, nil
}
func (c *Controller) Boot(ctx context.Context) {
ctx = setLoggerCtxValue(ctx, loggerKeyController, c.name)
c.bootOnce.Do(func() {
operation := func() error {
err := c.bootWithError(ctx)
if err != nil {
return microerror.Mask(err)
}
return nil
}
notifier := backoff.NewNotifier(c.logger, ctx)
err := backoff.RetryNotify(operation, c.backOffFactory(), notifier)
if err != nil {
c.sentry.Capture(ctx, err)
c.logger.LogCtx(ctx, "level", "error", "message", "stop controller boot retries due to too many errors", "stack", microerror.JSON(err))
os.Exit(1)
}
})
}
func (c *Controller) Booted() chan struct{} {
return c.booted
}
// Reconcile implements the reconciler given to the controller-runtime
// controller. Reconcile never returns any error as we deal with them in
// operatorkit internally.
func (c *Controller) Reconcile(req reconcile.Request) (reconcile.Result, error) {
ctx := context.Background()
// Add common keys to the logger context.
{
loop := strconv.FormatInt(atomic.AddInt64(&c.loop, 1), 10)
ctx = cachekeycontext.NewContext(ctx, fmt.Sprintf("%s-%s", c.name, loop))
ctx = finalizerskeptcontext.NewContext(ctx, make(chan struct{}))
ctx = updateallowedcontext.NewContext(ctx, make(chan struct{}))
ctx = setLoggerCtxValue(ctx, loggerKeyLoop, loop)
ctx = setLoggerCtxValue(ctx, loggerKeyController, c.name)
}
obj := c.newRuntimeObjectFunc()
err := c.k8sClient.CtrlClient().Get(ctx, req.NamespacedName, obj)
if errors.IsNotFound(err) {
// At this point the controller-runtime cache dispatches a runtime object
// which is already being deleted, which is why it cannot be found here
// anymore. We then likely perceive the last delete event of that runtime
// object and it got purged from the controller-runtime cache. We do not
// need to log these errors and just stop processing here in a more graceful
// way.
return reconcile.Result{}, nil
} else if err != nil {
return reconcile.Result{}, microerror.Mask(err)
}
res, err := c.reconcile(ctx, req, obj)
if err != nil {
// Microerror creates an error event on the object when kind and description is set.
c.event.Emit(ctx, obj, err)
errorGauge.Inc()
c.sentry.Capture(ctx, err)
c.logger.LogCtx(ctx, "level", "error", "message", "failed to reconcile", "stack", microerror.JSON(err))
return reconcile.Result{}, nil
}
return res, nil
}
func (c *Controller) bootWithError(ctx context.Context) error {
var err error
// Boot the collector.
err = c.collector.Boot(ctx)
if err != nil {
return microerror.Mask(err)
}
go func() {
for {
resetWait := c.resyncPeriod * 4
time.Sleep(resetWait)
errorGauge.Set(0)
}
}()
// We overwrite the k8s error handlers so they do not intercept our log
// streams. The format is way easier to parse for us that way. Here we also
// emit metrics for the occured errors to ensure we create more awareness of
// anything going wrong in our operators.
{
utilruntime.ErrorHandlers = []func(err error){
func(err error) {
// When we see a port forwarding error we ignore it because we cannot do
// anything about it. Errors like we check here would have to be dealt
// with in the third party tools we use. The port forwarding in general
// is broken by design which will go away with Helm 3, soon TM.
if IsPortforward(err) {
return
}
errorGauge.Inc()
c.logger.LogCtx(ctx, "level", "error", "message", "caught third party runtime error", "stack", microerror.JSON(err))
},
}
}
var mgr manager.Manager
{
o := manager.Options{
// MetricsBindAddress is set to 0 in order to disable it. We do this
// ourselves.
MetricsBindAddress: DisableMetricsServing,
SyncPeriod: to.DurationP(c.resyncPeriod),
}
mgr, err = manager.New(c.k8sClient.RESTConfig(), o)
if err != nil {
return microerror.Mask(err)
}
}
{
// We build our controller and set up its reconciliation.
// We use the Complete() method instead of Build() because we don't
// need the controller instance.
err = builder.
ControllerManagedBy(mgr).
For(c.newRuntimeObjectFunc()).
WithOptions(controller.Options{
MaxConcurrentReconciles: 1,
Reconciler: c,
}).
WithEventFilter(predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool { return c.selector.Matches(internalLabels(e.Meta.GetLabels())) },
DeleteFunc: func(e event.DeleteEvent) bool { return c.selector.Matches(internalLabels(e.Meta.GetLabels())) },
UpdateFunc: func(e event.UpdateEvent) bool { return c.selector.Matches(internalLabels(e.MetaNew.GetLabels())) },
GenericFunc: func(e event.GenericEvent) bool { return c.selector.Matches(internalLabels(e.Meta.GetLabels())) },
}).
Complete(c)
if err != nil {
return microerror.Mask(err)
}
// We put the controller into a booted state by closing its booted
// channel once so users know when to go ahead.
select {
case <-c.booted:
default:
close(c.booted)
}
// mgr.Start() blocks the boot process until it ends gracefully or fails.
err = mgr.Start(setupSignalHandler())
if err != nil {
return microerror.Mask(err)
}
}
return nil
}
func (c *Controller) deleteFunc(ctx context.Context, obj interface{}) error {
var err error
hasFinalizer, err := c.hasFinalizer(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
if !hasFinalizer {
return nil
}
err = ProcessDelete(ctx, obj, c.resources)
if err != nil {
return microerror.Mask(err)
}
err = c.removeFinalizer(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
return nil
}
func (c *Controller) hasPauseAnnotation(m map[string]string) bool {
for k, v := range m {
if hasAnnotation(c.pause, k, v) {
return true
}
}
return false
}
func (c *Controller) reconcile(ctx context.Context, req reconcile.Request, obj interface{}) (reconcile.Result, error) {
ctx, err := c.initCtx(ctx, obj)
if err != nil {
return reconcile.Result{}, microerror.Mask(err)
}
var m metav1.Object
{
m, err = meta.Accessor(obj)
if err != nil {
return reconcile.Result{}, microerror.Mask(err)
}
}
{
if c.hasPauseAnnotation(m.GetAnnotations()) {
c.logger.LogCtx(ctx, "level", "debug", "message", "found pause annotation")
c.logger.LogCtx(ctx, "level", "debug", "message", "cancelling reconciliation")
return reconcile.Result{}, nil
}
}
if m.GetDeletionTimestamp() != nil {
event := "delete"
t := prometheus.NewTimer(eventHistogram.WithLabelValues(event))
ctx = setLoggerCtxValue(ctx, loggerKeyEvent, event)
ctx = setLoggerCtxValue(ctx, loggerKeyObject, m.GetSelfLink())
ctx = setLoggerCtxValue(ctx, loggerKeyVersion, m.GetResourceVersion())
err = c.deleteFunc(ctx, obj)
if err != nil {
return reconcile.Result{}, microerror.Mask(err)
}
t.ObserveDuration()
} else {
event := "update"
t := prometheus.NewTimer(eventHistogram.WithLabelValues(event))
ctx = setLoggerCtxValue(ctx, loggerKeyEvent, event)
ctx = setLoggerCtxValue(ctx, loggerKeyObject, m.GetSelfLink())
ctx = setLoggerCtxValue(ctx, loggerKeyVersion, m.GetResourceVersion())
err = c.updateFunc(ctx, obj)
if err != nil {
return reconcile.Result{}, microerror.Mask(err)
}
t.ObserveDuration()
}
return reconcile.Result{}, nil
}
func (c *Controller) updateFunc(ctx context.Context, obj interface{}) error {
var err error
ok, err := c.addFinalizer(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
if ok {
// A finalizer was added, this causes a new update event, so we stop
// reconciling here and will pick up the new event.
return nil
}
err = ProcessUpdate(ctx, obj, c.resources)
if err != nil {
return microerror.Mask(err)
}
return nil
}
// ProcessDelete is a drop-in for an informer's DeleteFunc. It receives the
// custom object observed during custom resource watches and anything that
// implements Resource. ProcessDelete takes care about all necessary
// reconciliation logic for delete events.
//
// func deleteFunc(obj interface{}) {
// err := c.ProcessDelete(obj, resources)
// if err != nil {
// // error handling here
// }
// }
//
// newResourceEventHandler := &cache.ResourceEventHandlerFuncs{
// DeleteFunc: deleteFunc,
// }
//
func ProcessDelete(ctx context.Context, obj interface{}, resources []resource.Interface) error {
if len(resources) == 0 {
return microerror.Maskf(executionFailedError, "resources must not be empty")
}
ctx = reconciliationcanceledcontext.NewContext(ctx, make(chan struct{}))
defer func() {
ctx = unsetLoggerCtxValue(ctx, loggerKeyResource)
}()
for _, r := range resources {
ctx = setLoggerCtxValue(ctx, loggerKeyResource, r.Name())
ctx = resourcecanceledcontext.NewContext(ctx, make(chan struct{}))
err := r.EnsureDeleted(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
if reconciliationcanceledcontext.IsCanceled(ctx) {
return nil
}
}
return nil
}
// ProcessUpdate is a drop-in for an informer's UpdateFunc. It receives the new
// custom object observed during custom resource watches and anything that
// implements Resource. ProcessUpdate takes care about all necessary
// reconciliation logic for update events. For complex resources this means
// state has to be created, deleted and updated eventually, in this order.
//
// func updateFunc(oldObj, newObj interface{}) {
// err := c.ProcessUpdate(newObj, resources)
// if err != nil {
// // error handling here
// }
// }
//
// newResourceEventHandler := &cache.ResourceEventHandlerFuncs{
// UpdateFunc: updateFunc,
// }
//
func ProcessUpdate(ctx context.Context, obj interface{}, resources []resource.Interface) error {
if len(resources) == 0 {
return microerror.Maskf(executionFailedError, "resources must not be empty")
}
ctx = reconciliationcanceledcontext.NewContext(ctx, make(chan struct{}))
defer func() {
ctx = unsetLoggerCtxValue(ctx, loggerKeyResource)
}()
for _, r := range resources {
ctx = setLoggerCtxValue(ctx, loggerKeyResource, r.Name())
ctx = resourcecanceledcontext.NewContext(ctx, make(chan struct{}))
err := r.EnsureCreated(ctx, obj)
if err != nil {
return microerror.Mask(err)
}
if reconciliationcanceledcontext.IsCanceled(ctx) {
return nil
}
}
return nil
}
func hasAnnotation(annotations map[string]string, targetKey string, targetValue string) bool {
if annotations == nil {
return false
}
actualValue, ok := annotations[targetKey]
if !ok {
return false
}
return actualValue == targetValue
}
func setLoggerCtxValue(ctx context.Context, key, value string) context.Context {
m, ok := loggermeta.FromContext(ctx)
if !ok {
m = loggermeta.New()
ctx = loggermeta.NewContext(ctx, m)
}
m.KeyVals[key] = value
return ctx
}
func setupSignalHandler() (stopCh <-chan struct{}) {
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
func unsetLoggerCtxValue(ctx context.Context, key string) context.Context {
m, ok := loggermeta.FromContext(ctx)
if !ok {
m = loggermeta.New()
ctx = loggermeta.NewContext(ctx, m)
return ctx
}
delete(m.KeyVals, key)
return ctx
}