/
subscription.go
1365 lines (1076 loc) · 38.5 KB
/
subscription.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 2021 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 utils
import (
"context"
"crypto/sha1" // #nosec G505 Used only to generate random value to be used to generate hash string
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"time"
chnv1 "open-cluster-management.io/multicloud-operators-channel/pkg/apis/apps/v1"
addonV1alpha1 "open-cluster-management.io/api/addon/v1alpha1"
clusterapi "open-cluster-management.io/api/cluster/v1beta1"
manifestWorkV1 "open-cluster-management.io/api/work/v1"
appv1 "open-cluster-management.io/multicloud-operators-subscription/pkg/apis/apps/v1"
appsubReportV1alpha1 "open-cluster-management.io/multicloud-operators-subscription/pkg/apis/apps/v1alpha1"
managedClusterView "open-cluster-management.io/multicloud-operators-subscription/pkg/apis/view/v1beta1"
corev1 "k8s.io/api/core/v1"
clientsetx "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/equality"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
const (
//Max is 52 chars but as helm add behind the scene extension -delete-registrations for some objects
//The new limit is 31 chars
maxNameLength = 52 - len("-delete-registrations")
randomLength = 5
//minus 1 because we add a dash
annotationsSep = ","
maxGeneratedNameLength = maxNameLength - randomLength - 1
// klusterletagentaddon secret token reconcile
addonServiceAccountName = "application-manager"
addonServiceAccountNamespace = "open-cluster-management-agent-addon"
)
// PlacementDecisionPredicateFunctions filters PlacementDecision status decisions update
var PlacementDecisionPredicateFunctions = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
newPd, newOK := e.ObjectNew.(*clusterapi.PlacementDecision)
oldPd, oldOK := e.ObjectOld.(*clusterapi.PlacementDecision)
if !newOK || !oldOK {
klog.Infof("not placementDecision object, skip....")
return false
}
if !reflect.DeepEqual(newPd.Status.Decisions, oldPd.Status.Decisions) {
klog.Infof("cluster Decision list updated old: %v, new:%v", oldPd.Status.Decisions, newPd.Status.Decisions)
return true
}
return false
},
CreateFunc: func(e event.CreateEvent) bool {
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
}
func IsSubscriptionResourceChanged(oSub, nSub *appv1.Subscription) bool {
if IsSubscriptionBasicChanged(oSub, nSub) {
return true
}
// do we care phase change?
if nSub.Status.Phase == "" || nSub.Status.Phase != oSub.Status.Phase {
klog.V(5).Info("We care phase..", nSub.Status.Phase, " vs ", oSub.Status.Phase)
return true
}
klog.V(5).Info("Something we don't care changed")
return false
}
var AppSubSummaryPredicateFunc = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
klog.Info("UpdateFunc oldlabels:", e.ObjectOld.GetLabels())
var clusterLabel string
_, oldOK := e.ObjectOld.GetLabels()["apps.open-cluster-management.io/cluster"]
clusterLabel, newOK := e.ObjectNew.GetLabels()["apps.open-cluster-management.io/cluster"]
if !oldOK || !newOK || clusterLabel == "" {
klog.V(1).Infof("Not a managed cluster appSubPackageStatus updated, old: %v/%v, new: %v/%v",
e.ObjectOld.GetNamespace(), e.ObjectOld.GetName(), e.ObjectNew.GetNamespace(), e.ObjectNew.GetName())
return false
}
oldAppSubSummary, ok := e.ObjectOld.(*appsubReportV1alpha1.SubscriptionReport)
if !ok {
klog.V(1).Infof("Not a valid managed cluster appSubPackageStatus, old: %v/%v", e.ObjectOld.GetNamespace(), e.ObjectOld.GetName())
return false
}
newAppSubSummary, ok := e.ObjectNew.(*appsubReportV1alpha1.SubscriptionReport)
if !ok {
klog.V(1).Infof("Not a valid managed cluster appSubPackageStatus, new: %v/%v", e.ObjectNew.GetNamespace(), e.ObjectNew.GetName())
return false
}
return !equality.Semantic.DeepEqual(oldAppSubSummary, newAppSubSummary)
},
CreateFunc: func(e event.CreateEvent) bool {
klog.Info("CreateFunc oldlabels:", e.Object.GetLabels())
var clusterLabel string
clusterLabel, ok := e.Object.GetLabels()["apps.open-cluster-management.io/cluster"]
if !ok || clusterLabel == "" {
klog.V(1).Infof("Not a managed cluster appSubPackageStatus created: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
return false
}
klog.V(1).Infof("New managed cluster appSubPackageStatus created: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
klog.Info("DeleteFunc oldlabels:", e.Object.GetLabels())
var clusterLabel string
clusterLabel, ok := e.Object.GetLabels()["apps.open-cluster-management.io/cluster"]
if !ok || clusterLabel == "" {
klog.V(1).Infof("Not a managed cluster appSubPackageStatus deleted: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
return false
}
klog.Infof("managed cluster appSubPackageStatus deleted: %v/%v", e.Object.GetNamespace(), e.Object.GetName())
return true
},
}
// SubscriptionPredicateFunctions filters status update
var SubscriptionPredicateFunctions = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
subOld := e.ObjectOld.(*appv1.Subscription)
subNew := e.ObjectNew.(*appv1.Subscription)
return IsSubscriptionBasicChanged(subOld, subNew)
},
}
func IsSubscriptionBasicChanged(o, n *appv1.Subscription) bool {
fOsub := FilterOutTimeRelatedFields(o)
fNSub := FilterOutTimeRelatedFields(n)
// need to process delete with finalizers
if !reflect.DeepEqual(fOsub.GetFinalizers(), fNSub.GetFinalizers()) {
return true
}
// we care label change, pass it down
klog.Infof("fOsub_labels: %v", fOsub.GetLabels())
klog.Infof("fNSub_labels: %v", fNSub.GetLabels())
if !reflect.DeepEqual(fOsub.GetLabels(), fNSub.GetLabels()) {
klog.Info("different labels found")
return true
}
// In hub cluster, these annotations get updated by subscription reconcile
// so remove them before comparison to avoid triggering another reconciliation.
oldAnnotations := fOsub.GetAnnotations()
newAnnotations := fNSub.GetAnnotations()
if !isEqualAnnotationFiled(oldAnnotations, newAnnotations, appv1.AnnotationDeployables) {
return true
}
if !isEqualAnnotationFiled(oldAnnotations, newAnnotations, appv1.AnnotationTopo) {
return true
}
// When user updates the desired Git commit or tag, this annotation is expected to change as well by reconcile.
if !isEqualAnnotationFiled(oldAnnotations, newAnnotations, appv1.AnnotationGitCommit) {
return true
}
// we care annotation change. pass it down
if !reflect.DeepEqual(oldAnnotations, newAnnotations) {
return true
}
// we care spec for sure, we use the generation of 2 object to track the
// spec version
//https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource
if !reflect.DeepEqual(fOsub.Spec, fNSub.Spec) {
return true
}
return false
}
func isEqualAnnotationFiled(o, n map[string]string, key string) bool {
oDpl := o[key]
nDpl := n[key]
oOut := stringToSet(oDpl, annotationsSep)
nOut := stringToSet(nDpl, annotationsSep)
delete(o, key)
delete(n, key)
return reflect.DeepEqual(oOut, nOut)
}
func stringToSet(in string, sep string) map[string]struct{} {
out := map[string]struct{}{}
for _, w := range strings.Split(in, sep) {
if _, ok := out[w]; !ok {
out[w] = struct{}{}
}
}
return out
}
// the input object shouldn't be changed at all
func FilterOutTimeRelatedFields(in *appv1.Subscription) *appv1.Subscription {
if in == nil {
return nil
}
out := in.DeepCopy()
anno := out.GetAnnotations()
if len(anno) == 0 {
anno = map[string]string{}
}
//annotation that contains time
//also remove annotations that are added and updated by the subscription controller
timeFields := []string{"kubectl.kubernetes.io/last-applied-configuration"}
if anno[appv1.AnnotationGitTag] == "" && anno[appv1.AnnotationGitTargetCommit] == "" {
timeFields = append(timeFields, appv1.AnnotationGitCommit)
}
for _, f := range timeFields {
delete(anno, f)
}
out.SetAnnotations(anno)
//set managedFields time to empty
outF := []metav1.ManagedFieldsEntry{}
out.SetManagedFields(outF)
// we don't actually care about the status, when create a manifestwork for
// given subscription
return out
}
// assuming the message is only storing the window info, following format:
// cluster1:active,cluster2:block
func isSameMessage(aMsg, bMsg string) bool {
aMap, bMap := stringToMap(aMsg), stringToMap(bMsg)
if len(aMap) != len(bMap) {
return false
}
for ak, av := range aMap {
if bv, ok := bMap[ak]; !ok || av != bv {
return false
}
}
return true
}
func stringToMap(msg string) map[string]string {
cunits := strings.Split(msg, ",")
out := map[string]string{}
for _, val := range cunits {
u := strings.Split(val, ":")
if len(u) == 2 {
out[u[0]] = u[1]
} else if len(u) == 1 {
out[u[0]] = ""
}
}
return out
}
func IsHubRelatedStatusChanged(old, nnew *appv1.SubscriptionStatus) bool {
if !isAnsibleStatusEqual(old.AnsibleJobsStatus, nnew.AnsibleJobsStatus) {
return true
}
if old.Phase != nnew.Phase || old.Reason != nnew.Reason || !isSameMessage(old.Message, nnew.Message) {
return true
}
//care about the managed subscription status
if !isEqualSubClusterStatus(old.Statuses, nnew.Statuses) {
return true
}
return false
}
func isAnsibleStatusEqual(a, b appv1.AnsibleJobsStatus) bool {
if a.LastPosthookJob != b.LastPosthookJob {
return false
}
if a.LastPrehookJob != b.LastPrehookJob {
return false
}
return true
}
// ChannelPredicateFunctions filters channel spec update
var ChannelPredicateFunctions = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
newChn := e.ObjectNew.(*chnv1.Channel)
oldChn := e.ObjectOld.(*chnv1.Channel)
oldAnnotations := oldChn.GetAnnotations()
newAnnotations := newChn.GetAnnotations()
if !reflect.DeepEqual(oldAnnotations, newAnnotations) {
return true
}
return !reflect.DeepEqual(newChn.Spec, oldChn.Spec)
},
CreateFunc: func(e event.CreateEvent) bool {
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
}
// ServiceAccountPredicateFunctions watches for changes in klusterlet-addon-appmgr service account in open-cluster-management-agent-addon namespace
var ServiceAccountPredicateFunctions = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
newSA := e.ObjectNew.(*corev1.ServiceAccount)
if strings.EqualFold(newSA.Namespace, addonServiceAccountNamespace) && strings.EqualFold(newSA.Name, addonServiceAccountName) {
return true
}
return false
},
CreateFunc: func(e event.CreateEvent) bool {
sa := e.Object.(*corev1.ServiceAccount)
if strings.EqualFold(sa.Namespace, addonServiceAccountNamespace) && strings.EqualFold(sa.Name, addonServiceAccountName) {
return true
}
return false
},
DeleteFunc: func(e event.DeleteEvent) bool {
sa := e.Object.(*corev1.ServiceAccount)
if strings.EqualFold(sa.Namespace, addonServiceAccountNamespace) && strings.EqualFold(sa.Name, addonServiceAccountName) {
return true
}
return false
},
}
// GetHostSubscriptionFromObject extract the namespacedname of subscription hosting the object resource
func GetHostSubscriptionFromObject(obj metav1.Object) *types.NamespacedName {
if obj == nil {
return nil
}
objanno := obj.GetAnnotations()
if objanno == nil {
return nil
}
sourcestr := objanno[appv1.AnnotationHosting]
if sourcestr == "" {
return nil
}
parsedstr := strings.Split(sourcestr, "/")
if len(parsedstr) != 2 {
return nil
}
host := &types.NamespacedName{Name: parsedstr[1], Namespace: parsedstr[0]}
return host
}
// SetInClusterPackageStatus creates status strcuture and fill status
func SetInClusterPackageStatus(substatus *appv1.SubscriptionStatus, pkgname string, pkgerr error, status interface{}) error {
newStatus := substatus.DeepCopy()
if newStatus.Statuses == nil {
newStatus.Statuses = make(map[string]*appv1.SubscriptionPerClusterStatus)
}
clst := newStatus.Statuses["/"]
if clst == nil || clst.SubscriptionPackageStatus == nil {
clst = &appv1.SubscriptionPerClusterStatus{}
clst.SubscriptionPackageStatus = make(map[string]*appv1.SubscriptionUnitStatus)
}
pkgstatus := clst.SubscriptionPackageStatus[pkgname]
if pkgstatus == nil {
pkgstatus = &appv1.SubscriptionUnitStatus{}
}
if pkgerr == nil {
pkgstatus.Phase = appv1.SubscriptionSubscribed
pkgstatus.Reason = ""
pkgstatus.Message = ""
} else {
pkgstatus.Phase = appv1.SubscriptionFailed
pkgstatus.Reason = pkgerr.Error()
}
var err error
pkgstatus.LastUpdateTime = metav1.Now()
if status != nil {
if pkgstatus.ResourceStatus == nil {
pkgstatus.ResourceStatus = &runtime.RawExtension{}
}
pkgstatus.ResourceStatus.Raw, err = json.Marshal(status)
if err != nil {
klog.Info("Failed to mashall status for ", status, " with err:", err)
}
} else {
pkgstatus.ResourceStatus = nil
}
klog.V(1).Infof("Set package status, pkg: %v, pkgstatus: %#v", pkgname, pkgstatus)
clst.SubscriptionPackageStatus[pkgname] = pkgstatus
newStatus.Statuses["/"] = clst
newStatus.LastUpdateTime = metav1.Now()
if isEmptySubscriptionStatus(newStatus) || !isEqualSubscriptionStatus(substatus, newStatus) {
newStatus.DeepCopyInto(substatus)
}
return nil
}
func isEmptySubscriptionStatus(a *appv1.SubscriptionStatus) bool {
if a == nil {
return true
}
if len(a.Message) != 0 || len(a.Phase) != 0 || len(a.Reason) != 0 || len(a.Statuses) != 0 {
return false
}
return true
}
func IsEqualSubScriptionStatus(o, n *appv1.SubscriptionStatus) bool {
return isEqualSubscriptionStatus(o, n)
}
func isEqualSubscriptionStatus(a, b *appv1.SubscriptionStatus) bool {
if a == nil && b == nil {
return true
}
if a != nil && b == nil {
return false
}
if a == nil && b != nil {
return false
}
if !isSameMessage(a.Message, b.Message) {
return false
}
if a.Phase != b.Phase || a.Reason != b.Reason {
return false
}
aMap, bMap := a.Statuses, b.Statuses
if len(aMap) != len(bMap) {
return false
}
if len(aMap) == 0 {
return true
}
return isEqualSubClusterStatus(aMap, bMap)
}
func isEqualSubClusterStatus(a, b map[string]*appv1.SubscriptionPerClusterStatus) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
w, ok := b[k]
if ok {
if v == nil && w == nil {
continue
}
if v != nil && w != nil && isEqualSubPerClusterStatus(v.SubscriptionPackageStatus, w.SubscriptionPackageStatus) {
continue
}
return false
}
return false
}
return true
}
func isEqualSubPerClusterStatus(a, b map[string]*appv1.SubscriptionUnitStatus) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if w, ok := b[k]; !ok || !isEqualSubscriptionUnitStatus(v, w) {
return false
}
}
return true
}
func isEqualSubscriptionUnitStatus(a, b *appv1.SubscriptionUnitStatus) bool {
if a == nil && b == nil {
return true
}
if a != nil && b == nil {
return false
}
if a == nil && b != nil {
return false
}
if !isSameMessage(a.Message, b.Message) {
return false
}
if a.Phase != b.Phase || a.Reason != b.Reason ||
!reflect.DeepEqual(a.ResourceStatus, b.ResourceStatus) {
return false
}
return true
}
func UpdateLastUpdateTime(clt client.Client, instance *appv1.Subscription) {
curSub := &appv1.Subscription{}
if err := clt.Get(context.TODO(), types.NamespacedName{Name: instance.GetName(), Namespace: instance.GetNamespace()}, curSub); err != nil {
klog.Warning("Failed to get appsub to update LastUpdateTime", err)
return
}
curSub.Status.LastUpdateTime = metav1.Now()
if err := clt.Status().Update(context.TODO(), curSub); err != nil {
klog.Warning("Failed to update LastUpdateTime", err)
}
}
func UpdateSubscriptionStatus(clt client.Client, subName, subNs string, phase appv1.SubscriptionPhase, reason string) {
curSub := &appv1.Subscription{}
if err := clt.Get(context.TODO(), types.NamespacedName{Name: subName, Namespace: subNs}, curSub); err != nil {
klog.Warning("Failed to get appsub to update LastUpdateTime", err)
return
}
curSub.Status.Phase = phase
curSub.Status.Reason = reason
if err := clt.Status().Update(context.TODO(), curSub); err != nil {
klog.Warning("Failed to update LastUpdateTime", err)
}
}
// OverrideResourceBySubscription alter the given template with overrides
func OverrideResourceBySubscription(template *unstructured.Unstructured,
pkgName string, instance *appv1.Subscription) (*unstructured.Unstructured, error) {
ovs := prepareOverrides(pkgName, instance)
return OverrideTemplate(template, ovs)
}
func prepareOverrides(pkgName string, instance *appv1.Subscription) []appv1.ClusterOverride {
if instance == nil || instance.Spec.PackageOverrides == nil {
return nil
}
var overrides []appv1.ClusterOverride
// go over clsuters to find matching override
for _, ov := range instance.Spec.PackageOverrides {
if ov.PackageName != pkgName {
continue
}
for _, pov := range ov.PackageOverrides {
overrides = append(overrides, appv1.ClusterOverride(pov))
}
}
return overrides
}
// KeywordsChecker Checks if the helm chart has at least 1 keyword from the packageFilter.Keywords array
func KeywordsChecker(labelSelector *metav1.LabelSelector, ks []string) bool {
ls := make(map[string]string)
for _, k := range ks {
ls[k] = "true"
}
return LabelsChecker(labelSelector, ls)
}
// LabelsChecker checks labels against a labelSelector
func LabelsChecker(labelSelector *metav1.LabelSelector, ls map[string]string) bool {
clSelector, err := ConvertLabels(labelSelector)
if err != nil {
klog.Error("Failed to set label selector: ", labelSelector, " err:", err)
}
return clSelector.Matches(labels.Set(ls))
}
// GetReleaseName alters the given name in a deterministic way if the length exceed the maximum character
func GetReleaseName(base string) (string, error) {
if len(base) > maxNameLength {
h := sha1.New() // #nosec G401 Used only to generate random value to be used to generate hash string
_, err := h.Write([]byte(base))
if err != nil {
klog.Error("Failed to generate sha1 hash for: ", base, " error: ", err)
return "", err
}
sha1Hash := hex.EncodeToString(h.Sum(nil))
//minus 1 because adding "-"
base = base[:maxGeneratedNameLength]
return fmt.Sprintf("%s-%s", base, sha1Hash[:randomLength]), nil
}
return base, nil
}
// GetPauseLabel check if the subscription-pause label exists
func GetPauseLabel(instance *appv1.Subscription) bool {
labels := instance.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
if labels[appv1.LabelSubscriptionPause] != "" && strings.EqualFold(labels[appv1.LabelSubscriptionPause], "true") {
return true
}
return false
}
// AllowApplyTemplate check if the template is allowed to apply based on its hosting subscription pause label
// return false if the hosting subscription is paused.
func AllowApplyTemplate(localClient client.Client, template *unstructured.Unstructured) bool {
// if the template is subscription kind, allow its update
if strings.EqualFold(template.GetKind(), "Subscription") {
return true
}
//if the template is not subscription kind, check if its hosting subscription is paused.
sub := &appv1.Subscription{}
subkey := GetHostSubscriptionFromObject(template)
if subkey == nil {
klog.V(1).Infof("The template does not have hosting subscription. template: %v/%v, annoation: %#v",
template.GetNamespace(), template.GetName(), template.GetAnnotations())
return true
}
err := localClient.Get(context.TODO(), *subkey, sub)
if err != nil {
klog.V(1).Infof("Failed to get subscription object. sub: %v, error: %v", *subkey, err)
return true
}
if GetPauseLabel(sub) {
return false
}
return true
}
// IsResourceAllowed checks if the resource is on application subscription's allow list. The allow list is used only
// if the subscription is created by subscription-admin user.
func IsResourceAllowed(resource unstructured.Unstructured, allowlist map[string]map[string]string, isAdmin bool) bool {
// If subscription-admin, honor the allow list
if isAdmin {
// If allow list is empty, all resources are allowed for deploy
if len(allowlist) == 0 {
return true
}
return (allowlist[resource.GetAPIVersion()][resource.GetKind()] != "" ||
allowlist[resource.GetAPIVersion()]["*"] != "")
}
// If not subscription-admin, ignore the allow list and don't allow policy
return resource.GetAPIVersion() != "policy.open-cluster-management.io/v1"
}
// IsResourceDenied checks if the resource is on application subscription's deny list. The deny list is used only
// if the subscription is created by subscription-admin user.
func IsResourceDenied(resource unstructured.Unstructured, denyList map[string]map[string]string, isAdmin bool) bool {
// If subscription-admin, honor the deny list
if isAdmin {
// If deny list is empty, all resources are NOT denied
if len(denyList) == 0 {
return false
}
return (denyList[resource.GetAPIVersion()][resource.GetKind()] != "" ||
denyList[resource.GetAPIVersion()]["*"] != "")
}
// If not subscription-admin, ignore the deny list
return false
}
// GetAllowDenyLists returns subscription's allow and deny lists as maps. It returns empty map if there is no list.
func GetAllowDenyLists(subscription appv1.Subscription) (map[string]map[string]string, map[string]map[string]string) {
allowedGroupResources := make(map[string]map[string]string)
if subscription.Spec.Allow != nil {
for _, allowGroup := range subscription.Spec.Allow {
for _, resource := range allowGroup.Kinds {
klog.Info("allowing to deploy resource " + allowGroup.APIVersion + "/" + resource)
if allowedGroupResources[allowGroup.APIVersion] == nil {
allowedGroupResources[allowGroup.APIVersion] = make(map[string]string)
}
allowedGroupResources[allowGroup.APIVersion][resource] = resource
}
}
}
deniedGroupResources := make(map[string]map[string]string)
if subscription.Spec.Deny != nil {
for _, denyGroup := range subscription.Spec.Deny {
for _, resource := range denyGroup.Kinds {
klog.Info("denying to deploy resource " + denyGroup.APIVersion + "/" + resource)
if deniedGroupResources[denyGroup.APIVersion] == nil {
deniedGroupResources[denyGroup.APIVersion] = make(map[string]string)
}
deniedGroupResources[denyGroup.APIVersion][resource] = resource
}
}
}
return allowedGroupResources, deniedGroupResources
}
// DeleteSubscriptionCRD deletes the Subscription CRD
func DeleteSubscriptionCRD(runtimeClient client.Client, crdx *clientsetx.Clientset) {
sublist := &appv1.SubscriptionList{}
err := runtimeClient.List(context.TODO(), sublist, &client.ListOptions{})
if err != nil && !kerrors.IsNotFound(err) {
klog.Infof("subscription kind is gone. err: %s", err.Error())
os.Exit(0)
} else {
for _, sub := range sublist.Items {
annotations := sub.GetAnnotations()
if !strings.EqualFold(annotations[appv1.AnnotationHosting], "") {
klog.Infof("Found %s", sub.SelfLink)
// remove all finalizers
sub = *sub.DeepCopy()
sub.SetFinalizers([]string{})
err = runtimeClient.Update(context.TODO(), &sub) // #nosec G601 requires "k8s.io/apimachinery/pkg/runtime" object
if err != nil {
klog.Warning(err)
}
}
}
_, err := crdx.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), "multiclusterhubs.operator.open-cluster-management.io", metav1.GetOptions{})
if err != nil && kerrors.IsNotFound(err) {
klog.Info("This is not ACM hub cluster. Deleting subscription CRD.")
// now get rid of the crd.
err = crdx.ApiextensionsV1().CustomResourceDefinitions().Delete(context.TODO(), "subscriptions.apps.open-cluster-management.io", metav1.DeleteOptions{})
if err != nil {
klog.Infof("Deleting subscription CRD failed. err: %s", err.Error())
} else {
klog.Info("subscription CRD removed")
}
} else {
klog.Info("This is ACM hub cluster. Deleting propagated subscriptions only. Not deleting subscription CRD.")
for _, sub := range sublist.Items {
annotations := sub.GetAnnotations()
if !strings.EqualFold(annotations[appv1.AnnotationHosting], "") {
klog.Infof("Deleting %s", sub.SelfLink)
err = runtimeClient.Delete(context.TODO(), &sub) // #nosec G601 requires "k8s.io/apimachinery/pkg/runtime" object
if err != nil {
klog.Warning(err)
}
}
}
}
}
}
// RemoveSubAnnotations removes RHACM specific annotations from subscription
func RemoveSubAnnotations(obj *unstructured.Unstructured) *unstructured.Unstructured {
objanno := obj.GetAnnotations()
if objanno != nil {
delete(objanno, appv1.AnnotationClusterAdmin)
delete(objanno, appv1.AnnotationHosting)
delete(objanno, appv1.AnnotationSyncSource)
delete(objanno, appv1.AnnotationHostingDeployable)
delete(objanno, appv1.AnnotationChannelType)
}
if len(objanno) > 0 {
obj.SetAnnotations(objanno)
} else {
obj.SetAnnotations(nil)
}
return obj
}
// RemoveSubOwnerRef removes RHACM specific owner reference from subscription
func RemoveSubOwnerRef(obj *unstructured.Unstructured) *unstructured.Unstructured {
ownerRefs := obj.GetOwnerReferences()
newOwnerRefs := []metav1.OwnerReference{}
for _, ownerRef := range ownerRefs {
if !strings.EqualFold(ownerRef.Kind, "Subscription") {
newOwnerRefs = append(newOwnerRefs, ownerRef)
}
}
if len(newOwnerRefs) > 0 {
obj.SetOwnerReferences(newOwnerRefs)
} else {
obj.SetOwnerReferences(nil)
}
return obj
}
func IsSubscriptionBeDeleted(clt client.Client, subKey types.NamespacedName) bool {
subIns := &appv1.Subscription{}
if err := clt.Get(context.TODO(), subKey, subIns); err != nil {
return kerrors.IsNotFound(err)
}
return !subIns.GetDeletionTimestamp().IsZero()
}
// IsHub determines the hub cluster by listing multiclusterhubs resource items
func IsHub(config *rest.Config) bool {
var dl dynamic.ResourceInterface
multiclusterHubGVR := schema.GroupVersionResource{
Group: "operator.open-cluster-management.io",
Version: "v1",
Resource: "multiclusterhubs",
}
dynamicClient := dynamic.NewForConfigOrDie(config)
dl = dynamicClient.Resource(multiclusterHubGVR)
objlist, err := dl.List(context.TODO(), metav1.ListOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
klog.Infof("No multiclusterHub resource found, err: %v", err)
return false
}
klog.Infof("Listing multiclusterHub resource failed, exit... err: %v", err)
os.Exit(1)
}
if objlist == nil {
klog.Infof("obj list is nil, exit...")
os.Exit(1)
}
objCount := len(objlist.Items) //nolint
klog.Infof("multiclusterHub resource count: %v", objCount)
return objCount > 0
}
// GetReconcileRate determines reconcile rate based on channel annotations
func GetReconcileRate(chnAnnotations, subAnnotations map[string]string) string {
rate := "medium"
// If the channel does not have reconcile-level, default it to medium
if chnAnnotations[appv1.AnnotationResourceReconcileLevel] == "" {
klog.Info("Setting reconcile-level to default: medium")
rate = "medium"
} else {
if strings.EqualFold(chnAnnotations[appv1.AnnotationResourceReconcileLevel], "off") {
rate = "off"
} else if strings.EqualFold(chnAnnotations[appv1.AnnotationResourceReconcileLevel], "low") {
rate = "low"
} else if strings.EqualFold(chnAnnotations[appv1.AnnotationResourceReconcileLevel], "medium") {
rate = "medium"
} else if strings.EqualFold(chnAnnotations[appv1.AnnotationResourceReconcileLevel], "high") {
rate = "high"
} else {
klog.Info("Channel's reconcile-level has unknown value: ", chnAnnotations[appv1.AnnotationResourceReconcileLevel])
klog.Info("Setting it to medium")
rate = "medium"
}
}
// Reconcile level can be overridden to be
if strings.EqualFold(subAnnotations[appv1.AnnotationResourceReconcileLevel], "off") {
klog.Infof("Overriding channel's reconcile rate %s to turn it off", rate)
rate = "off"
}
return rate
}
// GetReconcileInterval determines reconcile loop interval based on reconcileRate setting