forked from IBM/ibm-common-service-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
917 lines (795 loc) · 26.4 KB
/
util.go
File metadata and controls
917 lines (795 loc) · 26.4 KB
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
//
// Copyright 2022 IBM Corporation
//
// 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 common
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"time"
utilyaml "github.com/ghodss/yaml"
olmv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/equality"
"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/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/runtime/serializer/streaming"
"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/apimachinery/pkg/types"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
"k8s.io/klog"
"sigs.k8s.io/controller-runtime/pkg/client"
apiv3 "github.com/IBM/ibm-common-service-operator/v4/api/v3"
"github.com/IBM/ibm-common-service-operator/v4/controllers/constant"
nssv1 "github.com/IBM/ibm-namespace-scope-operator/v4/api/v1"
odlm "github.com/IBM/operand-deployment-lifecycle-manager/v4/api/v1alpha1"
)
type CsMaps struct {
ControlNs string `json:"controlNamespace"`
NsMappingList []NsMapping `json:"namespaceMapping"`
// DefaultCsNs string `json:"defaultCsNs"`
}
type NsMapping struct {
RequestNs []string `json:"requested-from-namespace"`
CsNs string `json:"map-to-common-service-namespace"`
}
var (
ImageList = []string{"IBM_SECRETSHARE_OPERATOR_IMAGE", "IBM_CS_WEBHOOK_IMAGE"}
)
// CompareVersion takes vx.y.z, vx.y.z -> bool: if v1 is larger than v2
func CompareVersion(v1, v2 string) (v1IsLarger bool, err error) {
if v1 == "" {
v1 = "0.0.0"
}
v1Slice := strings.Split(v1, ".")
if len(v1Slice) == 1 {
v1 = "0.0." + v1
}
if v2 == "" {
v2 = "0.0.0"
}
v2Slice := strings.Split(v2, ".")
if len(v2Slice) == 1 {
v2 = "0.0." + v2
}
v1Slice = strings.Split(v1, ".")
v2Slice = strings.Split(v2, ".")
for index := range v1Slice {
v1SplitInt, e1 := strconv.Atoi(v1Slice[index])
if e1 != nil {
return false, e1
}
v2SplitInt, e2 := strconv.Atoi(v2Slice[index])
if e2 != nil {
return false, e2
}
if v1SplitInt > v2SplitInt {
return true, nil
} else if v1SplitInt == v2SplitInt {
continue
} else {
return false, nil
}
}
return false, nil
}
// YamlToObjects convert YAML content to unstructured objects
func YamlToObjects(yamlContent []byte) ([]*unstructured.Unstructured, error) {
var objects []*unstructured.Unstructured
// This step is for converting large yaml file, we can remove it after using "apimachinery" v0.19.0
if len(yamlContent) > 1024*64 {
object, err := YamlToObject(yamlContent)
if err != nil {
return nil, err
}
objects = append(objects, object)
return objects, nil
}
yamlDecoder := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
reader := json.YAMLFramer.NewFrameReader(io.NopCloser(bytes.NewReader(yamlContent)))
decoder := streaming.NewDecoder(reader, yamlDecoder)
for {
obj, _, err := decoder.Decode(nil, nil)
if err != nil {
if err == io.EOF {
break
}
klog.Infof("error convert object: %v", err)
continue
}
switch t := obj.(type) {
case *unstructured.Unstructured:
objects = append(objects, t)
default:
return nil, fmt.Errorf("failed to convert object %s", reflect.TypeOf(obj))
}
}
return objects, nil
}
// YamlToObject converting large yaml file, we can remove it after using "apimachinery" v0.19.0
func YamlToObject(yamlContent []byte) (*unstructured.Unstructured, error) {
obj := &unstructured.Unstructured{}
jsonSpec, err := utilyaml.YAMLToJSON(yamlContent)
if err != nil {
return nil, fmt.Errorf("could not convert yaml to json: %v", err)
}
if err := obj.UnmarshalJSON(jsonSpec); err != nil {
return nil, fmt.Errorf("could not unmarshal resource: %v", err)
}
return obj, nil
}
// NewUnstructured return Unstructured object
func NewUnstructured(group, kind, version string) *unstructured.Unstructured {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: group,
Kind: kind,
Version: version})
return u
}
// NewUnstructuredList return UnstructuredList object
func NewUnstructuredList(group, kind, version string) *unstructured.UnstructuredList {
ul := &unstructured.UnstructuredList{}
ul.SetGroupVersionKind(schema.GroupVersionKind{
Group: group,
Kind: kind,
Version: version})
return ul
}
func ObjectListToNewUnstructuredList(objs interface{}) (*unstructured.UnstructuredList, error) {
contents, err := runtime.DefaultUnstructuredConverter.ToUnstructured(objs)
if err != nil {
return nil, fmt.Errorf("could not convert Object to Unstructured resource: %v", err)
}
newUnstrList := &unstructured.UnstructuredList{}
newUnstrList.SetUnstructuredContent(contents)
return newUnstrList, nil
}
// GetOperatorName return the operator name
func GetOperatorName() (string, error) {
operatorName, found := os.LookupEnv(constant.OperatorNameEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", constant.OperatorNameEnvVar)
}
if len(operatorName) == 0 {
return "", fmt.Errorf("%s must not be empty", constant.OperatorNameEnvVar)
}
return operatorName, nil
}
// GetOperatorNamespace returns the namespace the operator should be running in.
func GetOperatorNamespace() (string, error) {
ns, found := os.LookupEnv(constant.OperatorNamespaceEnvVar)
if !found {
nsBytes, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("namespace not found for current environment")
}
return "", err
}
ns = strings.TrimSpace(string(nsBytes))
}
if len(ns) == 0 {
return "", fmt.Errorf("operator namespace is empty")
}
klog.V(2).Info("Found namespace: ", ns)
return ns, nil
}
// GetCPFSNamespace returns the namespace where foundational services operator should be running
func GetCPFSNamespace(r client.Reader) (cpfsNamespace string) {
cpfsNamespace, err := GetOperatorNamespace()
if err != nil {
return
}
defaultCsCR := &apiv3.CommonService{}
csName := "common-service"
if err := r.Get(context.TODO(), types.NamespacedName{Name: csName, Namespace: cpfsNamespace}, defaultCsCR); err != nil {
return
}
if string(defaultCsCR.Status.ConfigStatus.OperatorNamespace) != "" {
cpfsNamespace = string(defaultCsCR.Status.ConfigStatus.OperatorNamespace)
}
return
}
// GetServicesNamespace returns the namespace where foundational services CRs should be running
func GetServicesNamespace(r client.Reader) (servicesNamespace string) {
servicesNamespace, err := GetOperatorNamespace()
if err != nil {
return
}
defaultCsCR := &apiv3.CommonService{}
csName := "common-service"
if err := r.Get(context.TODO(), types.NamespacedName{Name: csName, Namespace: servicesNamespace}, defaultCsCR); err != nil {
return
}
if string(defaultCsCR.Spec.ServicesNamespace) != "" {
servicesNamespace = string(defaultCsCR.Spec.ServicesNamespace)
}
if string(defaultCsCR.Status.ConfigStatus.ServicesNamespace) != "" {
servicesNamespace = string(defaultCsCR.Status.ConfigStatus.ServicesNamespace)
}
return
}
// GetWatchNamespace returns the list of namespaces that the operator watches
func GetWatchNamespace() string {
ns, found := os.LookupEnv("WATCH_NAMESPACE")
if !found {
ns, err := GetOperatorNamespace()
if err != nil {
return ""
}
return ns
}
return ns
}
// GetNSSCMSynchronization returns whether NSS ConfigMap shchronization with OperatorGroup is enabled
func GetNSSCMSynchronization() bool {
isEnable, found := os.LookupEnv("NSSCM_SYNC_MODE")
if !found || isEnable == "true" {
return true
}
return false
}
// Contains returns whether the sub-string is contained
func Contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// Reverse resverses the string
func Reverse(original []string) []string {
reversed := make([]string, 0, len(original))
for i := len(original) - 1; i >= 0; i-- {
reversed = append(reversed, original[i])
}
return reversed
}
// Namespacelize adds the namespace specified
func Namespacelize(resource, placeholder, ns string) string {
return strings.ReplaceAll(resource, placeholder, ns)
}
func ReplaceImages(resource string) (result string) {
result = resource
for _, image := range ImageList {
result = strings.ReplaceAll(result, image, GetImage(image))
}
return
}
func GetImage(imageName string) string {
ns, _ := os.LookupEnv(imageName)
return ns
}
// GetCmOfMapCs gets ConfigMap of Common Services Maps
func GetCmOfMapCs(r client.Reader) (*corev1.ConfigMap, error) {
cmName := constant.CsMapConfigMap
cmNs := "kube-public"
csConfigmap := &corev1.ConfigMap{}
err := r.Get(context.TODO(), types.NamespacedName{Name: cmName, Namespace: cmNs}, csConfigmap)
if err != nil {
return nil, err
}
return csConfigmap, nil
}
// CheckStorageClass gets StorageClassList in current cluster, then validates whether StorageClass created
func CheckStorageClass(r client.Reader) error {
csStorageClass := &storagev1.StorageClassList{}
err := r.List(context.TODO(), csStorageClass)
if err != nil {
return fmt.Errorf("fail to list storageClass: %v", err)
}
size := len(csStorageClass.Items)
klog.Info("StorageClass Number: ", size)
if size <= 0 {
klog.Warning("StorageClass is not found, which might be required by CloudPak services, please refer to CloudPak's documentation for prerequisites.")
}
return nil
}
// UpdateNSList updates adopter namespaces of Common Services
func UpdateNSList(r client.Reader, c client.Client, cm *corev1.ConfigMap, nssKey, cpfsNamespace string, addControlNs bool) error {
nsScope := &nssv1.NamespaceScope{}
nsScopeKey := types.NamespacedName{Name: nssKey, Namespace: cpfsNamespace}
if err := r.Get(context.TODO(), nsScopeKey, nsScope); err != nil {
return err
}
var nsMems []string
nsSet := make(map[string]interface{})
for _, ns := range nsScope.Spec.NamespaceMembers {
nsSet[ns] = struct{}{}
}
commonServiceMaps, ok := cm.Data["common-service-maps.yaml"]
if !ok {
return fmt.Errorf("there is no common-service-maps.yaml in configmap kube-public/common-service-maps")
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
return fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", err)
}
if addControlNs {
if len(cmData.ControlNs) > 0 {
nsSet[cmData.ControlNs] = struct{}{}
}
}
for _, nsMapping := range cmData.NsMappingList {
if cpfsNamespace == nsMapping.CsNs {
for _, ns := range nsMapping.RequestNs {
nsSet[ns] = struct{}{}
}
}
}
for ns := range nsSet {
nsMems = append(nsMems, ns)
}
nsScope.Spec.NamespaceMembers = nsMems
if err := c.Update(context.TODO(), nsScope); err != nil {
return err
}
return nil
}
// UpdateAllNSList updates all adopter and CS namespaces into NSS CR
func UpdateAllNSList(r client.Reader, c client.Client, cm *corev1.ConfigMap, nssKey, nssNs string) error {
nsScope := &nssv1.NamespaceScope{}
nsScopeKey := types.NamespacedName{Name: nssKey, Namespace: nssNs}
if err := r.Get(context.TODO(), nsScopeKey, nsScope); err != nil {
return err
}
var nsMems []string
nsSet := make(map[string]interface{})
for _, ns := range nsScope.Spec.NamespaceMembers {
nsSet[ns] = struct{}{}
}
commonServiceMaps, ok := cm.Data["common-service-maps.yaml"]
if !ok {
return fmt.Errorf("there is no common-service-maps.yaml in configmap kube-public/common-service-maps")
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
return fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", err)
}
if len(cmData.ControlNs) > 0 {
nsSet[cmData.ControlNs] = struct{}{}
}
for _, nsMapping := range cmData.NsMappingList {
nsSet[nsMapping.CsNs] = struct{}{}
for _, ns := range nsMapping.RequestNs {
nsSet[ns] = struct{}{}
}
}
for ns := range nsSet {
nsMems = append(nsMems, ns)
}
nsScope.Spec.NamespaceMembers = nsMems
if err := c.Update(context.TODO(), nsScope); err != nil {
return err
}
return nil
}
// CheckSaas checks whether it is a SaaS deployment for Common Services
func CheckSaas(r client.Reader) (enable bool) {
cmName := constant.SaasConfigMap
cmNs := "kube-public"
saasConfigmap := &corev1.ConfigMap{}
err := r.Get(context.TODO(), types.NamespacedName{Name: cmName, Namespace: cmNs}, saasConfigmap)
if errors.IsNotFound(err) {
klog.V(2).Infof("There is no configmap %v/%v in the cluster: Running Common Service Operator in On-Prem mode", cmNs, cmName)
return false
} else if err != nil {
klog.Errorf("Failed to fetch configmap %v/%v: %v", cmNs, cmName, err)
return false
}
v, ok := saasConfigmap.Data["ibm_cloud_saas"]
if !ok {
klog.V(2).Infof("There is no ibm_cloud_saas in configmap %v/%v: Running Common Service Operator in On-Prem mode", cmNs, cmName)
return false
}
if v != "true" {
return false
}
klog.V(2).Infof("Running Common Service Operator in SaaS mode")
return true
}
// CheckMultiInstance checks whether it is a MultiInstances including SaaS and on-prem MultiInstances
func CheckMultiInstances(r client.Reader) (enable bool) {
return true
}
// GetControlNs gets control namespace of deploying cluster scope services
func GetControlNs(r client.Reader) (controlNs string) {
operatorNs, err := GetOperatorNamespace()
if err != nil {
klog.Errorf("Getting operator namespace failed: %v", err)
return
}
controlNs = operatorNs
return
}
// could have issue
func GetApprovalModeinNs(r client.Reader, ns string) (approvalMode string, err error) {
// set approval mode to empty in non-olm environment
if os.Getenv("NO_OLM") == "true" {
klog.V(2).Infof("set approval mode to empty in no olm environment")
return "", nil
}
approvalMode = string(olmv1alpha1.ApprovalAutomatic)
subList := &olmv1alpha1.SubscriptionList{}
if err := r.List(context.TODO(), subList, &client.ListOptions{Namespace: ns}); err != nil {
return approvalMode, err
}
for _, sub := range subList.Items {
if sub.Spec.InstallPlanApproval == olmv1alpha1.ApprovalManual {
approvalMode = string(olmv1alpha1.ApprovalManual)
return
}
}
return
}
// GetCatalogSource gets CatalogSource will be used by operators
func GetCatalogSource(packageName, ns string, r client.Reader) (CatalogSourceName, CatalogSourceNS string) {
if os.Getenv("NO_OLM") == "true" {
klog.V(2).Infof("set catalogsource name and namespace to empty in no olm environment")
return "", ""
}
subList := &olmv1alpha1.SubscriptionList{}
if err := r.List(context.TODO(), subList, &client.ListOptions{Namespace: ns}); err != nil {
klog.Info(err)
}
var subscriptions []olmv1alpha1.Subscription
for _, sub := range subList.Items {
if sub.Spec.Package == packageName {
subscriptions = append(subscriptions, sub)
}
}
if len(subscriptions) == 0 {
klog.Errorf("not found %v subscription in namespace: %v", packageName, ns)
return "", ""
}
if len(subscriptions) > 1 {
klog.Errorf("found more than one %v subscription in namespace: %v", packageName, ns)
return "", ""
}
return subscriptions[0].Spec.CatalogSource, subscriptions[0].Spec.CatalogSourceNamespace
}
// UpdateCsMaps will update namespaceMapping in common-service-maps
func UpdateCsMaps(cm *corev1.ConfigMap, requestNsList, servicesNS, operatorNs string) error {
commonServiceMaps, ok := cm.Data["common-service-maps.yaml"]
if !ok {
return fmt.Errorf("there is no common-service-maps.yaml in configmap kube-public/common-service-maps")
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
return fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", err)
}
var newNsMapping NsMapping
var newNsMappingList []NsMapping
// construct new mapping for current entry
newNsMapping.RequestNs = append(newNsMapping.RequestNs, strings.Split(requestNsList, ",")...)
newNsMapping.CsNs = servicesNS
newNsMappingList = append(newNsMappingList, newNsMapping)
// add well known control namespace for CP2 backward compatibility
if cmData.ControlNs == "" {
cmData.ControlNs = "cs-control"
}
for _, nsMapping := range cmData.NsMappingList {
var copiedNsMapping NsMapping
// exclude entire entry if its map-to-cs-namespace is in WATCH_NAMESPACE
if Contains(strings.Split(requestNsList, ","), nsMapping.CsNs) {
continue
}
copiedNsMapping.CsNs = nsMapping.CsNs
for _, ns := range nsMapping.RequestNs {
// exclude request namespace if it is in WATCH_NAMESPACE
if Contains(strings.Split(requestNsList, ","), ns) {
continue
}
copiedNsMapping.RequestNs = append(copiedNsMapping.RequestNs, ns)
}
// existing entry is valid and add it into new mapping list
if len(copiedNsMapping.CsNs) != 0 && len(copiedNsMapping.RequestNs) != 0 {
newNsMappingList = append(newNsMappingList, copiedNsMapping)
}
}
cmData.NsMappingList = newNsMappingList
commonServiceMap, error := utilyaml.Marshal(&cmData)
if error != nil {
return fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", error)
}
cm.Data["common-service-maps.yaml"] = string(commonServiceMap)
if !(cm.Labels != nil && cm.Labels[constant.CsManagedLabel] == "true") {
EnsureLabelsForConfigMap(cm, map[string]string{
constant.CsManagedLabel: "true",
})
}
return nil
}
// ValidateCsMaps checks common-service-maps has no scope overlapping
func ValidateCsMaps(cm *corev1.ConfigMap) error {
commonServiceMaps, ok := cm.Data["common-service-maps.yaml"]
if !ok {
return fmt.Errorf("there is no common-service-maps.yaml in configmap kube-public/common-service-maps")
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
return fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", err)
}
CsNsSet := make(map[string]interface{})
RequestNsSet := make(map[string]interface{})
for _, nsMapping := range cmData.NsMappingList {
// validate masterNamespace and controlNamespace
if cmData.ControlNs == nsMapping.CsNs {
return fmt.Errorf("invalid controlNamespace: %v. Cannot be the same as map-to-common-service-namespace", cmData.ControlNs)
}
if _, ok := CsNsSet[nsMapping.CsNs]; ok {
return fmt.Errorf("invalid map-to-common-service-namespace: %v", nsMapping.CsNs)
}
CsNsSet[nsMapping.CsNs] = struct{}{}
// validate CloudPak Namespace and controlNamespace
for _, ns := range nsMapping.RequestNs {
if cmData.ControlNs == ns {
return fmt.Errorf("invalid controlNamespace: %v. Cannot be the same as requested-from-namespace", cmData.ControlNs)
}
if _, ok := RequestNsSet[ns]; ok {
return fmt.Errorf("invalid requested-from-namespace: %v", ns)
}
RequestNsSet[ns] = struct{}{}
}
}
return nil
}
// GetCsScope fetchs the namespaces from its own requested-from-namespace and map-to-common-service-namespace
func GetCsScope(cm *corev1.ConfigMap, cpfsNamespace string) ([]string, error) {
var nsMems []string
nsSet := make(map[string]interface{})
commonServiceMaps, ok := cm.Data["common-service-maps.yaml"]
if !ok {
return nsMems, fmt.Errorf("there is no common-service-maps.yaml in configmap kube-public/common-service-maps")
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
return nsMems, fmt.Errorf("failed to fetch data of configmap common-service-maps: %v", err)
}
for _, nsMapping := range cmData.NsMappingList {
if cpfsNamespace == nsMapping.CsNs {
nsSet[cpfsNamespace] = struct{}{}
for _, ns := range nsMapping.RequestNs {
nsSet[ns] = struct{}{}
}
}
}
for ns := range nsSet {
nsMems = append(nsMems, ns)
}
return nsMems, nil
}
// EnsureLabelsForConfigMap ensures that the specifc ConfigMap has the certain labels
func EnsureLabelsForConfigMap(cm *corev1.ConfigMap, labels map[string]string) {
if cm.Labels == nil {
cm.Labels = make(map[string]string)
}
for k, v := range labels {
cm.Labels[k] = v
}
}
// EnsureLabels ensures that the specifc resource has the certain labels
func EnsureLabels(resource *unstructured.Unstructured, labels map[string]string) {
if resource.Object["metadata"].(map[string]interface{})["labels"] == nil {
resource.Object["metadata"].(map[string]interface{})["labels"] = make(map[string]string)
}
for k, v := range labels {
resource.Object["metadata"].(map[string]interface{})["labels"].(map[string]string)[k] = v
}
}
// GetRequestNs gets requested-from-namespace of map-to-common-service-namespace
func GetRequestNs(r client.Reader) (requestNs []string) {
operatorNs, err := GetOperatorNamespace()
if err != nil {
klog.Errorf("Getting operator namespace failed: %v", err)
return
}
csConfigmap, err := GetCmOfMapCs(r)
if err != nil {
klog.V(2).Infof("Could not find configmap kube-public/common-service-maps: %v", err)
return
}
commonServiceMaps, ok := csConfigmap.Data["common-service-maps.yaml"]
if !ok {
klog.Infof("There is no common-service-maps.yaml in configmap kube-public/common-service-maps")
return
}
var cmData CsMaps
if err := utilyaml.Unmarshal([]byte(commonServiceMaps), &cmData); err != nil {
klog.Errorf("Failed to fetch data of configmap common-service-maps: %v", err)
return
}
for _, nsMapping := range cmData.NsMappingList {
if operatorNs == nsMapping.CsNs {
requestNs = nsMapping.RequestNs
break
}
}
return
}
// GetNssCmNs gets namespaces from namespace-scope ConfigMap
func GetNssCmNs(r client.Reader, cpfsNamespace string) ([]string, error) {
nssConfigMap, err := GetCmOfNss(r, cpfsNamespace)
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
nssNsMems, ok := nssConfigMap.Data["namespaces"]
if !ok {
klog.Infof("There is no namespace in configmap %v/%v", cpfsNamespace, constant.NamespaceScopeConfigmapName)
return nil, nil
}
nssCmNs := strings.Split(nssNsMems, ",")
return nssCmNs, nil
}
// GetCmOfNss gets ConfigMap of Namespace-scope
func GetCmOfNss(r client.Reader, operatorNs string) (*corev1.ConfigMap, error) {
cmName := constant.NamespaceScopeConfigmapName
cmNs := operatorNs
nssConfigmap := &corev1.ConfigMap{}
if err := utilwait.PollImmediate(time.Second*5, time.Second*30, func() (done bool, err error) {
err = r.Get(context.TODO(), types.NamespacedName{Name: cmName, Namespace: cmNs}, nssConfigmap)
if err != nil {
if errors.IsNotFound(err) {
klog.Infof("waiting for configmap %v/%v", operatorNs, constant.NamespaceScopeConfigmapName)
}
return false, err
}
return true, nil
}); err != nil {
return nil, err
}
return nssConfigmap, nil
}
func GetResourcesDynamically(ctx context.Context, dynamic dynamic.Interface, group string, version string, resource string) (
[]unstructured.Unstructured, error) {
resourceID := schema.GroupVersionResource{
Group: group,
Version: version,
Resource: resource,
}
// Namespace is empty refer to all namespace
list, err := dynamic.Resource(resourceID).Namespace("").List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
return list.Items, nil
}
// GetEnableOpreqWebhook check if enable the webhook for the OperandRequest
func GetEnableOpreqWebhook() bool {
enable, found := os.LookupEnv("ENABLE_OPREQ_WEBHOOK")
if !found {
return true
}
if enable != "TRUE" {
return false
}
return true
}
// EnsureLabelsForConfigMap ensures that the specifc ConfigMap has the certain labels
func EnsureLabelsForCsCR(cs *apiv3.CommonService, labels map[string]string) {
if cs.Labels == nil {
cs.Labels = make(map[string]string)
}
for k, v := range labels {
cs.Labels[k] = v
}
}
func CompareObj(newObj *unstructured.Unstructured, existingObj *unstructured.Unstructured) (needUpdate bool) {
return !equality.Semantic.DeepEqual(newObj.GetLabels(), existingObj.GetLabels()) || !equality.Semantic.DeepEqual(newObj.GetAnnotations(), existingObj.GetAnnotations()) || !equality.Semantic.DeepEqual(newObj.Object["spec"], existingObj.Object["spec"])
}
// ReadFile reads file from local path
func ReadFile(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
klog.Error(err)
return nil, err
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
klog.Error(err)
return nil, err
}
fileSize := fileInfo.Size()
buffer := make([]byte, fileSize)
_, err = file.Read(buffer)
if err != nil {
klog.Error(err)
return nil, err
}
return buffer, nil
}
// EncodeBase64 encodes data to base64 string
func EncodeBase64(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}
// SanitizeData keep the key-value pair in the map if the value fulfill the valueType and requirement
func SanitizeData(data interface{}, valueType string, isEmpty bool) interface{} {
// check data type
switch data.(type) {
case map[string]interface{}:
sanitizedData := make(map[string]interface{})
for key, value := range data.(map[string]interface{}) {
switch valueType {
case "string":
if v, ok := value.(string); ok && (isEmpty || v != "") {
sanitizedData[key] = v
}
case "bool":
if v, ok := value.(bool); ok {
sanitizedData[key] = v
}
case "int":
if v, ok := value.(int); ok {
sanitizedData[key] = v
}
case "float64":
if v, ok := value.(float64); ok {
sanitizedData[key] = v
}
}
}
return sanitizedData
default:
klog.Errorf("data type is not map[string]interface{}")
return nil
}
}
func UpdateOpRegUserManaged(opreg *odlm.OperandRegistry, operatorName string, value bool) error {
packageName := GetPackageNameByServiceName(opreg, operatorName)
if packageName == "" {
return fmt.Errorf("failed to find package name while updating OperandRegistry with user managed field")
}
for i := range opreg.Spec.Operators {
i := i
if opreg.Spec.Operators[i].PackageName != packageName {
continue
}
opreg.Spec.Operators[i].UserManaged = value
}
return nil
}
func GetPackageNameByServiceName(opreg *odlm.OperandRegistry, operatorName string) string {
for _, v := range opreg.Spec.Operators {
v := v
if v.Name == operatorName {
return v.PackageName
}
}
return ""
}
func GetFirstNCharacter(str string, n int) string {
if n >= len(str) {
return str
}
return str[:n]
}