-
Notifications
You must be signed in to change notification settings - Fork 85
/
reconciler.go
847 lines (715 loc) · 25.2 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
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
/*
Copyright 2019 The Kubernetes Authors.
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 declarative
import (
"context"
"errors"
"fmt"
"net/http"
"path/filepath"
"reflect"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
recorder "k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/kustomize/kyaml/filesys"
"sigs.k8s.io/kubebuilder-declarative-pattern/commonclient"
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/addon/pkg/utils"
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/declarative/kustomize"
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/declarative/pkg/applier"
"sigs.k8s.io/kubebuilder-declarative-pattern/pkg/patterns/declarative/pkg/manifest"
)
var _ reconcile.Reconciler = &Reconciler{}
type Reconciler struct {
prototype DeclarativeObject
client client.Client
restConfig *rest.Config
httpClient *http.Client
dynamicClient dynamic.Interface
restMapper meta.RESTMapper
metrics reconcileMetrics
mgr manager.Manager
// recorder is the EventRecorder for creating k8s events
recorder recorder.EventRecorder
options reconcilerParams
}
type DeclarativeObject interface {
runtime.Object
metav1.Object
}
// Pruner is a trait for addon CRDs that determines whether pruning behavior should be enabled for the current CR.
// To enable this feature, it's necessary to enable WithApplyPrune. If WithApplyPrune is enabled but Pruner is not
// implemented, Prune behavior is assumed by default.
type Pruner interface {
Prune() bool
}
// PruneWhiteLister is a trait for addon CRDs that determines which kind of resources should be pruned. It's useful
// when CR in installed by Addon and want to prune them automatically. The format of array item should be exactly like
// <group>/<version>/<kind> (core group using 'core' indeed). For example: ["core/v1/ConfigMap", "batch/v1/Job"].
// Notice: kubeadm has a built-in prune white list, and it will be ignored if this method is implemented.
type PruneWhiteLister interface {
PruneWhiteList() []string
}
type ErrorResult struct {
Result reconcile.Result
Err error
}
func (e *ErrorResult) Error() string {
if e.Err != nil {
return e.Err.Error()
}
return ""
}
// For mocking
var defaultApplier = applier.DefaultApplier
func (r *Reconciler) Init(mgr manager.Manager, prototype DeclarativeObject, opts ...ReconcilerOption) error {
r.prototype = prototype
// TODO: Can we derive the name from prototype?
controllerName := "addon-controller"
r.recorder = mgr.GetEventRecorderFor(controllerName)
r.client = mgr.GetClient()
r.restConfig = mgr.GetConfig()
httpClient, err := commonclient.GetHTTPClient(mgr)
if err != nil {
return fmt.Errorf("getting HTTP client: %w", err)
}
r.httpClient = httpClient
r.mgr = mgr
globalObjectTracker.mgr = mgr
d, err := dynamic.NewForConfigAndClient(r.restConfig, r.httpClient)
if err != nil {
return err
}
r.dynamicClient = d
r.restMapper = mgr.GetRESTMapper()
if err := r.applyOptions(opts...); err != nil {
return err
}
if err := r.validateOptions(); err != nil {
return err
}
if r.CollectMetrics() {
if gvk, err := apiutil.GVKForObject(prototype, r.mgr.GetScheme()); err != nil {
return err
} else {
r.metrics = reconcileMetricsFor(gvk)
}
}
return nil
}
// +rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
var result reconcile.Result
statusInfo := &StatusInfo{}
log := log.FromContext(ctx)
defer func() {
r.collectMetrics(request, result, statusInfo.Err)
}()
// Fetch the object
instance := r.prototype.DeepCopyObject().(DeclarativeObject)
if err := r.client.Get(ctx, request.NamespacedName, instance); err != nil {
if apierrors.IsNotFound(err) {
// Object not found, return. Created objects are automatically garbage collected.
// For additional cleanup logic use finalizers.
return result, nil
}
// Error reading the object - requeue the request.
log.Error(err, "error reading object")
statusInfo.Err = err
return result, statusInfo.Err
}
// status.Reconciled should catch all error
defer func() {
if r.options.status != nil {
if statusErr := r.options.status.Reconciled(ctx, instance, statusInfo.Manifest, statusInfo.Err); statusErr != nil {
log.Error(statusErr, "failed to reconcile status")
}
}
}()
original := instance.DeepCopyObject().(DeclarativeObject)
if r.options.status != nil {
if err := r.options.status.Preflight(ctx, instance); err != nil {
if errorResult, ok := err.(*ErrorResult); ok {
// the user was specific about what they wanted to return; respect that
return errorResult.Result, errorResult.Err
}
log.Error(err, "preflight check failed, not reconciling")
statusInfo.Err = err
return result, statusInfo.Err
}
}
var reconcileErr error
statusInfo, reconcileErr = r.reconcileExists(ctx, request.NamespacedName, instance)
if reconcileErr != nil {
statusInfo.Err = reconcileErr
}
// Unpack ErrorResult (for example a retry)
if errorResult, ok := statusInfo.Err.(*ErrorResult); ok {
result = errorResult.Result
statusInfo.Err = errorResult.Err
}
if statusInfo.Err != nil {
r.recorder.Eventf(instance, "Warning", "InternalError", "internal error: %v", statusInfo.Err)
}
if r.options.status != nil {
if err := r.options.status.BuildStatus(ctx, statusInfo); err != nil {
if statusInfo.Err == nil {
statusInfo.Err = err
}
log.Error(err, "error building status")
return result, statusInfo.Err
}
}
if err := r.updateStatus(ctx, original, instance); err != nil {
if statusInfo.Err == nil {
statusInfo.Err = err
}
log.Error(err, "error updating status")
}
return result, statusInfo.Err
}
func (r *Reconciler) updateStatus(ctx context.Context, original DeclarativeObject, instance DeclarativeObject) error {
log := log.FromContext(ctx)
// Write the status if it has changed
oldStatus, err := utils.GetCommonStatus(original)
if err != nil {
log.Error(err, "error getting status")
return err
}
newStatus, err := utils.GetCommonStatus(instance)
if err != nil {
log.Error(err, "error getting status")
return err
}
statusOperation := &UpdateStatusOperation{}
for _, hook := range r.options.hooks {
if beforeUpdateStatus, ok := hook.(BeforeUpdateStatus); ok {
if err := beforeUpdateStatus.BeforeUpdateStatus(ctx, statusOperation); err != nil {
log.Error(err, "calling BeforeUpdateStatus hook")
return fmt.Errorf("error calling BeforeUpdateStatus hook: %w", err)
}
}
}
if !reflect.DeepEqual(oldStatus, newStatus) {
if err := r.client.Status().Update(ctx, instance); err != nil {
log.Error(err, "error updating status")
return err
}
}
for _, hook := range r.options.hooks {
if afterUpdateStatus, ok := hook.(AfterUpdateStatus); ok {
if err := afterUpdateStatus.AfterUpdateStatus(ctx, statusOperation); err != nil {
log.Error(err, "calling AfterUpdateStatus hook")
return fmt.Errorf("error calling AfterUpdateStatus hook: %w", err)
}
}
}
return nil
}
func (r *Reconciler) reconcileExists(ctx context.Context, name types.NamespacedName, instance DeclarativeObject) (*StatusInfo, error) {
log := log.FromContext(ctx)
log.WithValues("object", name.String()).Info("reconciling")
statusInfo := &StatusInfo{
Subject: instance,
}
var fs filesys.FileSystem
if r.IsKustomizeOptionUsed() {
fs = filesys.MakeFsInMemory()
}
objects, err := r.BuildDeploymentObjectsWithFs(ctx, name, instance, fs)
if err != nil {
log.Error(err, "building deployment objects")
return statusInfo, fmt.Errorf("error building deployment objects: %v", err)
}
objects, err = flattenListObjects(objects)
if err != nil {
log.Error(err, "flattening list objects")
return statusInfo, fmt.Errorf("error flattening list objects: %w", err)
}
log.WithValues("objects", fmt.Sprintf("%d", len(objects.Items))).Info("built deployment objects")
statusInfo.Manifest = objects
if r.options.status != nil {
isValidVersion, err := r.options.status.VersionCheck(ctx, instance, objects)
if err != nil {
if !isValidVersion {
statusInfo.KnownError = KnownErrorVersionCheckFailed
r.recorder.Event(instance, "Warning", "Failed version check", err.Error())
log.Error(err, "Version check failed, not reconciling")
return statusInfo, nil
} else {
log.Error(err, "Version check failed")
return statusInfo, err
}
}
}
err = r.setNamespaces(ctx, instance, objects)
if err != nil {
return statusInfo, err
}
err = r.injectOwnerRef(ctx, instance, objects)
if err != nil {
return statusInfo, err
}
var newItems []*manifest.Object
for _, obj := range objects.Items {
unstruct, err := GetObjectFromCluster(obj, r)
if err != nil && !apierrors.IsNotFound(errors.Unwrap(err)) {
log.WithValues("name", obj.GetName()).Error(err, "Unable to get resource")
}
if unstruct != nil {
annotations := unstruct.GetAnnotations()
if _, ok := annotations["addons.k8s.io/ignore"]; ok {
log.WithValues("kind", obj.Kind).WithValues("name", obj.GetName()).Info("Found ignore annotation on object, " +
"skipping object")
continue
}
}
newItems = append(newItems, obj)
}
objects.Items = newItems
extraArgs := []string{}
// allow user disable prune in CR
if p, ok := instance.(Pruner); (!ok && r.options.prune) || (ok && r.options.prune && p.Prune()) {
var labels []string
for k, v := range r.options.labelMaker(ctx, instance) {
labels = append(labels, fmt.Sprintf("%s=%s", k, v))
}
extraArgs = append(extraArgs, "--prune", "--selector", strings.Join(labels, ","))
if lister, ok := instance.(PruneWhiteLister); ok {
for _, gvk := range lister.PruneWhiteList() {
extraArgs = append(extraArgs, "--prune-whitelist", gvk)
}
}
}
ns := ""
if !r.options.preserveNamespace {
ns = name.Namespace
}
if r.CollectMetrics() {
if errs := globalObjectTracker.addIfNotPresent(objects.Items, ns); errs != nil {
for _, err := range errs.Errors() {
if errors.Is(err, noRESTMapperErr{}) {
log.WithName("declarative_reconciler").Error(err, "failed to get corresponding RESTMapper from API server")
} else if errors.Is(err, emptyNamespaceErr{}) {
// There should be no route to this path
log.WithName("declarative_reconciler").Info("Scoped object, but no namespace specified")
} else {
log.WithName("declarative_reconciler").Error(err, "Unknown error")
}
}
}
}
gvk, err := apiutil.GVKForObject(instance, r.mgr.GetScheme())
if err != nil {
return statusInfo, fmt.Errorf("getting GVK for %T: %w", instance, err)
}
parentRef, err := applier.NewParentRef(r.restMapper, instance, gvk, instance.GetName(), instance.GetNamespace())
if err != nil {
return statusInfo, fmt.Errorf("building applyset parent: %w", err)
}
applierOpt := applier.ApplierOptions{
RESTConfig: r.restConfig,
RESTMapper: r.restMapper,
Namespace: ns,
ParentRef: parentRef,
Objects: objects.GetItems(),
Validate: r.options.validate,
ExtraArgs: extraArgs,
Force: true,
CascadingStrategy: r.options.cascadingStrategy,
Client: r.client,
DynamicClient: r.dynamicClient,
}
applyOperation := &ApplyOperation{
Subject: instance,
Objects: objects,
ApplierOptions: &applierOpt,
}
applier := r.options.applier
for _, hook := range r.options.hooks {
if beforeApply, ok := hook.(BeforeApply); ok {
if err := beforeApply.BeforeApply(ctx, applyOperation); err != nil {
log.Error(err, "calling BeforeApply hook")
return statusInfo, fmt.Errorf("error calling BeforeApply hook: %v", err)
}
}
}
if err := applier.Apply(ctx, applierOpt); err != nil {
log.Error(err, "applying manifest")
statusInfo.KnownError = KnownErrorApplyFailed
return statusInfo, fmt.Errorf("error applying manifest: %v", err)
}
statusInfo.LiveObjects = func(ctx context.Context, gvk schema.GroupVersionKind, nn types.NamespacedName) (*unstructured.Unstructured, error) {
// TODO: Applier should return the objects in their post-apply state, so we don't have to requery
mapping, err := r.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return nil, fmt.Errorf("unable to get mapping for resource %v: %w", gvk, err)
}
var resource dynamic.ResourceInterface
switch mapping.Scope {
case meta.RESTScopeNamespace:
resource = r.dynamicClient.Resource(mapping.Resource).Namespace(nn.Namespace)
case meta.RESTScopeRoot:
resource = r.dynamicClient.Resource(mapping.Resource)
default:
return nil, fmt.Errorf("unknown scope %v", mapping.Scope)
}
u, err := resource.Get(ctx, nn.Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("error getting object: %w", err)
}
return u, nil
}
if r.options.sink != nil {
if err := r.options.sink.Notify(ctx, instance, objects); err != nil {
log.Error(err, "notifying sink")
return statusInfo, err
}
}
for _, hook := range r.options.hooks {
if afterApply, ok := hook.(AfterApply); ok {
if err := afterApply.AfterApply(ctx, applyOperation); err != nil {
log.Error(err, "calling AfterApply hook")
return statusInfo, fmt.Errorf("error calling AfterApply hook: %w", err)
}
}
}
return statusInfo, nil
}
// BuildDeploymentObjects performs all manifest operations to build a final set of objects for deployment
func (r *Reconciler) BuildDeploymentObjects(ctx context.Context, name types.NamespacedName, instance DeclarativeObject) (*manifest.Objects, error) {
return r.BuildDeploymentObjectsWithFs(ctx, name, instance, nil)
}
// BuildDeploymentObjectsWithFs is the implementation of BuildDeploymentObjects, supporting saving to a filesystem for kustomize
// If fs is provided, the transformed manifests will be saved to that filesystem
func (r *Reconciler) BuildDeploymentObjectsWithFs(ctx context.Context, name types.NamespacedName, instance DeclarativeObject, fs filesys.FileSystem) (*manifest.Objects, error) {
log := log.FromContext(ctx)
// 1. Load the manifest
manifestFiles, err := r.loadRawManifest(ctx, instance)
if err != nil {
log.Error(err, "error loading raw manifest")
return nil, err
}
manifestObjects := &manifest.Objects{}
// 2. Perform raw string operations
for manifestPath, manifestStr := range manifestFiles {
for _, t := range r.options.rawManifestOperations {
transformed, err := t(ctx, instance, manifestStr)
if err != nil {
log.Error(err, "error performing raw manifest operations")
return nil, err
}
manifestStr = transformed
}
// 3. Parse manifest into objects
objects, err := r.parseManifest(ctx, instance, manifestStr)
if err != nil {
log.Error(err, "error parsing manifest")
return nil, err
}
// 4. Perform object transformations
// (unless kustomize is in use, in which case we transform after running kustomize)
if !r.IsKustomizeOptionUsed() {
if err := r.transformManifest(ctx, instance, objects); err != nil {
log.Error(err, "error transforming manifest")
return nil, err
}
}
if fs != nil {
// 5. Write objects to filesystem for kustomizing, allow multiple objects in a file
finalJson := []byte("")
separator := []byte("---\n")
for _, item := range objects.Items {
json, err := item.JSON()
if err != nil {
log.Error(err, "error converting object to json")
return nil, err
}
finalJson = append(finalJson, separator...)
finalJson = append(finalJson, json...)
}
fs.WriteFile(string(manifestPath), finalJson)
for _, blob := range objects.Blobs {
fs.WriteFile(string(manifestPath), blob)
}
}
manifestObjects.Path = filepath.Dir(manifestPath)
manifestObjects.Items = append(manifestObjects.Items, objects.Items...)
manifestObjects.Blobs = append(manifestObjects.Blobs, objects.Blobs...)
}
// If Kustomize option is on, it's assumed that the entire addon manifest is created using Kustomize
// Here, the manifest is built using Kustomize and then replaces the Object items with the created manifest
if r.IsKustomizeOptionUsed() {
// run kustomize to create final manifest
manifestYaml, err := kustomize.Run(ctx, fs, manifestObjects.Path)
if err != nil {
log.Error(err, "run kustomize build")
return nil, fmt.Errorf("error running kustomize: %v", err)
}
objects, err := r.parseManifest(ctx, instance, string(manifestYaml))
if err != nil {
log.Error(err, "creating final manifest yaml")
return nil, err
}
if err := r.transformManifest(ctx, instance, objects); err != nil {
log.Error(err, "error transforming manifest")
return nil, err
}
manifestObjects.Items = objects.Items
}
// 6. Sort objects to work around dependent objects in the same manifest (eg: service-account, deployment)
manifestObjects.Sort(DefaultObjectOrder(ctx))
return manifestObjects, nil
}
// parseManifest parses the manifest into objects
func (r *Reconciler) parseManifest(ctx context.Context, instance DeclarativeObject, manifestStr string) (*manifest.Objects, error) {
log := log.FromContext(ctx)
objects, err := manifest.ParseObjects(ctx, manifestStr)
if err != nil {
log.Error(err, "error parsing manifest")
return nil, err
}
return objects, nil
}
// transformManifest runs any transformations as required
func (r *Reconciler) transformManifest(ctx context.Context, instance DeclarativeObject, objects *manifest.Objects) error {
transforms := r.options.objectTransformations
if r.options.labelMaker != nil {
transforms = append(transforms, AddLabels(r.options.labelMaker(ctx, instance)))
}
// TODO(jrjohnson): apply namespace here
for _, t := range transforms {
err := t(ctx, instance, objects)
if err != nil {
return err
}
}
return nil
}
// loadRawManifest loads the raw manifest YAML from the repository
func (r *Reconciler) loadRawManifest(ctx context.Context, o DeclarativeObject) (map[string]string, error) {
s, err := r.options.manifestController.ResolveManifest(ctx, o)
if err != nil {
return nil, err
}
return s, nil
}
func (r *Reconciler) applyOptions(opts ...ReconcilerOption) error {
params := reconcilerParams{}
params.applier = defaultApplier
opts = append(Options.Begin, opts...)
opts = append(opts, Options.End...)
for _, opt := range opts {
params = opt(params)
}
// Default the manifest controller if not set
if params.manifestController == nil && DefaultManifestLoader != nil {
loader, err := DefaultManifestLoader()
if err != nil {
return err
}
params.manifestController = loader
}
if params.cascadingStrategy == "" {
params.cascadingStrategy = "Foreground"
}
r.options = params
return nil
}
// Validate compatibility of selected options
func (r *Reconciler) validateOptions() error {
var errs []string
if r.options.prune && r.options.labelMaker == nil {
errs = append(errs, "WithApplyPrune must be used with the WithLabels option")
}
if r.options.manifestController == nil {
errs = append(errs, "ManifestController must be set either by configuring DefaultManifestLoader or specifying the WithManifestController option")
}
if len(errs) != 0 {
return fmt.Errorf(strings.Join(errs, ","))
}
return nil
}
// setNamespaces will set the object on all namespace-scoped objects, unless the preserveNamespace option is set
func (r *Reconciler) setNamespaces(ctx context.Context, instance DeclarativeObject, objects *manifest.Objects) error {
if r.options.preserveNamespace {
return nil
}
ns := instance.GetNamespace()
if ns == "" {
// No namespace to set
return nil
}
log := log.FromContext(ctx)
log.WithValues("namespace", ns).Info("setting namespace")
for _, o := range objects.Items {
if o.GetNamespace() != "" {
continue
}
gvk := o.GroupVersionKind()
mapping, err := r.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
log.Error(err, "error getting scope for gvk", "gvk", gvk)
continue
}
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
o.SetNamespace(ns)
}
}
return nil
}
func (r *Reconciler) injectOwnerRef(ctx context.Context, instance DeclarativeObject, objects *manifest.Objects) error {
if r.options.ownerFn == nil {
return nil
}
log := log.FromContext(ctx)
log.WithValues("object", fmt.Sprintf("%s/%s", instance.GetName(), instance.GetNamespace())).Info("injecting owner references")
for _, o := range objects.Items {
owner, err := r.options.ownerFn(ctx, instance, *o, *objects)
if err != nil {
log.WithValues("object", o).Error(err, "resolving owner ref", o)
return err
}
if owner == nil {
log.WithValues("object", o).Info("no owner resolved")
continue
}
if owner.GetName() == "" {
log.WithValues("object", o).Info("has no name")
continue
}
if string(owner.GetUID()) == "" {
log.WithValues("object", o).Info("has no UID")
continue
}
gvk, err := apiutil.GVKForObject(owner, r.mgr.GetScheme())
if err != nil {
log.WithValues("object", o).Error(err, "unable to get GVK for object")
continue
}
if gvk.Group == "" || gvk.Version == "" {
log.WithValues("object", o).WithValues("GroupVersionKind", gvk).Info("is not valid")
continue
}
if owner.GetNamespace() != "" && owner.GetNamespace() != o.GetNamespace() {
// a namespaced object can only own objects within the same namespace, not objects in other namespaces or cluster-scoped objects
// for any other combination, skip setting owner reference here, to allow declarative.SourceAsOwner to be used for the
// subset of objects that make up a supported combination
log.WithValues("object", o).Info("not setting ownerRef across namespaces")
continue
}
ownerRefs := []interface{}{
map[string]interface{}{
"apiVersion": gvk.Group + "/" + gvk.Version,
"blockOwnerDeletion": true,
"controller": true,
"kind": gvk.Kind,
"name": owner.GetName(),
"uid": string(owner.GetUID()),
},
}
if err := o.SetNestedField(ownerRefs, "metadata", "ownerReferences"); err != nil {
return err
}
}
return nil
}
func (r *Reconciler) collectMetrics(request reconcile.Request, result reconcile.Result, err error) {
if r.options.metrics {
r.metrics.reconcileWith(request)
r.metrics.reconcileFailedWith(request, result, err)
}
}
// IsKustomizeOptionUsed checks if the option for Kustomize build is used for creating manifests
func (r *Reconciler) IsKustomizeOptionUsed() bool {
if r.options.kustomize {
return true
}
return false
}
// SetSink provides a Sink that will be notified for all deployments
//
// Deprecated: prefer WithHook
func (r *Reconciler) SetSink(sink Sink) {
r.options.sink = sink
}
// AddHook provides a Hook that will be notified of significant events
func (r *Reconciler) AddHook(hook Hook) {
r.options.hooks = append(r.options.hooks, hook)
}
// flattenListObjects will replace any List objects in the manifest with the items,
// "flattening" the objects.
func flattenListObjects(infos *manifest.Objects) (*manifest.Objects, error) {
var out []*manifest.Object
for _, item := range infos.Items {
if item.Group == "v1" && item.Kind == "List" {
itemObj := item.UnstructuredObject()
err := itemObj.EachListItem(func(obj runtime.Object) error {
itemUnstructured := obj.(*unstructured.Unstructured)
newObj, err := manifest.NewObject(itemUnstructured)
if err != nil {
return err
}
out = append(out, newObj)
return nil
})
if err != nil {
return nil, err
}
} else {
out = append(out, item)
}
}
ret := manifest.Objects{
Items: out,
Blobs: infos.Blobs,
Path: infos.Path,
}
return &ret, nil
}
// CollectMetrics determines whether metrics of declarative reconciler is enabled
func (r *Reconciler) CollectMetrics() bool {
return r.options.metrics
}
// GetObjectFromCluster gets the current state of the object from the cluster.
//
// deprecated: use LiveObjectReader instead when computing status
func GetObjectFromCluster(obj *manifest.Object, r *Reconciler) (*unstructured.Unstructured, error) {
getOptions := metav1.GetOptions{}
gvk := obj.GroupVersionKind()
mapping, err := r.restMapper.RESTMapping(obj.GroupKind(), gvk.Version)
if err != nil {
return nil, fmt.Errorf("unable to get mapping for resource %v: %w", gvk, err)
}
ns, name := "", obj.GetName()
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
ns = obj.GetNamespace()
}
unstruct, err := r.dynamicClient.Resource(mapping.Resource).Namespace(ns).Get(context.TODO(), name, getOptions)
if err != nil {
return nil, fmt.Errorf("unable to get object: %w", err)
}
return unstruct, nil
}