-
Notifications
You must be signed in to change notification settings - Fork 18
/
reconcilers.go
1704 lines (1500 loc) · 54.8 KB
/
reconcilers.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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2020 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package reconcilers
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"time"
"github.com/go-logr/logr"
"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/cache"
"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/cluster"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"github.com/vmware-labs/reconciler-runtime/tracker"
)
var (
_ reconcile.Reconciler = (*ParentReconciler)(nil)
)
// Config holds common resources for controllers. The configuration may be
// passed to sub-reconcilers.
type Config struct {
client.Client
APIReader client.Reader
Recorder record.EventRecorder
Tracker tracker.Tracker
// Deprecated: use a logger from the context instead. For example:
// * `log, err := logr.FromContext(ctx)`
// * `log := logr.FromContextOrDiscard(ctx)`
Log logr.Logger
}
func (c Config) IsEmpty() bool {
return c == Config{}
}
// WithCluster extends the config to access a new cluster.
func (c Config) WithCluster(cluster cluster.Cluster) Config {
return Config{
Client: cluster.GetClient(),
APIReader: cluster.GetAPIReader(),
Recorder: cluster.GetEventRecorderFor("controller"),
Log: c.Log,
Tracker: c.Tracker,
}
}
// TrackAndGet tracks the resources for changes and returns the current value. The track is
// registered even when the resource does not exists so that its creation can be tracked.
//
// Equivlent to calling both `c.Tracker.Track(...)` and `c.Client.Get(...)`
func (c Config) TrackAndGet(ctx context.Context, key types.NamespacedName, obj client.Object) error {
c.Tracker.Track(
ctx,
tracker.NewKey(gvk(obj, c.Scheme()), key),
RetrieveRequest(ctx).NamespacedName,
)
return c.Get(ctx, key, obj)
}
// NewConfig creates a Config for a specific API type. Typically passed into a
// reconciler.
func NewConfig(mgr ctrl.Manager, apiType client.Object, syncPeriod time.Duration) Config {
name := typeName(apiType)
log := newWarnOnceLogger(ctrl.Log.WithName("controllers").WithName(name))
return Config{
Log: log,
Tracker: tracker.New(2 * syncPeriod),
}.WithCluster(mgr)
}
// ParentReconciler is a controller-runtime reconciler that reconciles a given
// existing resource. The ParentType resource is fetched for the reconciler
// request and passed in turn to each SubReconciler. Finally, the reconciled
// resource's status is compared with the original status, updating the API
// server if needed.
type ParentReconciler struct {
// Name used to identify this reconciler. Defaults to `{Type}ParentReconciler`. Ideally
// unique, but not required to be so.
//
// +optional
Name string
// Type of resource to reconcile
Type client.Object
// Reconciler is called for each reconciler request with the parent
// resource being reconciled. Typically, Reconciler is a Sequence of
// multiple SubReconcilers.
Reconciler SubReconciler
Config Config
}
func (r *ParentReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
if r.Name == "" {
r.Name = fmt.Sprintf("%sParentReconciler", typeName(r.Type))
}
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name).
WithValues("parentType", gvk(r.Type, r.Config.Scheme()))
ctx = logr.NewContext(ctx, log)
ctx = StashConfig(ctx, r.Config)
ctx = StashParentConfig(ctx, r.Config)
ctx = StashParentType(ctx, r.Type)
ctx = StashCastParentType(ctx, r.Type)
if err := r.validate(ctx); err != nil {
return err
}
bldr := ctrl.NewControllerManagedBy(mgr).For(r.Type)
if err := r.Reconciler.SetupWithManager(ctx, mgr, bldr); err != nil {
return err
}
return bldr.Complete(r)
}
func (r *ParentReconciler) validate(ctx context.Context) error {
// validate Type value
if r.Type == nil {
return fmt.Errorf("ParentReconciler %q must define Type", r.Name)
}
// validate Reconciler value
if r.Reconciler == nil {
return fmt.Errorf("ParentReconciler %q must define Reconciler", r.Name)
}
// warn users of common pitfalls. These are not blockers.
log := logr.FromContextOrDiscard(ctx)
parentType := reflect.TypeOf(r.Type).Elem()
statusField, hasStatus := parentType.FieldByName("Status")
if !hasStatus {
log.Info("parent resource missing status field, operations related to status will be skipped")
return nil
}
statusType := statusField.Type
if statusType.Kind() == reflect.Ptr {
log.Info("parent status is nilable, status is typically a struct")
statusType = statusType.Elem()
}
observedGenerationField, hasObservedGeneration := statusType.FieldByName("ObservedGeneration")
if !hasObservedGeneration || observedGenerationField.Type.Kind() != reflect.Int64 {
log.Info("parent status missing ObservedGeneration field of type int64, generation will not be managed")
}
initializeConditionsMethod, hasInitializeConditions := reflect.PtrTo(statusType).MethodByName("InitializeConditions")
if !hasInitializeConditions || initializeConditionsMethod.Type.NumIn() != 1 || initializeConditionsMethod.Type.NumOut() != 0 {
log.Info("parent status missing InitializeConditions() method, conditions will not be auto-initialized")
}
conditionsField, hasConditions := statusType.FieldByName("Conditions")
if !hasConditions || !conditionsField.Type.AssignableTo(reflect.TypeOf([]metav1.Condition{})) {
log.Info("parent status is missing field Conditions of type []metav1.Condition, condition timestamps will not be managed")
}
return nil
}
func (r *ParentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctx = WithStash(ctx)
c := r.Config
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name).
WithValues("parentType", gvk(r.Type, c.Scheme()))
ctx = logr.NewContext(ctx, log)
ctx = StashRequest(ctx, req)
ctx = StashConfig(ctx, c)
ctx = StashParentConfig(ctx, c)
ctx = StashParentType(ctx, r.Type)
ctx = StashCastParentType(ctx, r.Type)
originalParent := r.Type.DeepCopyObject().(client.Object)
if err := c.Get(ctx, req.NamespacedName, originalParent); err != nil {
if apierrs.IsNotFound(err) {
// we'll ignore not-found errors, since they can't be fixed by an immediate
// requeue (we'll need to wait for a new notification), and we can get them
// on deleted requests.
return ctrl.Result{}, nil
}
log.Error(err, "unable to fetch resource")
return ctrl.Result{}, err
}
parent := originalParent.DeepCopyObject().(client.Object)
if defaulter, ok := parent.(webhook.Defaulter); ok {
// parent.Default()
defaulter.Default()
}
r.initializeConditions(parent)
result, err := r.reconcile(ctx, parent)
if r.hasStatus(originalParent) {
// restore last transition time for unchanged conditions
r.syncLastTransitionTime(r.conditions(parent), r.conditions(originalParent))
// check if status has changed before updating
parentStatus, originalParentStatus := r.status(parent), r.status(originalParent)
if !equality.Semantic.DeepEqual(parentStatus, originalParentStatus) && parent.GetDeletionTimestamp() == nil {
// update status
log.Info("updating status", "diff", cmp.Diff(originalParentStatus, parentStatus))
if updateErr := c.Status().Update(ctx, parent); updateErr != nil {
log.Error(updateErr, "unable to update status")
c.Recorder.Eventf(parent, corev1.EventTypeWarning, "StatusUpdateFailed",
"Failed to update status: %v", updateErr)
return ctrl.Result{}, updateErr
}
c.Recorder.Eventf(parent, corev1.EventTypeNormal, "StatusUpdated",
"Updated status")
}
}
// return original reconcile result
return result, err
}
func (r *ParentReconciler) reconcile(ctx context.Context, parent client.Object) (ctrl.Result, error) {
if parent.GetDeletionTimestamp() != nil && len(parent.GetFinalizers()) == 0 {
// resource is being deleted and has no pending finalizers, nothing to do
return ctrl.Result{}, nil
}
result, err := r.Reconciler.Reconcile(ctx, parent)
if err != nil {
return ctrl.Result{}, err
}
r.copyGeneration(parent)
return result, nil
}
func (r *ParentReconciler) initializeConditions(obj client.Object) {
status := r.status(obj)
if status == nil {
return
}
initializeConditions := reflect.ValueOf(status).MethodByName("InitializeConditions")
if !initializeConditions.IsValid() {
return
}
if t := initializeConditions.Type(); t.Kind() != reflect.Func || t.NumIn() != 0 || t.NumOut() != 0 {
return
}
initializeConditions.Call([]reflect.Value{})
}
func (r *ParentReconciler) conditions(obj client.Object) []metav1.Condition {
// return obj.Status.Conditions
status := r.status(obj)
if status == nil {
return nil
}
statusValue := reflect.ValueOf(status).Elem()
conditionsValue := statusValue.FieldByName("Conditions")
if !conditionsValue.IsValid() || conditionsValue.IsZero() {
return nil
}
conditions, ok := conditionsValue.Interface().([]metav1.Condition)
if !ok {
return nil
}
return conditions
}
func (r *ParentReconciler) copyGeneration(obj client.Object) {
// obj.Status.ObservedGeneration = obj.Generation
status := r.status(obj)
if status == nil {
return
}
statusValue := reflect.ValueOf(status).Elem()
if !statusValue.IsValid() {
return
}
observedGenerationValue := statusValue.FieldByName("ObservedGeneration")
if observedGenerationValue.Kind() != reflect.Int64 || !observedGenerationValue.CanSet() {
return
}
generation := obj.GetGeneration()
observedGenerationValue.SetInt(generation)
}
func (r *ParentReconciler) hasStatus(obj client.Object) bool {
status := r.status(obj)
return status != nil
}
func (r *ParentReconciler) status(obj client.Object) interface{} {
if obj == nil {
return nil
}
statusValue := reflect.ValueOf(obj).Elem().FieldByName("Status")
if statusValue.Kind() == reflect.Ptr {
statusValue = statusValue.Elem()
}
if !statusValue.IsValid() || !statusValue.CanAddr() {
return nil
}
return statusValue.Addr().Interface()
}
// syncLastTransitionTime restores a condition's LastTransitionTime value for
// each proposed condition that is otherwise equivlent to the original value.
// This method is useful to prevent updating the status for a resource that is
// otherwise unchanged.
func (r *ParentReconciler) syncLastTransitionTime(proposed, original []metav1.Condition) {
for _, o := range original {
for i := range proposed {
p := &proposed[i]
if o.Type == p.Type {
if o.Status == p.Status &&
o.Reason == p.Reason &&
o.Message == p.Message &&
o.ObservedGeneration == p.ObservedGeneration {
p.LastTransitionTime = o.LastTransitionTime
}
break
}
}
}
}
const requestStashKey StashKey = "reconciler-runtime:request"
const configStashKey StashKey = "reconciler-runtime:config"
const parentConfigStashKey StashKey = "reconciler-runtime:parentConfig"
const parentTypeStashKey StashKey = "reconciler-runtime:parentType"
const castParentTypeStashKey StashKey = "reconciler-runtime:castParentType"
func StashRequest(ctx context.Context, req ctrl.Request) context.Context {
return context.WithValue(ctx, requestStashKey, req)
}
func StashConfig(ctx context.Context, config Config) context.Context {
return context.WithValue(ctx, configStashKey, config)
}
func StashParentConfig(ctx context.Context, parentConfig Config) context.Context {
return context.WithValue(ctx, parentConfigStashKey, parentConfig)
}
func StashParentType(ctx context.Context, parentType client.Object) context.Context {
return context.WithValue(ctx, parentTypeStashKey, parentType)
}
func StashCastParentType(ctx context.Context, currentType client.Object) context.Context {
return context.WithValue(ctx, castParentTypeStashKey, currentType)
}
// RetrieveRequest returns the reconciler Request from the context, or empty if not found.
func RetrieveRequest(ctx context.Context) ctrl.Request {
value := ctx.Value(requestStashKey)
if req, ok := value.(ctrl.Request); ok {
return req
}
return ctrl.Request{}
}
// RetrieveConfig returns the Config from the context. An error is returned if not found.
func RetrieveConfig(ctx context.Context) (Config, error) {
value := ctx.Value(configStashKey)
if config, ok := value.(Config); ok {
return config, nil
}
return Config{}, fmt.Errorf("config must exist on the context. Check that the context is from a ParentReconciler or WithConfig")
}
// RetrieveConfigOrDie returns the Config from the context. Panics if not found.
func RetrieveConfigOrDie(ctx context.Context) Config {
config, err := RetrieveConfig(ctx)
if err != nil {
panic(err)
}
return config
}
// RetrieveParentConfig returns the Config from the context used to load the parent resource. An
// error is returned if not found.
func RetrieveParentConfig(ctx context.Context) (Config, error) {
value := ctx.Value(parentConfigStashKey)
if parentConfig, ok := value.(Config); ok {
return parentConfig, nil
}
return Config{}, fmt.Errorf("parent config must exist on the context. Check that the context is from a ParentReconciler")
}
// RetrieveParentConfigOrDie returns the Config from the context used to load the parent resource.
// Panics if not found.
func RetrieveParentConfigOrDie(ctx context.Context) Config {
config, err := RetrieveParentConfig(ctx)
if err != nil {
panic(err)
}
return config
}
// RetrieveParentType returns the parent type object, or nil if not found.
func RetrieveParentType(ctx context.Context) client.Object {
value := ctx.Value(parentTypeStashKey)
if parentType, ok := value.(client.Object); ok {
return parentType
}
return nil
}
// RetrieveCastParentType returns the parent type object, or nil if not found.
func RetrieveCastParentType(ctx context.Context) client.Object {
value := ctx.Value(castParentTypeStashKey)
if currentType, ok := value.(client.Object); ok {
return currentType
}
return nil
}
// SubReconciler are participants in a larger reconciler request. The resource
// being reconciled is passed directly to the sub reconciler. The resource's
// status can be mutated to reflect the current state.
type SubReconciler interface {
SetupWithManager(ctx context.Context, mgr ctrl.Manager, bldr *builder.Builder) error
Reconcile(ctx context.Context, parent client.Object) (ctrl.Result, error)
}
var (
_ SubReconciler = (*SyncReconciler)(nil)
_ SubReconciler = (*ChildReconciler)(nil)
_ SubReconciler = (Sequence)(nil)
_ SubReconciler = (*CastParent)(nil)
_ SubReconciler = (*WithConfig)(nil)
_ SubReconciler = (*WithFinalizer)(nil)
)
// SyncReconciler is a sub reconciler for custom reconciliation logic. No
// behavior is defined directly.
type SyncReconciler struct {
// Name used to identify this reconciler. Defaults to `SyncReconciler`. Ideally unique, but
// not required to be so.
//
// +optional
Name string
// Setup performs initialization on the manager and builder this reconciler
// will run with. It's common to setup field indexes and watch resources.
//
// +optional
Setup func(ctx context.Context, mgr ctrl.Manager, bldr *builder.Builder) error
// SyncDuringFinalization indicates the Sync method should be called when the resource is pending deletion.
SyncDuringFinalization bool
// Sync does whatever work is necessary for the reconciler.
//
// If SyncDuringFinalization is true this method is called when the resource is pending
// deletion. This is useful if the reconciler is managing reference data.
//
// Expected function signature:
// func(ctx context.Context, parent client.Object) error
// func(ctx context.Context, parent client.Object) (ctrl.Result, error)
Sync interface{}
// Finalize does whatever work is necessary for the reconciler when the resource is pending
// deletion. If this reconciler sets a finalizer it should do the necessary work to clean up
// state the finalizer represents and then clear the finalizer.
//
// Expected function signature:
// func(ctx context.Context, parent client.Object) error
// func(ctx context.Context, parent client.Object) (ctrl.Result, error)
//
// +optional
Finalize interface{}
}
func (r *SyncReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, bldr *builder.Builder) error {
if r.Name == "" {
r.Name = "SyncReconciler"
}
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name)
ctx = logr.NewContext(ctx, log)
if r.Setup == nil {
return nil
}
if err := r.validate(ctx); err != nil {
return err
}
return r.Setup(ctx, mgr, bldr)
}
func (r *SyncReconciler) validate(ctx context.Context) error {
// validate Sync function signature:
// func(ctx context.Context, parent client.Object) error
// func(ctx context.Context, parent client.Object) (ctrl.Result, error)
if r.Sync == nil {
return fmt.Errorf("SyncReconciler %q must implement Sync", r.Name)
} else {
castParentType := RetrieveCastParentType(ctx)
fn := reflect.TypeOf(r.Sync)
err := fmt.Errorf("SyncReconciler %q must implement Sync: func(context.Context, %s) error | func(context.Context, %s) (ctrl.Result, error), found: %s", r.Name, reflect.TypeOf(castParentType), reflect.TypeOf(castParentType), fn)
if fn.NumIn() != 2 ||
!reflect.TypeOf((*context.Context)(nil)).Elem().AssignableTo(fn.In(0)) ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(1)) {
return err
}
switch fn.NumOut() {
case 1:
if !reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.Out(0)) {
return err
}
case 2:
if !reflect.TypeOf(ctrl.Result{}).AssignableTo(fn.Out(0)) ||
!reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.Out(1)) {
return err
}
default:
return err
}
}
// validate Finalize function signature:
// nil
// func(ctx context.Context, parent client.Object) error
// func(ctx context.Context, parent client.Object) (ctrl.Result, error)
if r.Finalize != nil {
castParentType := RetrieveCastParentType(ctx)
fn := reflect.TypeOf(r.Finalize)
err := fmt.Errorf("SyncReconciler %q must implement Finalize: nil | func(context.Context, %s) error | func(context.Context, %s) (ctrl.Result, error), found: %s", r.Name, reflect.TypeOf(castParentType), reflect.TypeOf(castParentType), fn)
if fn.NumIn() != 2 ||
!reflect.TypeOf((*context.Context)(nil)).Elem().AssignableTo(fn.In(0)) ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(1)) {
return err
}
switch fn.NumOut() {
case 1:
if !reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.Out(0)) {
return err
}
case 2:
if !reflect.TypeOf(ctrl.Result{}).AssignableTo(fn.Out(0)) ||
!reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.Out(1)) {
return err
}
default:
return err
}
}
return nil
}
func (r *SyncReconciler) Reconcile(ctx context.Context, parent client.Object) (ctrl.Result, error) {
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name)
ctx = logr.NewContext(ctx, log)
result := ctrl.Result{}
if parent.GetDeletionTimestamp() == nil || r.SyncDuringFinalization {
syncResult, err := r.sync(ctx, parent)
if err != nil {
log.Error(err, "unable to sync")
return ctrl.Result{}, err
}
result = AggregateResults(result, syncResult)
}
if parent.GetDeletionTimestamp() != nil {
finalizeResult, err := r.finalize(ctx, parent)
if err != nil {
log.Error(err, "unable to finalize")
return ctrl.Result{}, err
}
result = AggregateResults(result, finalizeResult)
}
return result, nil
}
func (r *SyncReconciler) sync(ctx context.Context, parent client.Object) (ctrl.Result, error) {
fn := reflect.ValueOf(r.Sync)
out := fn.Call([]reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(parent),
})
result := ctrl.Result{}
var err error
switch len(out) {
case 2:
result = out[0].Interface().(ctrl.Result)
if !out[1].IsNil() {
err = out[1].Interface().(error)
}
case 1:
if !out[0].IsNil() {
err = out[0].Interface().(error)
}
}
return result, err
}
func (r *SyncReconciler) finalize(ctx context.Context, parent client.Object) (ctrl.Result, error) {
if r.Finalize == nil {
return ctrl.Result{}, nil
}
fn := reflect.ValueOf(r.Finalize)
out := fn.Call([]reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(parent),
})
result := ctrl.Result{}
var err error
switch len(out) {
case 2:
result = out[0].Interface().(ctrl.Result)
if !out[1].IsNil() {
err = out[1].Interface().(error)
}
case 1:
if !out[0].IsNil() {
err = out[0].Interface().(error)
}
}
return result, err
}
var (
OnlyReconcileChildStatus = errors.New("skip reconciler create/update/delete behavior for the child resource, while still reflecting the existing child's status on the parent")
)
// ChildReconciler is a sub reconciler that manages a single child resource for
// a parent. The reconciler will ensure that exactly one child will match the
// desired state by:
// - creating a child if none exists
// - updating an existing child
// - removing an unneeded child
// - removing extra children
//
// The flow for each reconciliation request is:
// - DesiredChild
// - if child is desired:
// - HarmonizeImmutableFields (optional)
// - SemanticEquals
// - MergeBeforeUpdate
// - ReflectChildStatusOnParent
//
// During setup, the child resource type is registered to watch for changes.
type ChildReconciler struct {
// Name used to identify this reconciler. Defaults to `{ChildType}ChildReconciler`. Ideally
// unique, but not required to be so.
//
// +optional
Name string
// ChildType is the resource being created/updated/deleted by the
// reconciler. For example, a parent Deployment would have a ReplicaSet as a
// child.
ChildType client.Object
// ChildListType is the listing type for the child type. For example,
// PodList is the list type for Pod
ChildListType client.ObjectList
// Finalizer is set on the parent resource before a child resource is created, and cleared
// after a child resource is deleted. The value must be unique to this specific reconciler
// instance and not shared. Reusing a value may result in orphaned resources when the parent
// resource is deleted.
//
// Using a finalizer is encouraged when the Kubernetes garbage collector is unable to delete
// the child resource automatically, like when the parent and child are in different
// namespaces, scopes or clusters.
//
// Use of a finalizer implies that SkipOwnerReference is true, and OurChild must be defined.
//
// +optional
Finalizer string
// SkipOwnerReference when true will not create and find child resources via an owner
// reference. OurChild must be defined for the reconciler to distinguish the child being
// reconciled from other resources of the same type.
//
// Any child resource created is tracked for changes.
SkipOwnerReference bool
// Setup performs initialization on the manager and builder this reconciler
// will run with. It's common to setup field indexes and watch resources.
//
// +optional
Setup func(ctx context.Context, mgr ctrl.Manager, bldr *builder.Builder) error
// DesiredChild returns the desired child object for the given parent
// object, or nil if the child should not exist.
//
// To skip reconciliation of the child resource while still reflecting an
// existing child's status on the parent, return OnlyReconcileChildStatus as
// an error.
//
// Expected function signature:
// func(ctx context.Context, parent client.Object) (client.Object, error)
DesiredChild interface{}
// ReflectChildStatusOnParent updates the parent object's status with values
// from the child. Select types of error are passed, including:
// - apierrs.IsConflict
//
// Expected function signature:
// func(parent, child client.Object, err error)
ReflectChildStatusOnParent interface{}
// HarmonizeImmutableFields allows fields that are immutable on the current
// object to be copied to the desired object in order to avoid creating
// updates which are guaranteed to fail.
//
// Expected function signature:
// func(current, desired client.Object)
//
// +optional
HarmonizeImmutableFields interface{}
// MergeBeforeUpdate copies desired fields on to the current object before
// calling update. Typically fields to copy are the Spec, Labels and
// Annotations.
//
// Expected function signature:
// func(current, desired client.Object)
MergeBeforeUpdate interface{}
// SemanticEquals compares two child resources returning true if there is a
// meaningful difference that should trigger an update.
//
// Expected function signature:
// func(a1, a2 client.Object) bool
SemanticEquals interface{}
// ListOptions allows custom options to be use when listing potential child resources. Each
// resource retrieved as part of the listing is confirmed via OurChild.
//
// Defaults to filtering by the parent's namespace:
// []client.ListOption{
// client.InNamespace(parent.GetNamespace()),
// }
//
// Expected function signature:
// func(ctx context.Context, parent client.Object) []client.ListOption
//
// +optional
ListOptions interface{}
// OurChild is used when there are multiple ChildReconciler for the same ChildType
// controlled by the same parent object. The function return true for child resources
// managed by this ChildReconciler. Objects returned from the DesiredChild function
// should match this function, otherwise they may be orphaned. If not specified, all
// children match.
//
// OurChild is required when a Finalizer is defined or SkipOwnerReference is true.
//
// Expected function signature:
// func(parent, child client.Object) bool
//
// +optional
OurChild interface{}
// Sanitize is called with an object before logging the value. Any value may
// be returned. A meaningful subset of the resource is typically returned,
// like the Spec.
//
// Expected function signature:
// func(child client.Object) interface{}
//
// +optional
Sanitize interface{}
// mutationCache holds patches received from updates to a resource made by
// mutation webhooks. This cache is used to avoid unnecessary update calls
// that would actually have no effect.
mutationCache *cache.Expiring
lazyInit sync.Once
}
func (r *ChildReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, bldr *builder.Builder) error {
c := RetrieveConfigOrDie(ctx)
if r.Name == "" {
r.Name = fmt.Sprintf("%sChildReconciler", typeName(r.ChildType))
}
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name).
WithValues("childType", gvk(r.ChildType, c.Scheme()))
ctx = logr.NewContext(ctx, log)
if err := r.validate(ctx); err != nil {
return err
}
if r.SkipOwnerReference {
bldr.Watches(&source.Kind{Type: r.ChildType}, EnqueueTracked(ctx, r.ChildType))
} else {
bldr.Owns(r.ChildType)
}
if r.Setup == nil {
return nil
}
return r.Setup(ctx, mgr, bldr)
}
func (r *ChildReconciler) validate(ctx context.Context) error {
castParentType := RetrieveCastParentType(ctx)
// default implicit values
if r.Finalizer != "" {
r.SkipOwnerReference = true
}
// validate ChildType value
if r.ChildType == nil {
return fmt.Errorf("ChildReconciler %q must define ChildType", r.Name)
}
// validate ChildListType value
if r.ChildListType == nil {
return fmt.Errorf("ChildReconciler %q must define ChildListType", r.Name)
}
// validate DesiredChild function signature:
// func(ctx context.Context, parent client.Object) (client.Object, error)
if r.DesiredChild == nil {
return fmt.Errorf("ChildReconciler %q must implement DesiredChild", r.Name)
} else {
fn := reflect.TypeOf(r.DesiredChild)
if fn.NumIn() != 2 || fn.NumOut() != 2 ||
!reflect.TypeOf((*context.Context)(nil)).Elem().AssignableTo(fn.In(0)) ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(1)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.Out(0)) ||
!reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.Out(1)) {
return fmt.Errorf("ChildReconciler %q must implement DesiredChild: func(context.Context, %s) (%s, error), found: %s", r.Name, reflect.TypeOf(castParentType), reflect.TypeOf(r.ChildType), fn)
}
}
// validate ReflectChildStatusOnParent function signature:
// func(parent, child client.Object, err error)
if r.ReflectChildStatusOnParent == nil {
return fmt.Errorf("ChildReconciler %q must implement ReflectChildStatusOnParent", r.Name)
} else {
fn := reflect.TypeOf(r.ReflectChildStatusOnParent)
if fn.NumIn() != 3 || fn.NumOut() != 0 ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(0)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(1)) ||
!reflect.TypeOf((*error)(nil)).Elem().AssignableTo(fn.In(2)) {
return fmt.Errorf("ChildReconciler %q must implement ReflectChildStatusOnParent: func(%s, %s, error), found: %s", r.Name, reflect.TypeOf(castParentType), reflect.TypeOf(r.ChildType), fn)
}
}
// validate HarmonizeImmutableFields function signature:
// nil
// func(current, desired client.Object)
if r.HarmonizeImmutableFields != nil {
fn := reflect.TypeOf(r.HarmonizeImmutableFields)
if fn.NumIn() != 2 || fn.NumOut() != 0 ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(0)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(1)) {
return fmt.Errorf("ChildReconciler %q must implement HarmonizeImmutableFields: nil | func(%s, %s), found: %s", r.Name, reflect.TypeOf(r.ChildType), reflect.TypeOf(r.ChildType), fn)
}
}
// validate MergeBeforeUpdate function signature:
// func(current, desired client.Object)
if r.MergeBeforeUpdate == nil {
return fmt.Errorf("ChildReconciler %q must implement MergeBeforeUpdate", r.Name)
} else {
fn := reflect.TypeOf(r.MergeBeforeUpdate)
if fn.NumIn() != 2 || fn.NumOut() != 0 ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(0)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(1)) {
return fmt.Errorf("ChildReconciler %q must implement MergeBeforeUpdate: func(%s, %s), found: %s", r.Name, reflect.TypeOf(r.ChildType), reflect.TypeOf(r.ChildType), fn)
}
}
// validate SemanticEquals function signature:
// func(a1, a2 client.Object) bool
if r.SemanticEquals == nil {
return fmt.Errorf("ChildReconciler %q must implement SemanticEquals", r.Name)
} else {
fn := reflect.TypeOf(r.SemanticEquals)
if fn.NumIn() != 2 || fn.NumOut() != 1 ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(0)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(1)) ||
fn.Out(0).Kind() != reflect.Bool {
return fmt.Errorf("ChildReconciler %q must implement SemanticEquals: func(%s, %s) bool, found: %s", r.Name, reflect.TypeOf(r.ChildType), reflect.TypeOf(r.ChildType), fn)
}
}
// validate ListOptions function signature:
// nil
// func(ctx context.Context, parent client.Object) []client.ListOption
if r.ListOptions != nil {
fn := reflect.TypeOf(r.ListOptions)
if fn.NumIn() != 2 || fn.NumOut() != 1 ||
!reflect.TypeOf((*context.Context)(nil)).Elem().AssignableTo(fn.In(0)) ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(1)) ||
!reflect.TypeOf([]client.ListOption{}).AssignableTo(fn.Out(0)) {
return fmt.Errorf("ChildReconciler %q must implement ListOptions: nil | func(context.Context, %s) []client.ListOption, found: %s", r.Name, reflect.TypeOf(castParentType), fn)
}
}
// validate OurChild function signature:
// nil
// func(parent, child client.Object) bool
if r.OurChild != nil {
fn := reflect.TypeOf(r.OurChild)
if fn.NumIn() != 2 || fn.NumOut() != 1 ||
!reflect.TypeOf(castParentType).AssignableTo(fn.In(0)) ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(1)) ||
fn.Out(0).Kind() != reflect.Bool {
return fmt.Errorf("ChildReconciler %q must implement OurChild: nil | func(%s, %s) bool, found: %s", r.Name, reflect.TypeOf(castParentType), reflect.TypeOf(r.ChildType), fn)
}
}
if r.OurChild == nil && r.SkipOwnerReference {
// OurChild is required when SkipOwnerReference is true
return fmt.Errorf("ChildReconciler %q must implement OurChild since owner references are not used", r.Name)
}
// validate Sanitize function signature:
// nil
// func(child client.Object) interface{}
if r.Sanitize != nil {
fn := reflect.TypeOf(r.Sanitize)
if fn.NumIn() != 1 || fn.NumOut() != 1 ||
!reflect.TypeOf(r.ChildType).AssignableTo(fn.In(0)) {
return fmt.Errorf("ChildReconciler %q must implement Sanitize: nil | func(%s) interface{}, found: %s", r.Name, reflect.TypeOf(r.ChildType), fn)
}
}
return nil
}
func (r *ChildReconciler) Reconcile(ctx context.Context, parent client.Object) (ctrl.Result, error) {
c := RetrieveConfigOrDie(ctx)
log := logr.FromContextOrDiscard(ctx).
WithName(r.Name).
WithValues("childType", gvk(r.ChildType, c.Scheme()))
ctx = logr.NewContext(ctx, log)
r.lazyInit.Do(func() {
r.mutationCache = cache.NewExpiring()
})
child, err := r.reconcile(ctx, parent)
if parent.GetDeletionTimestamp() != nil {
return ctrl.Result{}, err
}
if err != nil {
if apierrs.IsAlreadyExists(err) {
// check if the resource blocking create is owned by the parent.
// the created child from a previous turn may be slow to appear in the informer cache, but shouldn't appear
// on the parent as being not ready.
apierr := err.(apierrs.APIStatus)
conflicted := newEmpty(r.ChildType).(client.Object)
_ = c.APIReader.Get(ctx, types.NamespacedName{Namespace: parent.GetNamespace(), Name: apierr.Status().Details.Name}, conflicted)
if r.ourChild(parent, conflicted) {
// skip updating the parent's status, fail and try again
return ctrl.Result{}, err
}
log.Info("unable to reconcile child, not owned", "child", namespaceName(conflicted), "ownerRefs", conflicted.GetOwnerReferences())
r.reflectChildStatusOnParent(parent, child, err)