-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathprofile_utils.go
1122 lines (948 loc) · 40 KB
/
profile_utils.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 2023. 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"
"crypto/sha256"
"fmt"
"math"
"reflect"
"strings"
"github.com/dariubs/percent"
"github.com/gdexlab/go-render/render"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/util/retry"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1"
"github.com/projectsveltos/addon-controller/controllers/dependencymanager"
"github.com/projectsveltos/addon-controller/pkg/scope"
libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1"
"github.com/projectsveltos/libsveltos/lib/clusterproxy"
logs "github.com/projectsveltos/libsveltos/lib/logsettings"
libsveltosset "github.com/projectsveltos/libsveltos/lib/set"
)
func getMatchingClusters(ctx context.Context, c client.Client, namespace string, clusterSelector *metav1.LabelSelector,
clusterRefs []corev1.ObjectReference, logger logr.Logger) ([]corev1.ObjectReference, error) {
var matchingCluster []corev1.ObjectReference
if clusterSelector != nil {
var err error
matchingCluster, err = clusterproxy.GetMatchingClusters(ctx, c, clusterSelector, namespace,
getCAPIOnboardAnnotation(), logger)
if err != nil {
return nil, err
}
}
matchingCluster = append(matchingCluster, clusterRefs...)
return matchingCluster, nil
}
// allClusterSummariesGone returns true if all ClusterSummaries owned by a
// ClusterProfile/Profile instances are gone.
func allClusterSummariesGone(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) bool {
listOptions := []client.ListOption{}
// Originally only ClusterProfile was present and ClusterProfileLabelName was set.
// With the addition of Profiles, different label is set ProfileLabelName
if profileScope.Profile.GetObjectKind().GroupVersionKind().Kind == configv1beta1.ClusterProfileKind {
listOptions = append(listOptions, client.MatchingLabels{ClusterProfileLabelName: profileScope.Name()})
} else {
listOptions = append(listOptions,
client.MatchingLabels{ProfileLabelName: profileScope.Name()},
client.InNamespace(profileScope.Profile.GetNamespace()))
}
clusterSummaryList := &configv1beta1.ClusterSummaryList{}
if err := c.List(ctx, clusterSummaryList, listOptions...); err != nil {
profileScope.Logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to list clustersummaries. err %v", err))
return false
}
if len(clusterSummaryList.Items) > 0 {
profileScope.Logger.V(logs.LogInfo).Info("not all clusterSummaries are gone")
}
return len(clusterSummaryList.Items) == 0
}
// canRemoveFinalizer returns true if there is no ClusterSummary left created by this
// ClusterProfile/Profile instance
func canRemoveFinalizer(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) bool {
return allClusterSummariesGone(ctx, c, profileScope)
}
// ClusterConfigurations
// - Name depends just on Cluster name
// - Each ClusterProfile/Profile matching corresponding Cluster and deploying add-ons/applications
// is added as OwnerReference
// updateClusterConfigurationProfileResources adds a section for ClusterProfile/Profile
// in clusterConfiguration Status.(Cluster)ProfileResources
func updateClusterConfigurationProfileResources(ctx context.Context, c client.Client,
profile client.Object, clusterConfiguration *configv1beta1.ClusterConfiguration) error {
profileKind := profile.GetObjectKind().GroupVersionKind().Kind
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
currentClusterConfiguration, err := getClusterConfiguration(ctx, c,
clusterConfiguration.Namespace, clusterConfiguration.Name)
if err != nil {
return err
}
if profileKind == configv1beta1.ClusterProfileKind {
for i := range currentClusterConfiguration.Status.ClusterProfileResources {
cpr := ¤tClusterConfiguration.Status.ClusterProfileResources[i]
if cpr.ClusterProfileName == profile.GetName() {
return nil
}
}
currentClusterConfiguration.Status.ClusterProfileResources = append(
currentClusterConfiguration.Status.ClusterProfileResources,
configv1beta1.ClusterProfileResource{
ClusterProfileName: profile.GetName(),
})
} else {
for i := range currentClusterConfiguration.Status.ProfileResources {
cpr := ¤tClusterConfiguration.Status.ProfileResources[i]
if cpr.ProfileName == profile.GetName() {
return nil
}
}
currentClusterConfiguration.Status.ProfileResources = append(
currentClusterConfiguration.Status.ProfileResources,
configv1beta1.ProfileResource{
ProfileName: profile.GetName(),
})
}
return c.Status().Update(ctx, currentClusterConfiguration)
})
return err
}
// updateClusterConfigurationOwnerReferences adds profile as owner of ClusterConfiguration
func updateClusterConfigurationOwnerReferences(ctx context.Context, c client.Client,
profile client.Object, clusterConfiguration *configv1beta1.ClusterConfiguration) error {
if util.IsOwnedByObject(clusterConfiguration, profile) {
return nil
}
ownerRef := metav1.OwnerReference{
Kind: profile.GetObjectKind().GroupVersionKind().Kind,
UID: profile.GetUID(),
APIVersion: configv1beta1.GroupVersion.String(),
Name: profile.GetName(),
}
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
currentClusterConfiguration, err := getClusterConfiguration(ctx, c,
clusterConfiguration.Namespace, clusterConfiguration.Name)
if err != nil {
return err
}
currentClusterConfiguration.OwnerReferences = util.EnsureOwnerRef(clusterConfiguration.OwnerReferences, ownerRef)
return c.Update(ctx, currentClusterConfiguration)
})
return err
}
// updateClusterConfiguration updates if necessary ClusterConfiguration given a
// ClusterProfile/Profile and a matching Sveltos/Cluster.
// Update consists in:
// - adding ClusterProfile/Profile as one of OwnerReferences for ClusterConfiguration
// - adding a section in Status.(Cluster)ProfileResources for this (Cluster)Profile
func updateClusterConfigurationWithProfile(ctx context.Context, c client.Client, profile client.Object,
cluster *corev1.ObjectReference) error {
clusterConfiguration, err := getClusterConfiguration(ctx, c, cluster.Namespace,
getClusterConfigurationName(cluster.Name, clusterproxy.GetClusterType(cluster)))
if err != nil {
return err
}
err = updateClusterConfigurationOwnerReferences(ctx, c, profile, clusterConfiguration)
if err != nil {
return err
}
err = updateClusterConfigurationProfileResources(ctx, c, profile, clusterConfiguration)
if err != nil {
return err
}
return nil
}
// createClusterConfiguration creates ClusterConfiguration given a Sveltos/Cluster.
// If already existing, return nil
func createClusterConfiguration(ctx context.Context, c client.Client, cluster *corev1.ObjectReference) error {
clusterConfiguration := &configv1beta1.ClusterConfiguration{
ObjectMeta: metav1.ObjectMeta{
Namespace: cluster.Namespace,
Name: getClusterConfigurationName(cluster.Name, clusterproxy.GetClusterType(cluster)),
Labels: map[string]string{
configv1beta1.ClusterNameLabel: cluster.Name,
configv1beta1.ClusterTypeLabel: string(clusterproxy.GetClusterType(cluster)),
},
},
}
err := c.Create(ctx, clusterConfiguration)
if err != nil {
if apierrors.IsAlreadyExists(err) {
return nil
}
}
return err
}
// updateClusterConfigurations for each Sveltos/Cluster currently matching ClusterProfile/Profile:
// - creates corresponding ClusterConfiguration if one does not exist already
// - updates (eventually) corresponding ClusterConfiguration if one already exists
// Both create and update only add ClusterProfile/Profile as OwnerReference for ClusterConfiguration
func updateClusterConfigurations(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
for i := range profileScope.GetStatus().MatchingClusterRefs {
cluster := profileScope.GetStatus().MatchingClusterRefs[i]
// Create ClusterConfiguration if not already existing.
err := createClusterConfiguration(ctx, c, &cluster)
if err != nil {
profileScope.Logger.Error(err, fmt.Sprintf("failed to create ClusterConfiguration for cluster %s/%s",
cluster.Namespace, cluster.Name))
return err
}
// Update ClusterConfiguration
err = updateClusterConfigurationWithProfile(ctx, c, profileScope.Profile, &cluster)
if err != nil {
profileScope.Logger.Error(err, fmt.Sprintf("failed to update ClusterConfiguration for cluster %s/%s",
cluster.Namespace, cluster.Name))
return err
}
}
return nil
}
// cleanClusterConfigurations finds all ClusterConfigurations currently owned by ClusterProfile/Profile.
// For each such ClusterConfigurations, if corresponding Cluster is not a match anymore:
// - remove (Cluster)Profile as OwnerReference
// - if no more OwnerReferences are left, delete ClusterConfigurations
func cleanClusterConfigurations(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
clusterConfigurationList := &configv1beta1.ClusterConfigurationList{}
listOptions := []client.ListOption{}
if profileScope.Profile.GetObjectKind().GroupVersionKind().Kind == configv1beta1.ProfileKind {
listOptions = append(listOptions,
client.InNamespace(profileScope.Profile.GetNamespace()))
}
matchingClusterMap := make(map[string]bool)
info := func(namespace, clusterConfigurationName string) string {
return fmt.Sprintf("%s--%s", namespace, clusterConfigurationName)
}
for i := range profileScope.GetStatus().MatchingClusterRefs {
ref := &profileScope.GetStatus().MatchingClusterRefs[i]
matchingClusterMap[info(ref.Namespace, getClusterConfigurationName(ref.Name, clusterproxy.GetClusterType(ref)))] = true
}
err := c.List(ctx, clusterConfigurationList, listOptions...)
if err != nil {
return err
}
for i := range clusterConfigurationList.Items {
cc := &clusterConfigurationList.Items[i]
// If Sveltos/Cluster is still a match, continue (don't remove (Cluster)Profile as OwnerReference)
if _, ok := matchingClusterMap[info(cc.Namespace, cc.Name)]; ok {
continue
}
err = cleanClusterConfiguration(ctx, c, profileScope.Profile, cc)
if err != nil {
return err
}
}
return nil
}
func cleanClusterConfiguration(ctx context.Context, c client.Client, profile client.Object,
clusterConfiguration *configv1beta1.ClusterConfiguration) error {
// remove ClusterProfile/Profile as one of the ClusterConfiguration's owners
err := cleanClusterConfigurationOwnerReferences(ctx, c, profile, clusterConfiguration)
if err != nil {
return err
}
// remove the section in ClusterConfiguration.Status.ProfileResource used for this ClusterProfile/Profile
err = cleanClusterConfigurationProfileResources(ctx, c, profile, clusterConfiguration)
if err != nil {
return err
}
return nil
}
func cleanClusterConfigurationOwnerReferences(ctx context.Context, c client.Client, profile client.Object,
clusterConfiguration *configv1beta1.ClusterConfiguration) error {
ownerRef := metav1.OwnerReference{
Kind: profile.GetObjectKind().GroupVersionKind().Kind,
UID: profile.GetUID(),
APIVersion: configv1beta1.GroupVersion.String(),
Name: profile.GetName(),
}
if !util.IsOwnedByObject(clusterConfiguration, profile) {
return nil
}
clusterConfiguration.OwnerReferences = util.RemoveOwnerRef(clusterConfiguration.OwnerReferences, ownerRef)
if len(clusterConfiguration.OwnerReferences) == 0 {
return c.Delete(ctx, clusterConfiguration)
} else {
return c.Update(ctx, clusterConfiguration)
}
}
func cleanClusterConfigurationProfileResources(ctx context.Context, c client.Client, profile client.Object,
clusterConfiguration *configv1beta1.ClusterConfiguration) error {
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
currentClusterConfiguration, err := getClusterConfiguration(ctx, c,
clusterConfiguration.Namespace, clusterConfiguration.Name)
if err != nil {
// If ClusterConfiguration is not found, nothing to do here.
// ClusterConfiguration is removed if (Cluster)Profile was the last owner.
if apierrors.IsNotFound(err) {
return nil
}
return err
}
profileKind := profile.GetObjectKind().GroupVersionKind().Kind
if profileKind == configv1beta1.ClusterProfileKind {
return cleanClusterProfileResources(ctx, c, profile, currentClusterConfiguration)
} else {
return cleanProfileResources(ctx, c, profile, currentClusterConfiguration)
}
})
return err
}
func cleanClusterProfileResources(ctx context.Context, c client.Client, profile client.Object,
currentClusterConfiguration *configv1beta1.ClusterConfiguration) error {
toBeUpdated := false
for i := range currentClusterConfiguration.Status.ClusterProfileResources {
cpr := ¤tClusterConfiguration.Status.ClusterProfileResources[i]
if cpr.ClusterProfileName != profile.GetName() {
continue
}
// Order is not important. So move the element at index i with last one in order to avoid moving all elements.
length := len(currentClusterConfiguration.Status.ClusterProfileResources)
currentClusterConfiguration.Status.ClusterProfileResources[i] =
currentClusterConfiguration.Status.ClusterProfileResources[length-1]
currentClusterConfiguration.Status.ClusterProfileResources =
currentClusterConfiguration.Status.ClusterProfileResources[:length-1]
toBeUpdated = true
break
}
if toBeUpdated {
return c.Status().Update(ctx, currentClusterConfiguration)
}
return nil
}
func cleanProfileResources(ctx context.Context, c client.Client, profile client.Object,
currentClusterConfiguration *configv1beta1.ClusterConfiguration) error {
toBeUpdated := false
for i := range currentClusterConfiguration.Status.ProfileResources {
cpr := ¤tClusterConfiguration.Status.ProfileResources[i]
if cpr.ProfileName != profile.GetName() {
continue
}
// Order is not important. So move the element at index i with last one in order to avoid moving all elements.
length := len(currentClusterConfiguration.Status.ProfileResources)
currentClusterConfiguration.Status.ProfileResources[i] =
currentClusterConfiguration.Status.ProfileResources[length-1]
currentClusterConfiguration.Status.ProfileResources =
currentClusterConfiguration.Status.ProfileResources[:length-1]
toBeUpdated = true
break
}
if toBeUpdated {
return c.Status().Update(ctx, currentClusterConfiguration)
}
return nil
}
// ClusterSummary
// - Name is based on cluster type/name and matching ClusterProfile/Profile type/name
// - Labels: * ClusterProfileLabelName or ProfileLabelName
// * ClusterTypeLabel and ClusterNameLabel
// updateClusterSummary updates if necessary ClusterSummary given a ClusterProfile/Profile
// and a matching Sveltos/Cluster.
// If ClusterProfile/Profile Spec.SyncMode is set to one time, nothing will happen
func updateClusterSummary(ctx context.Context, c client.Client, profileScope *scope.ProfileScope,
cluster *corev1.ObjectReference) error {
if profileScope.IsOneTimeSync() {
return nil
}
clusterSummary, err := getClusterSummary(ctx, c, profileScope.GetKind(), profileScope.Name(),
cluster.Namespace, cluster.Name, clusterproxy.GetClusterType(cluster))
if err != nil {
return err
}
if reflect.DeepEqual(profileScope.GetSpec(), clusterSummary.Spec.ClusterProfileSpec) &&
reflect.DeepEqual(profileScope.Profile.GetAnnotations(), clusterSummary.Annotations) {
// Nothing has changed
return nil
}
clusterSummary.Annotations = profileScope.Profile.GetAnnotations()
clusterSummary.Spec.ClusterProfileSpec = *profileScope.GetSpec()
clusterSummary.Spec.ClusterType = clusterproxy.GetClusterType(cluster)
addClusterSummaryLabels(clusterSummary, profileScope, cluster)
// Copy annotation. Paused annotation might be set on ClusterProfile.
clusterSummary.Annotations = profileScope.Profile.GetAnnotations()
return c.Update(ctx, clusterSummary)
}
func addClusterSummaryLabels(clusterSummary *configv1beta1.ClusterSummary, profileScope *scope.ProfileScope,
cluster *corev1.ObjectReference) {
if profileScope.Profile.GetObjectKind().GroupVersionKind().Kind == configv1beta1.ClusterProfileKind {
addLabel(clusterSummary, ClusterProfileLabelName, profileScope.Name())
} else {
addLabel(clusterSummary, ProfileLabelName, profileScope.Name())
}
addLabel(clusterSummary, configv1beta1.ClusterNameLabel, cluster.Name)
if cluster.APIVersion == libsveltosv1beta1.GroupVersion.String() {
addLabel(clusterSummary, configv1beta1.ClusterTypeLabel, string(libsveltosv1beta1.ClusterTypeSveltos))
} else {
addLabel(clusterSummary, configv1beta1.ClusterTypeLabel, string(libsveltosv1beta1.ClusterTypeCapi))
}
clusterProfileLabels := profileScope.Profile.GetLabels()
if clusterProfileLabels != nil {
v, ok := clusterProfileLabels[libsveltosv1beta1.ServiceAccountNameLabel]
if ok {
addLabel(clusterSummary, libsveltosv1beta1.ServiceAccountNameLabel, v)
}
v, ok = clusterProfileLabels[libsveltosv1beta1.ServiceAccountNamespaceLabel]
if ok {
addLabel(clusterSummary, libsveltosv1beta1.ServiceAccountNamespaceLabel, v)
}
}
}
// createClusterSummary creates ClusterSummary given a ClusterProfile and a matching Sveltos/Cluster
func createClusterSummary(ctx context.Context, c client.Client, profileScope *scope.ProfileScope,
cluster *corev1.ObjectReference) error {
clusterSummaryName := GetClusterSummaryName(profileScope.GetKind(), profileScope.Name(),
cluster.Name, cluster.APIVersion == libsveltosv1beta1.GroupVersion.String())
clusterSummary := &configv1beta1.ClusterSummary{
ObjectMeta: metav1.ObjectMeta{
Name: clusterSummaryName,
Namespace: cluster.Namespace,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: configv1beta1.GroupVersion.String(),
Kind: profileScope.Profile.GetObjectKind().GroupVersionKind().Kind,
Name: profileScope.Profile.GetName(),
UID: profileScope.Profile.GetUID(),
},
},
Annotations: profileScope.Profile.GetAnnotations(),
},
Spec: configv1beta1.ClusterSummarySpec{
ClusterNamespace: cluster.Namespace,
ClusterName: cluster.Name,
ClusterProfileSpec: *profileScope.GetSpec(),
},
}
clusterSummary.Spec.ClusterType = clusterproxy.GetClusterType(cluster)
clusterSummary.Labels = profileScope.Profile.GetLabels()
addClusterSummaryLabels(clusterSummary, profileScope, cluster)
// Copy annotation. Paused annotation might be set on ClusterProfile.
clusterSummary.Annotations = profileScope.Profile.GetAnnotations()
return c.Create(ctx, clusterSummary)
}
// updateClusterSummaries for each Sveltos/Cluster currently matching ClusterProfile/Profile:
// - creates corresponding ClusterSummary if one does not exist already
// - updates (eventually) corresponding ClusterSummary if one already exists
// Return an error if due to MaxUpdate not all ClusterSummaries are synced
func updateClusterSummaries(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
currentHash := getProfileSpecHash(profileScope)
// Remove Status.UpdatedClusters if hash is different
if !reflect.DeepEqual(profileScope.GetStatus().UpdatedClusters.Hash, currentHash) {
profileScope.GetStatus().UpdatedClusters = configv1beta1.Clusters{
Hash: currentHash,
Clusters: []corev1.ObjectReference{},
}
}
// Remove clusters non matching anynmore from UpdatedClusters and UpdatingClusters
reviseUpdatedAndUpdatingClusters(profileScope)
if err := reviseUpdatingClusterList(ctx, c, profileScope, currentHash); err != nil {
return err
}
updatedClusters, updatingClusters := getUpdatedAndUpdatingClusters(profileScope)
maxUpdate := getMaxUpdate(profileScope)
skippedUpdate := false
// Consider matchingCluster number and MaxUpdate, walk remaining matching clusters. If more clusters can be
// updated, update ClusterSummary and add it to UpdatingClusters
for i := range profileScope.GetStatus().MatchingClusterRefs {
cluster := profileScope.GetStatus().MatchingClusterRefs[i]
logger := profileScope.Logger
logger = logger.WithValues("cluster", fmt.Sprintf("%s:%s/%s", cluster.Kind, cluster.Namespace, cluster.Name))
ready, err := clusterproxy.IsClusterReadyToBeConfigured(ctx, c, &cluster, profileScope.Logger)
if err != nil {
return err
}
if !ready {
logger.V(logs.LogDebug).Info("Cluster is not ready yet")
continue
}
if updatedClusters.Has(&cluster) {
logger.V(logs.LogDebug).Info("Cluster is already updated")
continue
}
if maxUpdate != 0 {
// maxUpdate is set. Skip paused clusters (which would not be updated anyhow as set to paused)
// and try to pcik any non paused cluster
isClusterPaused, err := clusterproxy.IsClusterPaused(ctx, c, cluster.Namespace,
cluster.Name, clusterproxy.GetClusterType(&cluster))
if err != nil {
logger.V(logs.LogDebug).Info(fmt.Sprintf("failed to verify if cluster is paused: %v", err))
return err
}
if isClusterPaused {
// No need to set skippedUpdated. Profile will react to a cluster switching from paused to unpaused
logger.V(logs.LogDebug).Info("Cluster is paused and maxUpdate is set. Ignore this cluster.")
continue
}
}
// if maxUpdate is set no more than maxUpdate clusters can be updated in parallel by ClusterProfile
if maxUpdate != 0 && !updatingClusters.Has(&cluster) && updatingClusters.Len() >= int(maxUpdate) {
logger.V(logs.LogDebug).Info(fmt.Sprintf("Already %d being updating", updatingClusters.Len()))
skippedUpdate = true
continue
}
// ClusterProfile does not look at whether Cluster is paused or not.
// If a Cluster exists and it is a match, ClusterSummary is created (and ClusterSummary.Spec kept in sync if mode is
// continuous).
// ClusterSummary won't program cluster in paused state.
err = patchClusterSummary(ctx, c, profileScope, &cluster, logger)
if err != nil {
return err
}
if !updatingClusters.Has(&cluster) {
updatingClusters.Insert(&cluster)
profileScope.GetStatus().UpdatingClusters.Clusters =
append(profileScope.GetStatus().UpdatingClusters.Clusters,
cluster)
}
profileScope.GetStatus().UpdatingClusters.Hash = currentHash
}
if skippedUpdate {
return fmt.Errorf("not all clusters updated yet. %d still being updated",
len(profileScope.GetStatus().UpdatingClusters.Clusters))
}
// If all ClusterSummaries have been updated, reset Updated and Updating
profileScope.GetStatus().UpdatedClusters = configv1beta1.Clusters{}
profileScope.GetStatus().UpdatingClusters = configv1beta1.Clusters{}
return nil
}
func patchClusterSummary(ctx context.Context, c client.Client, profileScope *scope.ProfileScope,
cluster *corev1.ObjectReference, logger logr.Logger) error {
// ClusterProfile does not look at whether Cluster is paused or not.
// If a Cluster exists and it is a match, ClusterSummary is created (and ClusterSummary.Spec kept in sync if mode is
// continuous).
// ClusterSummary won't program cluster in paused state.
_, err := getClusterSummary(ctx, c, profileScope.GetKind(), profileScope.Name(), cluster.Namespace,
cluster.Name, clusterproxy.GetClusterType(cluster))
if err != nil {
if apierrors.IsNotFound(err) {
err = createClusterSummary(ctx, c, profileScope, cluster)
if err != nil {
logger.Error(err, "failed to create ClusterSummary")
}
} else {
logger.Error(err, "failed to get ClusterSummary")
return err
}
} else {
err = updateClusterSummary(ctx, c, profileScope, cluster)
if err != nil {
logger.Error(err, "failed to update ClusterSummary")
return err
}
}
return nil
}
// cleanClusterSummaries finds all ClusterSummary currently owned by ClusterProfile/Profile.
// For each such ClusterSummary, if corresponding Sveltos/Cluster is not a match anymore, deletes ClusterSummary
func cleanClusterSummaries(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
matching := make(map[string]bool)
getClusterInfo := func(clusterNamespace, clusterName string, clusterType libsveltosv1beta1.ClusterType) string {
return fmt.Sprintf("%s-%s-%s", clusterType, clusterNamespace, clusterName)
}
for i := range profileScope.GetStatus().MatchingClusterRefs {
reference := profileScope.GetStatus().MatchingClusterRefs[i]
clusterName := getClusterInfo(reference.Namespace, reference.Name, clusterproxy.GetClusterType(&reference))
matching[clusterName] = true
}
listOptions := []client.ListOption{}
if profileScope.Profile.GetObjectKind().GroupVersionKind().Kind == configv1beta1.ClusterProfileKind {
listOptions = append(listOptions, client.MatchingLabels{ClusterProfileLabelName: profileScope.Name()})
} else {
listOptions = append(listOptions,
client.MatchingLabels{ProfileLabelName: profileScope.Name()},
client.InNamespace(profileScope.Profile.GetNamespace()))
}
clusterSummaryList := &configv1beta1.ClusterSummaryList{}
if err := c.List(ctx, clusterSummaryList, listOptions...); err != nil {
return err
}
// Check if any ClusterSummary instance that needs to be removed is still present
foundClusterSummaries := false
for i := range clusterSummaryList.Items {
cs := &clusterSummaryList.Items[i]
if util.IsOwnedByObject(cs, profileScope.Profile) {
if _, ok := matching[getClusterInfo(cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cs.Spec.ClusterType)]; !ok {
foundClusterSummaries = true
err := c.Delete(ctx, cs)
if err != nil {
profileScope.Logger.Error(err, fmt.Sprintf("failed to update ClusterSummary for cluster %s/%s",
cs.Namespace, cs.Name))
return err
}
}
}
if err := updateClusterSummarySyncMode(ctx, c, cs, profileScope.GetSpec().SyncMode); err != nil {
return err
}
}
if foundClusterSummaries {
return fmt.Errorf("clusterSummaries still present")
}
return nil
}
func updateClusterSummarySyncMode(ctx context.Context, c client.Client,
clusterSummary *configv1beta1.ClusterSummary, syncMode configv1beta1.SyncMode) error {
if clusterSummary.Spec.ClusterProfileSpec.SyncMode == syncMode {
return nil
}
currentClusterSummary := &configv1beta1.ClusterSummary{}
err := c.Get(ctx,
types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name},
currentClusterSummary)
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
clusterSummary.Spec.ClusterProfileSpec.SyncMode = syncMode
return c.Update(ctx, clusterSummary)
}
// ClusterReports
// updateClusterReports for each Sveltos/Cluster currently matching ClusterProfile/Profile:
// - if syncMode is DryRun, creates corresponding ClusterReport if one does not exist already;
// - if syncMode is DryRun, deletes ClusterReports for any Sveltos/Cluster not matching anymore;
// - if syncMode is not DryRun, deletes ClusterReports created by this ClusterProfile instance
func updateClusterReports(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
if profileScope.IsDryRunSync() {
err := createClusterReports(ctx, c, profileScope)
if err != nil {
profileScope.Logger.Error(err, "failed to create ClusterReports")
return err
}
} else {
// delete all ClusterReports created by this ClusterProfile/Profile instance
err := cleanClusterReports(ctx, c, profileScope)
if err != nil {
profileScope.Logger.Error(err, "failed to delete ClusterReports")
return err
}
}
return nil
}
// createClusterReports creates a ClusterReport for each matching Cluster
func createClusterReports(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
for i := range profileScope.GetStatus().MatchingClusterRefs {
cluster := profileScope.GetStatus().MatchingClusterRefs[i]
// Create ClusterReport if not already existing.
err := createClusterReport(ctx, c, profileScope.Profile, &cluster)
if err != nil {
return err
}
}
return nil
}
// createClusterReport creates ClusterReport given a Sveltos/Cluster.
// If already existing, return nil
func createClusterReport(ctx context.Context, c client.Client, profile client.Object,
cluster *corev1.ObjectReference) error {
clusterType := clusterproxy.GetClusterType(cluster)
lbls := map[string]string{
configv1beta1.ClusterNameLabel: cluster.Name,
configv1beta1.ClusterTypeLabel: string(clusterproxy.GetClusterType(cluster)),
}
if profile.GetObjectKind().GroupVersionKind().Kind == configv1beta1.ClusterProfileKind {
lbls[ClusterProfileLabelName] = profile.GetName()
} else {
lbls[ProfileLabelName] = profile.GetName()
}
clusterReport := &configv1beta1.ClusterReport{
ObjectMeta: metav1.ObjectMeta{
Namespace: cluster.Namespace,
Name: getClusterReportName(profile.GetObjectKind().GroupVersionKind().Kind, profile.GetName(),
cluster.Name, clusterType),
Labels: lbls,
OwnerReferences: []metav1.OwnerReference{
{
Kind: profile.GetObjectKind().GroupVersionKind().Kind,
UID: profile.GetUID(),
APIVersion: configv1beta1.GroupVersion.String(),
Name: profile.GetName(),
},
},
},
Spec: configv1beta1.ClusterReportSpec{
ClusterNamespace: cluster.Namespace,
ClusterName: cluster.Name,
},
}
err := c.Create(ctx, clusterReport)
if err != nil {
if apierrors.IsAlreadyExists(err) {
return nil
}
}
return err
}
// cleanClusterReports deletes ClusterReports created by this ClusterProfile/Profile instance.
func cleanClusterReports(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error {
listOptions := []client.ListOption{}
if profileScope.IsDryRunSync() {
return nil
}
if profileScope.GetKind() == configv1beta1.ClusterProfileKind {
listOptions = append(listOptions, client.MatchingLabels{ClusterProfileLabelName: profileScope.Name()})
} else {
listOptions = append(listOptions,
client.MatchingLabels{ProfileLabelName: profileScope.Name()},
client.InNamespace(profileScope.Namespace()))
}
clusterReportList := &configv1beta1.ClusterReportList{}
err := c.List(ctx, clusterReportList, listOptions...)
if err != nil {
return err
}
for i := range clusterReportList.Items {
cr := &clusterReportList.Items[i]
err = c.Delete(ctx, cr)
if err != nil {
if !apierrors.IsNotFound(err) {
return err
}
}
}
return nil
}
// getProfileSpecHash returns hash of current clusterProfile/Profile Spec
func getProfileSpecHash(profileScope *scope.ProfileScope) []byte {
h := sha256.New()
var config string
config += render.AsCode(profileScope.GetSpec())
h.Write([]byte(config))
return h.Sum(nil)
}
// reviseUpdatedAndUpdatingClusters updates ClusterProfile Status UpdatedClusters and UpdatingClusters fields
// by removing clusters non matching ClusterProfile/Profile anymore.
// - UpdatedClusters represents list of matching clusters already updated since last ClusterProfile/Profile change
// - UpdatingClusters represents list of matching clusters being updated since last ClusterProfile/Profile change
func reviseUpdatedAndUpdatingClusters(profileScope *scope.ProfileScope) {
matchingCluster := libsveltosset.Set{}
for i := range profileScope.GetStatus().MatchingClusterRefs {
cluster := profileScope.GetStatus().MatchingClusterRefs[i]
matchingCluster.Insert(&cluster)
}
updatedClusters := &libsveltosset.Set{}
currentUpdatedClusters := make([]corev1.ObjectReference, 0, len(profileScope.GetStatus().UpdatedClusters.Clusters))
for i := range profileScope.GetStatus().UpdatedClusters.Clusters {
cluster := &profileScope.GetStatus().UpdatedClusters.Clusters[i]
if matchingCluster.Has(cluster) {
currentUpdatedClusters = append(currentUpdatedClusters, *cluster)
updatedClusters.Insert(cluster)
}
}
profileScope.GetStatus().UpdatedClusters.Clusters = currentUpdatedClusters
updatingClusters := &libsveltosset.Set{}
currentUpdatingClusters := make([]corev1.ObjectReference, 0, len(profileScope.GetStatus().UpdatingClusters.Clusters))
for i := range profileScope.GetStatus().UpdatingClusters.Clusters {
cluster := &profileScope.GetStatus().UpdatingClusters.Clusters[i]
if matchingCluster.Has(cluster) {
currentUpdatingClusters = append(currentUpdatingClusters, *cluster)
updatingClusters.Insert(cluster)
}
}
profileScope.GetStatus().UpdatingClusters.Clusters = currentUpdatingClusters
}
func getMaxUpdate(profileScope *scope.ProfileScope) int32 {
if profileScope.GetSpec().MaxUpdate == nil {
return int32(0)
}
// Check the Type field to determine if it is an int or a string.
switch profileScope.GetSpec().MaxUpdate.Type {
case intstr.Int:
return profileScope.GetSpec().MaxUpdate.IntVal
case intstr.String:
maxUpdateString := profileScope.GetSpec().MaxUpdate.StrVal
maxUpdateString = strings.ReplaceAll(maxUpdateString, "%s", "")
var maxUpdateInt int
if _, err := fmt.Sscanf(maxUpdateString, "%d", &maxUpdateInt); err != nil {
// There is a validation on format accepted so this should never happen
profileScope.Logger.V(logs.LogInfo).Info(fmt.Sprintf("incorrect MaxUpdate %s: %v",
profileScope.GetSpec().MaxUpdate.StrVal, err))
return int32(0)
}
return int32(math.Ceil(percent.Percent(
maxUpdateInt,
len(profileScope.GetStatus().MatchingClusterRefs),
)))
}
return int32(0)
}
func getUpdatedAndUpdatingClusters(profileScope *scope.ProfileScope,
) (updatedClusters, updatingClusters *libsveltosset.Set) {
updatedClusters = &libsveltosset.Set{}
for i := range profileScope.GetStatus().UpdatedClusters.Clusters {
cluster := &profileScope.GetStatus().UpdatedClusters.Clusters[i]
updatedClusters.Insert(cluster)
}
updatingClusters = &libsveltosset.Set{}
for i := range profileScope.GetStatus().UpdatingClusters.Clusters {
cluster := &profileScope.GetStatus().UpdatingClusters.Clusters[i]
updatingClusters.Insert(cluster)
}
return
}
// reviseUpdatingClusterList walks over list of clusters in updating state.
// If all features are marked as provisioned, cluster is moved to updated list.
// Otherwise it is left in the updating list.
func reviseUpdatingClusterList(ctx context.Context, c client.Client, profileScope *scope.ProfileScope,
currentHash []byte) error {
if !reflect.DeepEqual(profileScope.GetStatus().UpdatingClusters.Hash, currentHash) {
// Since ClusterProfile/Profile Spec hash has changed, even if ClusterSummary are in
// Provisioned state those cannot be moved to UpdatedClusters. Due to ClusterProfile/Profile
// Spec change new updates are needed
return nil
}
// Walk UpdatingClusters:
// - if hash is same and cluster is provisioned, moved to UpdatedClusters. Remove from UpdatingClusters
// - if hash is different, update ClusterSummary and leave it in UpdatingClusters
updatingClusters := []corev1.ObjectReference{}
for i := range profileScope.GetStatus().UpdatingClusters.Clusters {
cluster := &profileScope.GetStatus().UpdatingClusters.Clusters[i]
clusterType := clusterproxy.GetClusterType(cluster)
clusterSumary, err := getClusterSummary(ctx, c, profileScope.GetKind(), profileScope.Name(),
cluster.Namespace, cluster.Name, clusterType)
if err != nil {
return err
}
if isCluterSummaryProvisioned(clusterSumary) {
profileScope.GetStatus().UpdatedClusters.Clusters =
append(profileScope.GetStatus().UpdatedClusters.Clusters, *cluster)
} else {
updatingClusters = append(updatingClusters, *cluster)
}
}
profileScope.GetStatus().UpdatingClusters.Clusters = updatingClusters
return nil
}
func addFinalizer(ctx context.Context, profileScope *scope.ProfileScope, finalizer string) error {
controllerutil.AddFinalizer(profileScope.Profile, finalizer)
if err := profileScope.PatchObject(ctx); err != nil {
profileScope.Error(err, "Failed to add finalizer")
return fmt.Errorf("failed to add finalizer for %s: %w", profileScope.Name(), err)
}
return nil
}
func reconcileDeleteCommon(ctx context.Context, c client.Client, profileScope *scope.ProfileScope,
finalizer string, logger logr.Logger) error {
profileScope.SetMatchingClusterRefs(nil)
depManager, err := dependencymanager.GetManagerInstance()
if err != nil {
return err
}