/
clustersummary_controller.go
1090 lines (908 loc) · 41.9 KB
/
clustersummary_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
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 2022-23. projectsveltos.io. All rights reserved.
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 controllers
import (
"context"
"fmt"
"sync"
"syscall"
"time"
sourcev1 "github.com/fluxcd/source-controller/api/v1"
sourcev1b2 "github.com/fluxcd/source-controller/api/v1beta2"
"github.com/go-logr/logr"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util/annotations"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
configv1alpha1 "github.com/projectsveltos/addon-controller/api/v1alpha1"
"github.com/projectsveltos/addon-controller/controllers/chartmanager"
"github.com/projectsveltos/addon-controller/pkg/scope"
libsveltosv1alpha1 "github.com/projectsveltos/libsveltos/api/v1alpha1"
"github.com/projectsveltos/libsveltos/lib/clusterproxy"
"github.com/projectsveltos/libsveltos/lib/deployer"
logs "github.com/projectsveltos/libsveltos/lib/logsettings"
libsveltosset "github.com/projectsveltos/libsveltos/lib/set"
"github.com/projectsveltos/libsveltos/lib/sharding"
)
const (
// deleteRequeueAfter is how long to wait before checking again to see if the cluster still has
// children during deletion.
deleteRequeueAfter = 10 * time.Second
// normalRequeueAfter is how long to wait before checking again to see if the cluster can be moved
// to ready after or workload features (for instance ingress or reporter) have failed
normalRequeueAfter = 10 * time.Second
)
type ReportMode int
const (
// Default mode. In this mode, addon-controller running
// in the management cluster periodically collects/processes
// ResourceSummaries from Sveltos/CAPI Clusters
CollectFromManagementCluster ReportMode = iota
// In this mode, drift detection manager sends ResourceSummaries
// updates to management cluster.
AgentSendUpdatesNoGateway
)
// ClusterSummaryReconciler reconciles a ClusterSummary object
type ClusterSummaryReconciler struct {
*rest.Config
client.Client
Scheme *runtime.Scheme
Logger logr.Logger
ReportMode ReportMode
AgentInMgmtCluster bool // if true, indicates drift-detection-manager needs to be started in the management cluster
ShardKey string // when set, only clusters matching the ShardKey will be reconciled
Deployer deployer.DeployerInterface
ConcurrentReconciles int
PolicyMux sync.Mutex // use a Mutex to update Map as MaxConcurrentReconciles is higher than one
ReferenceMap map[corev1.ObjectReference]*libsveltosset.Set // key: Referenced object; value: set of all ClusterSummaries referencing the resource
ClusterMap map[corev1.ObjectReference]*libsveltosset.Set // key: Sveltos/Cluster; value: set of all ClusterSummaries for that Cluster
ctrl controller.Controller
}
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clustersummaries,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clustersummaries/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clustersummaries/finalizers,verbs=update;patch
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clusterconfigurations,verbs=get;list;watch
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clusterconfigurations/status,verbs=get;list;update
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clusterreports,verbs=get;list;watch
//+kubebuilder:rbac:groups=config.projectsveltos.io,resources=clusterreports/status,verbs=get;list;update
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
//+kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch
//+kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=kubeadmcontrolplanes,verbs=get;watch;list
//+kubebuilder:rbac:groups="infrastructure.cluster.x-k8s.io",resources="*",verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=gitrepositories,verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=gitrepositories/status,verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=ocirepositories,verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=ocirepositories/status,verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=buckets,verbs=get;watch;list
//+kubebuilder:rbac:groups="source.toolkit.fluxcd.io",resources=buckets/status,verbs=get;watch;list
func (r *ClusterSummaryReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
logger := ctrl.LoggerFrom(ctx)
logger.V(logs.LogInfo).Info("Reconciling")
// Fecth the clusterSummary instance
clusterSummary := &configv1alpha1.ClusterSummary{}
if err := r.Get(ctx, req.NamespacedName, clusterSummary); err != nil {
if apierrors.IsNotFound(err) {
return reconcile.Result{}, nil
}
logger.Error(err, "Failed to fetch clusterSummary")
return reconcile.Result{}, errors.Wrapf(
err,
"Failed to fetch clusterSummary %s",
req.NamespacedName,
)
}
// Fetch the (Cluster)Profile.
profile, err := configv1alpha1.GetProfileOwner(ctx, r.Client, clusterSummary)
if err != nil {
logger.Error(err, "Failed to get owner clusterProfile")
return reconcile.Result{}, errors.Wrapf(
err,
"Failed to get owner clusterProfile for %s",
req.NamespacedName,
)
}
if profile == nil {
logger.Error(err, "Failed to get owner (Cluster)Profile")
return reconcile.Result{}, fmt.Errorf("failed to get owner (Cluster)Profile for %s",
req.NamespacedName)
}
clusterSummaryScope, err := scope.NewClusterSummaryScope(&scope.ClusterSummaryScopeParams{
Client: r.Client,
Logger: logger,
ClusterSummary: clusterSummary,
Profile: profile,
ControllerName: "clustersummary",
})
if err != nil {
logger.Error(err, "Failed to create clusterProfileScope")
return reconcile.Result{}, errors.Wrapf(
err,
"unable to create clusterprofile scope for %s",
req.NamespacedName,
)
}
var isMatch bool
isMatch, err = r.isClusterAShardMatch(ctx, clusterSummary, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
} else if !isMatch {
// This addon-controller pod is not a shard match, yet we need to refresh internal state by:
// - removing any helm chart registration made by this ClusterSummary
// - update internal maps. This is needed cause when cluster changes, shard annotation changes,
// this addon-controller might become the new shard match and so it must reconcile this ClusterSummary instance
return reconcile.Result{}, r.refreshInternalState(ctx, clusterSummaryScope, logger)
}
err = r.updateClusterShardPair(ctx, clusterSummary, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
// Always close the scope when exiting this function so we can persist any ClusterSummary
// changes.
defer func() {
if err = clusterSummaryScope.Close(ctx); err != nil {
reterr = err
}
}()
// Handle deleted clusterSummary
if !clusterSummary.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, clusterSummaryScope, logger)
}
isReady, err := r.isReady(ctx, clusterSummary, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
if !isReady {
logger.V(logs.LogInfo).Info("cluster is not ready.")
r.setFailureMessage(clusterSummaryScope, "cluster is not ready")
r.resetFeatureStatus(clusterSummaryScope, configv1alpha1.FeatureStatusFailed)
// if cluster is not ready, do nothing and don't queue for reconciliation.
// When cluster becomes ready, all matching clusterSummaries will be requeued for reconciliation
return reconcile.Result{}, r.updateMaps(ctx, clusterSummaryScope, logger)
}
// Handle non-deleted clusterSummary
return r.reconcileNormal(ctx, clusterSummaryScope, logger)
}
func (r *ClusterSummaryReconciler) reconcileDelete(
ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger,
) (reconcile.Result, error) {
logger.V(logs.LogInfo).Info("Reconciling ClusterSummary delete")
isReady, err := r.isReady(ctx, clusterSummaryScope.ClusterSummary, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
// If Sveltos/Cluster is not found, there is nothing to clean up.
isPresent, isDeleted, err := r.isClusterPresent(ctx, clusterSummaryScope)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
if isPresent && isReady { // if cluster is not ready, do not try to clean up. It would fail.
// Cleanup
paused, err := r.isPaused(ctx, clusterSummaryScope.ClusterSummary)
if err != nil {
return reconcile.Result{}, err
}
if paused {
logger.V(logs.LogInfo).Info("cluster is paused. Do nothing.")
return reconcile.Result{}, nil
}
err = r.removeResourceSummary(ctx, clusterSummaryScope, logger)
if err != nil {
logger.V(logs.LogInfo).Error(err, "failed to remove ResourceSummary.")
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
err = r.undeploy(ctx, clusterSummaryScope, logger)
if err != nil {
// In DryRun mode it is expected to always get an error back
if !clusterSummaryScope.IsDryRunSync() {
logger.V(logs.LogInfo).Error(err, "failed to undeploy")
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
}
if !r.canRemoveFinalizer(ctx, clusterSummaryScope, logger) {
logger.V(logs.LogInfo).Error(err, "cannot remove finalizer yet")
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
}
// If cluster is not present anymore or is it marked for deletion
if !isPresent || isDeleted {
logger.V(logs.LogDebug).Info("remove drift-detection-manager resources from management cluster")
cs := clusterSummaryScope.ClusterSummary
if err := removeDriftDetectionManagerFromManagementCluster(ctx,
cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cs.Spec.ClusterType, logger); err != nil {
logger.V(logs.LogInfo).Info(
fmt.Sprintf("failed to remove drift-detection-manager resources from management cluster: %v", err))
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
}
// Cluster is not present anymore or cleanup succeeded
logger.V(logs.LogInfo).Info("Removing finalizer")
if controllerutil.ContainsFinalizer(clusterSummaryScope.ClusterSummary, configv1alpha1.ClusterSummaryFinalizer) {
if finalizersUpdated := controllerutil.RemoveFinalizer(clusterSummaryScope.ClusterSummary,
configv1alpha1.ClusterSummaryFinalizer); !finalizersUpdated {
return reconcile.Result{}, fmt.Errorf("failed to remove finalizer")
}
}
if err := r.deleteChartMap(ctx, clusterSummaryScope, logger); err != nil {
return reconcile.Result{}, err
}
r.cleanMaps(clusterSummaryScope)
logger.V(logs.LogInfo).Info("Reconcile delete success")
return reconcile.Result{}, nil
}
func (r *ClusterSummaryReconciler) reconcileNormal(
ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger,
) (reconcile.Result, error) {
logger.V(logs.LogInfo).Info("Reconciling ClusterSummary")
if !controllerutil.ContainsFinalizer(clusterSummaryScope.ClusterSummary, configv1alpha1.ClusterSummaryFinalizer) {
if err := r.addFinalizer(ctx, clusterSummaryScope); err != nil {
logger.V(logs.LogInfo).Error(err, "failed to add finalizer")
return reconcile.Result{}, err
}
}
if !r.shouldReconcile(clusterSummaryScope, logger) {
logger.V(logs.LogInfo).Info("ClusterSummary does not need a reconciliation")
return reconcile.Result{}, nil
}
if err := r.updateMaps(ctx, clusterSummaryScope, logger); err != nil {
logger.V(logs.LogInfo).Info("Failed to update maps")
return reconcile.Result{}, nil
}
paused, err := r.isPaused(ctx, clusterSummaryScope.ClusterSummary)
if err != nil {
return reconcile.Result{}, err
}
if paused {
logger.V(logs.LogInfo).Info("cluster is paused. Do nothing.")
return reconcile.Result{}, nil
}
allDeployed, msg, err := r.areDependenciesDeployed(ctx, clusterSummaryScope, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
clusterSummaryScope.SetDependenciesMessage(&msg)
if !allDeployed {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
err = r.updateChartMap(ctx, clusterSummaryScope, logger)
if err != nil {
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
if !clusterSummaryScope.IsContinuousWithDriftDetection() {
err = r.removeResourceSummary(ctx, clusterSummaryScope, logger)
if err != nil {
logger.V(logs.LogInfo).Error(err, "failed to remove ResourceSummary.")
return reconcile.Result{Requeue: true, RequeueAfter: deleteRequeueAfter}, nil
}
}
if err := r.deploy(ctx, clusterSummaryScope, logger); err != nil {
logger.V(logs.LogInfo).Error(err, "failed to deploy")
return reconcile.Result{Requeue: true, RequeueAfter: normalRequeueAfter}, nil
}
logger.V(logs.LogInfo).Info("Reconciling ClusterSummary success")
return reconcile.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *ClusterSummaryReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
c, err := ctrl.NewControllerManagedBy(mgr).
For(&configv1alpha1.ClusterSummary{}).
WithOptions(controller.Options{
MaxConcurrentReconciles: r.ConcurrentReconciles,
}).
Build(r)
if err != nil {
return errors.Wrap(err, "error creating controller")
}
// At this point we don't know yet whether CAPI is present in the cluster.
// Later on, in main, we detect that and if CAPI is present WatchForCAPI will be invoked.
// When Sveltos Cluster changes (from paused to unpaused), one or more ClusterSummaries
// need to be reconciled.
err = c.Watch(source.Kind(mgr.GetCache(), &libsveltosv1alpha1.SveltosCluster{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForCluster),
SveltosClusterPredicates(mgr.GetLogger().WithValues("predicate", "clusterpredicate")),
)
if err != nil {
return err
}
// When ConfigMap changes, according to ConfigMapPredicates,
// one or more ClusterSummaries need to be reconciled.
err = c.Watch(source.Kind(mgr.GetCache(), &corev1.ConfigMap{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForReference),
ConfigMapPredicates(mgr.GetLogger().WithValues("predicate", "configmappredicate")),
)
if err != nil {
return err
}
// When Secret changes, according to SecretPredicates,
// one or more ClusterSummaries need to be reconciled.
err = c.Watch(source.Kind(mgr.GetCache(), &corev1.Secret{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForReference),
SecretPredicates(mgr.GetLogger().WithValues("predicate", "secretpredicate")),
)
if r.ReportMode == CollectFromManagementCluster {
go collectAndProcessResourceSummaries(ctx, mgr.GetClient(), r.ShardKey, mgr.GetLogger())
}
initializeManager(ctrl.Log.WithName("watchers"), mgr.GetConfig(), mgr.GetClient())
r.ctrl = c
return err
}
func (r *ClusterSummaryReconciler) WatchForCAPI(mgr ctrl.Manager, c controller.Controller) error {
// When CAPI Cluster changes (from paused to unpaused), one or more ClusterSummaries
// need to be reconciled.
return c.Watch(source.Kind(mgr.GetCache(), &clusterv1.Cluster{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForCluster),
ClusterPredicates(mgr.GetLogger().WithValues("predicate", "clusterpredicate")),
)
}
func (r *ClusterSummaryReconciler) WatchForFlux(mgr ctrl.Manager, c controller.Controller) error {
// When a Flux source (GitRepository/OCIRepository/Bucket) changes, one or more ClusterSummaries
// need to be reconciled.
err := c.Watch(source.Kind(mgr.GetCache(), &sourcev1.GitRepository{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForFluxSource),
FluxSourcePredicates(mgr.GetLogger().WithValues("predicate", "fluxsourcepredicate")),
)
if err != nil {
return err
}
err = c.Watch(source.Kind(mgr.GetCache(), &sourcev1b2.OCIRepository{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForFluxSource),
FluxSourcePredicates(mgr.GetLogger().WithValues("predicate", "fluxsourcepredicate")),
)
if err != nil {
return err
}
return c.Watch(source.Kind(mgr.GetCache(), &sourcev1b2.Bucket{}),
handler.EnqueueRequestsFromMapFunc(r.requeueClusterSummaryForFluxSource),
FluxSourcePredicates(mgr.GetLogger().WithValues("predicate", "fluxsourcepredicate")),
)
}
func (r *ClusterSummaryReconciler) addFinalizer(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope) error {
// If the SveltosCluster doesn't have our finalizer, add it.
controllerutil.AddFinalizer(clusterSummaryScope.ClusterSummary, configv1alpha1.ClusterSummaryFinalizer)
// Register the finalizer immediately to avoid orphaning clusterprofile resources on delete
if err := clusterSummaryScope.PatchObject(ctx); err != nil {
clusterSummaryScope.Error(err, "Failed to add finalizer")
return errors.Wrapf(
err,
"Failed to add finalizer for %s",
clusterSummaryScope.Name(),
)
}
return nil
}
func (r *ClusterSummaryReconciler) deploy(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
clusterSummary := clusterSummaryScope.ClusterSummary
logger = logger.WithValues("clusternamespace", clusterSummary.Spec.ClusterNamespace, "clustername", clusterSummary.Spec.ClusterName)
coreResourceErr := r.deployResources(ctx, clusterSummaryScope, logger)
helmErr := r.deployHelm(ctx, clusterSummaryScope, logger)
kustomizeError := r.deployKustomizeRefs(ctx, clusterSummaryScope, logger)
if coreResourceErr != nil {
return coreResourceErr
}
if helmErr != nil {
return helmErr
}
if kustomizeError != nil {
return kustomizeError
}
return nil
}
func (r *ClusterSummaryReconciler) deployKustomizeRefs(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
if clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs == nil {
logger.V(logs.LogDebug).Info("no policy configuration")
if !r.isFeatureStatusPresent(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureKustomize) {
logger.V(logs.LogDebug).Info("no policy status. Do not reconcile this")
return nil
}
}
f := getHandlersForFeature(configv1alpha1.FeatureKustomize)
return r.deployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) deployResources(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
if clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.PolicyRefs == nil {
logger.V(logs.LogDebug).Info("no policy configuration")
if !r.isFeatureStatusPresent(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureResources) {
logger.V(logs.LogDebug).Info("no policy status. Do not reconcile this")
return nil
}
}
f := getHandlersForFeature(configv1alpha1.FeatureResources)
return r.deployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) deployHelm(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
if clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.HelmCharts == nil {
logger.V(logs.LogDebug).Info("no helm configuration")
if !r.isFeatureStatusPresent(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureHelm) {
logger.V(logs.LogDebug).Info("no helm status. Do not reconcile this")
return nil
}
}
f := getHandlersForFeature(configv1alpha1.FeatureHelm)
return r.deployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) isClusterPresent(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope) (present, deleted bool, err error) {
cs := clusterSummaryScope.ClusterSummary
var cluster client.Object
cluster, err = clusterproxy.GetCluster(ctx, r.Client, cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cs.Spec.ClusterType)
if err != nil {
if apierrors.IsNotFound(err) {
return false, false, nil
}
}
return true, !cluster.GetDeletionTimestamp().IsZero(), err
}
func (r *ClusterSummaryReconciler) undeploy(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger) error {
resourceErr := r.undeployResources(ctx, clusterSummaryScope, logger)
kustomizeResourceErr := r.undeployKustomizeResources(ctx, clusterSummaryScope, logger)
helmErr := r.undeployHelm(ctx, clusterSummaryScope, logger)
if resourceErr != nil {
return resourceErr
}
if kustomizeResourceErr != nil {
return kustomizeResourceErr
}
if helmErr != nil {
return helmErr
}
return nil
}
func (r *ClusterSummaryReconciler) undeployResources(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
f := getHandlersForFeature(configv1alpha1.FeatureResources)
return r.undeployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) undeployKustomizeResources(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
f := getHandlersForFeature(configv1alpha1.FeatureKustomize)
return r.undeployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) undeployHelm(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
f := getHandlersForFeature(configv1alpha1.FeatureHelm)
return r.undeployFeature(ctx, clusterSummaryScope, f, logger)
}
func (r *ClusterSummaryReconciler) updateChartMap(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger) error {
// When in DryRun mode, ClusterSummary won't update (install/upgrade/uninstall) any helm chart.
// So it does not update helm chart registration. Whatever registrations it had, are still there (if it was
// managing an helm chart, that information still holds as dryrun means change nothing).
// Let's say currently no ClusterProfile is managing an helm chart, if we allowed a ClusterSummary in DryRun to
// register then:
// 1) this ClusterSummary would be elected as manager
// 2) ClusterSummary is in DryRun mode so it actually won't deploy anything
// 3) If another ClusterProfile in not DryRun mode tried to manage same helm chart, it would not be allowed.
if clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1alpha1.SyncModeDryRun {
return nil
}
chartManager, err := chartmanager.GetChartManagerInstance(ctx, r.Client)
if err != nil {
return err
}
// First try to be elected manager. Only if that succeeds, manage an helm chart.
logger.V(logs.LogDebug).Info("register clustersummary with helm chart manager")
chartManager.RegisterClusterSummaryForCharts(clusterSummaryScope.ClusterSummary)
// Registration for helm chart not referenced anymore, are cleaned only after such helm
// chart are removed from Sveltos/Cluster. That is done as part of deployHelmCharts and
// undeployHelmCharts (RemoveStaleRegistrations).
// That is because we need to make sure managed helm charts are successfully uninstalled
// before any registration with chartManager is cleared.
return nil
}
// deleteChartMap removes any registration with chartManager.
// Call it only when ClusterSummary is ready to be deleted (finalizer is removed)
func (r *ClusterSummaryReconciler) deleteChartMap(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger) error {
chartManager, err := chartmanager.GetChartManagerInstance(ctx, r.Client)
if err != nil {
return err
}
logger.V(logs.LogDebug).Info("remove clustersummary with helm chart manager")
chartManager.RemoveAllRegistrations(clusterSummaryScope.ClusterSummary)
return nil
}
func (r *ClusterSummaryReconciler) cleanMaps(clusterSummaryScope *scope.ClusterSummaryScope) {
r.PolicyMux.Lock()
defer r.PolicyMux.Unlock()
clusterSummaryInfo := getKeyFromObject(r.Scheme, clusterSummaryScope.ClusterSummary)
for i := range r.ClusterMap {
clusterSummarySet := r.ClusterMap[i]
clusterSummarySet.Erase(clusterSummaryInfo)
}
for i := range r.ReferenceMap {
clusterSummarySet := r.ReferenceMap[i]
clusterSummarySet.Erase(clusterSummaryInfo)
}
}
func (r *ClusterSummaryReconciler) updateMaps(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope,
logger logr.Logger) error {
if clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1alpha1.SyncModeOneTime {
logger.V(logs.LogDebug).Info("sync mode is one time. No need to reconcile on policies change.")
return nil
}
logger.V(logs.LogDebug).Info("update policy map")
currentReferences := r.getCurrentReferences(clusterSummaryScope)
r.PolicyMux.Lock()
defer r.PolicyMux.Unlock()
cs := clusterSummaryScope.ClusterSummary
clusterObject, err := clusterproxy.GetCluster(ctx, r.Client, cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cs.Spec.ClusterType)
if err != nil {
return err
}
clusterInfo := getKeyFromObject(r.Scheme, clusterObject)
clusterSummaryInfo := corev1.ObjectReference{APIVersion: configv1alpha1.GroupVersion.String(),
Kind: configv1alpha1.ClusterSummaryKind, Namespace: clusterSummaryScope.Namespace(),
Name: clusterSummaryScope.Name()}
r.getClusterMapForEntry(clusterInfo).Insert(&clusterSummaryInfo)
for k, l := range r.ReferenceMap {
l.Erase(&clusterSummaryInfo)
if l.Len() == 0 {
delete(r.ReferenceMap, k)
}
}
// For each currently referenced instance, add ClusterSummary as consumer
for _, referencedResource := range currentReferences.Items() {
tmpResource := referencedResource
r.getReferenceMapForEntry(&tmpResource).Insert(
&corev1.ObjectReference{
APIVersion: configv1alpha1.GroupVersion.String(),
Kind: configv1alpha1.ClusterSummaryKind,
Namespace: clusterSummaryScope.Namespace(),
Name: clusterSummaryScope.Name(),
},
)
}
return nil
}
func (r *ClusterSummaryReconciler) getClusterMapForEntry(entry *corev1.ObjectReference) *libsveltosset.Set {
s := r.ClusterMap[*entry]
if s == nil {
s = &libsveltosset.Set{}
r.ClusterMap[*entry] = s
}
return s
}
// shouldReconcile returns true if a reconciliation is needed.
// When syncMode is set to one time, if features are marked as provisioned, no reconciliation is needed.
func (r *ClusterSummaryReconciler) shouldReconcile(clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) bool {
clusterSummary := clusterSummaryScope.ClusterSummary
if clusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1alpha1.SyncModeContinuous ||
clusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1alpha1.SyncModeContinuousWithDriftDetection {
logger.V(logs.LogDebug).Info(fmt.Sprintf("Mode set to %s. Reconciliation is needed.",
clusterSummary.Spec.ClusterProfileSpec.SyncMode))
return true
}
if clusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1alpha1.SyncModeDryRun {
logger.V(logs.LogDebug).Info("Mode set to dryRun. Reconciliation is needed.")
return true
}
if len(clusterSummary.Spec.ClusterProfileSpec.PolicyRefs) != 0 {
if !r.isFeatureDeployed(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureResources) {
logger.V(logs.LogDebug).Info("Mode set to one time. Resources not deployed yet. Reconciliation is needed.")
return true
}
}
if len(clusterSummary.Spec.ClusterProfileSpec.HelmCharts) != 0 {
if !r.isFeatureDeployed(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureHelm) {
logger.V(logs.LogDebug).Info("Mode set to one time. Helm Charts not deployed yet. Reconciliation is needed.")
return true
}
}
if len(clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs) != 0 {
if !r.isFeatureDeployed(clusterSummaryScope.ClusterSummary, configv1alpha1.FeatureKustomize) {
logger.V(logs.LogDebug).Info("Mode set to one time. Kustomization resources not deployed yet. Reconciliation is needed.")
return true
}
}
return false
}
func (r *ClusterSummaryReconciler) getCurrentReferences(clusterSummaryScope *scope.ClusterSummaryScope) *libsveltosset.Set {
currentReferences := &libsveltosset.Set{}
for i := range clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.PolicyRefs {
referencedNamespace := clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.PolicyRefs[i].Namespace
referencedName := clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.PolicyRefs[i].Name
namespace := getReferenceResourceNamespace(clusterSummaryScope.Namespace(), referencedNamespace)
currentReferences.Insert(&corev1.ObjectReference{
APIVersion: corev1.SchemeGroupVersion.String(), // the only resources that can be referenced are Secret and ConfigMap
Kind: clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.PolicyRefs[i].Kind,
Namespace: namespace,
Name: referencedName,
})
}
for i := range clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs {
referencedNamespace := clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs[i].Namespace
referencedName := clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs[i].Name
namespace := getReferenceResourceNamespace(clusterSummaryScope.Namespace(), referencedNamespace)
var apiVersion string
switch clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs[i].Kind {
case sourcev1.GitRepositoryKind:
apiVersion = sourcev1.GroupVersion.String()
case sourcev1b2.OCIRepositoryKind:
apiVersion = sourcev1b2.GroupVersion.String()
case sourcev1b2.BucketKind:
apiVersion = sourcev1b2.GroupVersion.String()
}
currentReferences.Insert(&corev1.ObjectReference{
APIVersion: apiVersion,
Kind: clusterSummaryScope.ClusterSummary.Spec.ClusterProfileSpec.KustomizationRefs[i].Kind,
Namespace: namespace,
Name: referencedName,
})
}
return currentReferences
}
func (r *ClusterSummaryReconciler) getReferenceMapForEntry(entry *corev1.ObjectReference) *libsveltosset.Set {
s := r.ReferenceMap[*entry]
if s == nil {
s = &libsveltosset.Set{}
r.ReferenceMap[*entry] = s
}
return s
}
// isReady returns true if Sveltos/Cluster is ready
func (r *ClusterSummaryReconciler) isReady(ctx context.Context,
clusterSummary *configv1alpha1.ClusterSummary, logger logr.Logger) (bool, error) {
clusterRef := &corev1.ObjectReference{
Namespace: clusterSummary.Spec.ClusterNamespace,
Name: clusterSummary.Spec.ClusterName,
}
if clusterSummary.Spec.ClusterType == libsveltosv1alpha1.ClusterTypeSveltos {
clusterRef.Kind = libsveltosv1alpha1.SveltosClusterKind
clusterRef.APIVersion = libsveltosv1alpha1.GroupVersion.String()
} else {
clusterRef.Kind = clusterKind
clusterRef.APIVersion = clusterv1.GroupVersion.String()
}
isClusterReady, err := clusterproxy.IsClusterReadyToBeConfigured(ctx, r.Client, clusterRef, logger)
if err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return isClusterReady, nil
}
// isPaused returns true if Sveltos/Cluster is paused or ClusterSummary has paused annotation.
func (r *ClusterSummaryReconciler) isPaused(ctx context.Context,
clusterSummary *configv1alpha1.ClusterSummary) (bool, error) {
isClusterPaused, err := clusterproxy.IsClusterPaused(ctx, r.Client, clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType)
if err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
if isClusterPaused {
return true, nil
}
return annotations.HasPaused(clusterSummary), nil
}
// canRemoveFinalizer returns true if finalizer can be removed.
// A ClusterSummary in DryRun mode can be removed if deleted and ClusterProfile is also marked for deletion.
// A ClusterSummary in not DryRun mode can be removed if deleted and all features are undeployed.
func (r *ClusterSummaryReconciler) canRemoveFinalizer(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) bool {
clusterSummary := clusterSummaryScope.ClusterSummary
if clusterSummaryScope.ClusterSummary.DeletionTimestamp.IsZero() {
logger.V(logs.LogDebug).Info("ClusterSummary not marked for deletion")
return false
}
_, err := clusterproxy.GetCluster(ctx, r.Client, clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType)
if err != nil {
if apierrors.IsNotFound(err) {
logger.V(logs.LogInfo).Info(fmt.Sprintf("cluster %s/%s not found. Nothing to do.",
clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName))
return true
}
return false
}
if clusterSummaryScope.IsDryRunSync() {
logger.V(logs.LogInfo).Info("DryRun mode. Can only be deleted if ClusterProfile is marked for deletion.")
// A ClusterSummary in DryRun mode can only be removed if also ClusterProfile is marked
// for deletion. Otherwise ClusterSummary has to stay and list what would happen if owning
// ClusterProfile is moved away from DryRun mode.
profile, err := configv1alpha1.GetProfileOwner(ctx, r.Client, clusterSummaryScope.ClusterSummary)
if err != nil {
logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get ClusterProfile %v", err))
return false
}
if profile == nil {
logger.V(logs.LogInfo).Info("failed to get ClusterProfile")
return false
}
if !profile.GetDeletionTimestamp().IsZero() {
return true
}
logger.V(logs.LogInfo).Info("ClusterProfile not marked for deletion")
return false
}
for i := range clusterSummaryScope.ClusterSummary.Status.FeatureSummaries {
fs := &clusterSummaryScope.ClusterSummary.Status.FeatureSummaries[i]
if fs.Status != configv1alpha1.FeatureStatusRemoved {
logger.V(logs.LogInfo).Info("Not all features marked as removed")
return false
}
}
return true
}
// removeResourceSummary removes, if still present, ResourceSummary corresponding
// to this ClusterSummary instance
func (r *ClusterSummaryReconciler) removeResourceSummary(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
// ResourceSummary is a Sveltos resource deployed in managed clusters.
// Such resources are always created, removed using cluster-admin roles.
cs := clusterSummaryScope.ClusterSummary
remoteClient, err := clusterproxy.GetKubernetesClient(ctx, r.Client, cs.Spec.ClusterNamespace,
cs.Spec.ClusterName, "", "", cs.Spec.ClusterType, logger)
if err != nil {
return err
}
err = unDeployResourceSummaryInstance(ctx, remoteClient, cs.Spec.ClusterNamespace,
cs.Name, logger)
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
// ResourceSummaries are only installed when in ContinuousWithDriftDetection mode
if meta.IsNoMatchError(err) {
return nil
}
}
return err
}
func (r *ClusterSummaryReconciler) updateClusterShardPair(ctx context.Context,
clusterSummary *configv1alpha1.ClusterSummary, logger logr.Logger) error {
if hasShardChanged, err := sharding.RegisterClusterShard(ctx, r.Client, libsveltosv1alpha1.ComponentAddonManager,
string(configv1alpha1.FeatureHelm), r.ShardKey, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName,
clusterSummary.Spec.ClusterType); err != nil {
logger.V(logs.LogDebug).Info(fmt.Sprintf("failed to check/update cluster:shard pair %v", err))
return err
} else if hasShardChanged {
// internal in-memory state must be rebuilt. Restart pod
logger.V(logs.LogInfo).Info("restarting pod to rebuild internal state")
if killErr := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); killErr != nil {
panic("kill -TERM failed")
}
}
return nil
}
// isClusterAShardMatch checks if cluster is matching this addon-controller deployment shard.
func (r *ClusterSummaryReconciler) isClusterAShardMatch(ctx context.Context,
clusterSummary *configv1alpha1.ClusterSummary, logger logr.Logger) (bool, error) {
cluster, err := clusterproxy.GetCluster(ctx, r.Client, clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType)
if err != nil {
// If Cluster does not exist anymore, make it match any shard
if apierrors.IsNotFound(err) {
return true, nil
}
logger.V(logs.LogDebug).Info(fmt.Sprintf("failed to get cluster: %v", err))
return false, err
}
if !sharding.IsShardAMatch(r.ShardKey, cluster) {
logger.V(logs.LogDebug).Info("not a shard match")
return false, nil
}
return true, nil
}
// refreshInternalState updates internal maps in this addon-controller pod:
// - remove any chart subscription handled by the clusterSummary
// - update cluster to clusterSummary maps. This is needed cause if cluster shard changes,
// we want this clusterSummary to be reconciled)
func (r *ClusterSummaryReconciler) refreshInternalState(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) error {
if err := r.deleteChartMap(ctx, clusterSummaryScope, logger); err != nil {
return err
}
clusterInfo := &corev1.ObjectReference{
Namespace: clusterSummaryScope.ClusterSummary.Spec.ClusterNamespace,
Name: clusterSummaryScope.ClusterSummary.Spec.ClusterName,
}
switch clusterSummaryScope.ClusterSummary.Spec.ClusterType {
case libsveltosv1alpha1.ClusterTypeSveltos:
clusterInfo.Kind = string(libsveltosv1alpha1.ClusterTypeSveltos)
clusterInfo.APIVersion = libsveltosv1alpha1.GroupVersion.String()
case libsveltosv1alpha1.ClusterTypeCapi:
clusterInfo.Kind = clusterKind
clusterInfo.APIVersion = clusterv1.GroupVersion.String()
}