forked from openshift/compliance-operator
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathcommon.go
More file actions
3034 lines (2714 loc) · 98.8 KB
/
common.go
File metadata and controls
3034 lines (2714 loc) · 98.8 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
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
package framework
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
ocpapi "github.com/openshift/api"
configv1 "github.com/openshift/api/config/v1"
imagev1 "github.com/openshift/api/image/v1"
mcfgapi "github.com/openshift/api/machineconfiguration"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
batchv1 "k8s.io/api/batch/v1"
core "k8s.io/api/core/v1"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/rbac/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
clusterv1alpha1 "open-cluster-management.io/api/cluster/v1alpha1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
psapi "k8s.io/pod-security-admission/api"
"sigs.k8s.io/controller-runtime/pkg/client"
dynclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/ComplianceAsCode/compliance-operator/pkg/apis"
compv1alpha1 "github.com/ComplianceAsCode/compliance-operator/pkg/apis/compliance/v1alpha1"
compscanctrl "github.com/ComplianceAsCode/compliance-operator/pkg/controller/compliancescan"
compsuitectrl "github.com/ComplianceAsCode/compliance-operator/pkg/controller/compliancesuite"
"github.com/ComplianceAsCode/compliance-operator/pkg/utils"
)
var defaultBackoff = backoff.WithMaxRetries(backoff.NewExponentialBackOff(), maxRetries)
// readFile accepts a file path and returns the file contents.
func (f *Framework) readFile(p *string) ([]byte, error) {
y, err := os.ReadFile(*p)
if err != nil {
log.Printf("unable to read contents of %s: %s", *p, err)
return nil, err
}
return y, nil
}
type ObjectResouceVersioner interface {
dynclient.Object
metav1.Common
}
// readYAML accepts a byte string that is YAML-like and attempts to read
// it into a slice of byte strings where each element in the slice is a
// separate YAML document delimited by "---". This is useful for working
// with files that contain multiple YAML documents.
func (f *Framework) readYAML(y []byte) ([][]byte, error) {
o := make([][]byte, 0)
s := NewYAMLScanner(bytes.NewBuffer(y))
for s.Scan() {
// Grab the current YAML document
d := s.Bytes()
// Convert to JSON and attempt to decode it
obj := &unstructured.Unstructured{}
j, err := yaml.YAMLToJSON(d)
if err != nil {
return nil, fmt.Errorf("could not convert yaml document to json: %w", err)
}
if err := obj.UnmarshalJSON(j); err != nil {
return nil, fmt.Errorf("failed to decode object spec: %w", err)
}
o = append(o, j)
}
return o, nil
}
func unmarshalJSON(j []byte) (dynclient.Object, error) {
obj := &unstructured.Unstructured{}
if err := obj.UnmarshalJSON(j); err != nil {
return nil, fmt.Errorf("failed to unmarshal object spec: %w", err)
}
return obj, nil
}
func (f *Framework) cleanUpFromYAMLFile(p *string) error {
c, err := f.readFile(p)
if err != nil {
return err
}
documents, err := f.readYAML(c)
if err != nil {
return err
}
for _, d := range documents {
obj, err := unmarshalJSON(d)
if err != nil {
return err
}
obj.SetNamespace(f.OperatorNamespace)
log.Printf("deleting %s %s", obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
if err := f.Client.Delete(context.TODO(), obj); err != nil {
return fmt.Errorf("failed to delete %s: %w", obj.GetObjectKind().GroupVersionKind().Kind, err)
}
}
return nil
}
func (f *Framework) PrintROSADebugInfo(t *testing.T) {
// List cluster claims
clusterClaimList := clusterv1alpha1.ClusterClaimList{}
err := f.Client.List(context.TODO(), &clusterClaimList)
if err != nil {
t.Fatalf("Failed to list cluster claims: %v", err)
}
for _, clusterClaim := range clusterClaimList.Items {
t.Logf("ClusterClaim: %s", clusterClaim.Name)
t.Logf("ClusterClaim.Spec.Value: %v", clusterClaim.Spec.Value)
}
// List infrastructures
infraList := configv1.InfrastructureList{}
err = f.Client.List(context.TODO(), &infraList)
if err != nil {
t.Fatalf("Failed to list infrastructures: %v", err)
}
for _, infra := range infraList.Items {
t.Logf("Infrastructure: %s", infra.Name)
t.Logf("Infrastructure.Status.ControlPlaneTopology: %v", infra.Status.ControlPlaneTopology)
}
// print out logs for compliance-operator deployment
podList := corev1.PodList{}
err = f.Client.List(context.TODO(), &podList, client.InNamespace(f.OperatorNamespace))
if err != nil {
t.Fatalf("Failed to list pods: %v", err)
}
for _, pod := range podList.Items {
// find pod named contains compliance-operator substring
if strings.Contains(pod.Name, "compliance-operator") {
log.Printf("Pod: %s", pod.Name)
log.Printf("Pod.Status: %v", pod.Status)
// print out logs for compliance-operator pod
req := f.KubeClient.CoreV1().Pods(f.OperatorNamespace).GetLogs(pod.Name, &corev1.PodLogOptions{})
log.Printf("Request: %v", req)
reader, err := req.Stream(context.Background())
if err != nil {
t.Fatalf("Failed to get logs: %v", err)
}
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if err != nil {
break
}
log.Printf("Logs: %s", string(buf[:n]))
}
}
}
}
func (f *Framework) CreateProfileBundle(pbName string, baselineImage string, contentFile string) (*compv1alpha1.ProfileBundle, error) {
origPb := &compv1alpha1.ProfileBundle{
ObjectMeta: metav1.ObjectMeta{
Name: pbName,
Namespace: f.OperatorNamespace,
},
Spec: compv1alpha1.ProfileBundleSpec{
ContentImage: baselineImage,
ContentFile: contentFile,
},
}
// Pass nil in as the cleanupOptions since so we don't invoke all the
// cleanup function code in Create. Use defer to cleanup the
// ProfileBundle at the end of the test, instead of at the end of the
// suite.
log.Printf("Creating ProfileBundle %s", pbName)
if err := f.Client.Create(context.TODO(), origPb, nil); err != nil {
return nil, err
}
return origPb, nil
}
func (f *Framework) cleanUpProfileBundle(p string) error {
pb := &compv1alpha1.ProfileBundle{
ObjectMeta: metav1.ObjectMeta{
Name: p,
Namespace: f.OperatorNamespace,
},
}
err := f.Client.Delete(context.TODO(), pb)
if err != nil {
return fmt.Errorf("failed to delete ProfileBundle%s: %w", p, err)
}
return nil
}
func (f *Framework) createFromYAMLFile(p *string) error {
c, err := f.readFile(p)
if err != nil {
return err
}
return f.createFromYAMLString(string(c))
}
func (f *Framework) createFromYAMLString(y string) error {
c := []byte(y)
documents, err := f.readYAML(c)
if err != nil {
return err
}
for _, d := range documents {
obj, err := unmarshalJSON(d)
if err != nil {
return err
}
obj.SetNamespace(f.OperatorNamespace)
log.Printf("creating %s %s", obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())
err = f.Client.CreateWithoutCleanup(context.TODO(), obj)
if err != nil {
return err
}
}
return nil
}
func (f *Framework) waitForScanCleanup() error {
timeouterr := wait.Poll(time.Second*5, time.Minute*2, func() (bool, error) {
var scans compv1alpha1.ComplianceScanList
f.Client.List(context.TODO(), &scans, &dynclient.ListOptions{})
if len(scans.Items) == 0 {
return true, nil
}
log.Printf("%d scans not cleaned up\n", len(scans.Items))
for _, i := range scans.Items {
log.Printf("scan %s still exists in namespace %s", i.Name, i.Namespace)
}
return false, nil
})
if timeouterr != nil {
return fmt.Errorf("timed out waiting for scans to cleanup: %w", timeouterr)
}
return nil
}
func (f *Framework) addFrameworks() error {
// compliance-operator objects
coObjs := [3]dynclient.ObjectList{&compv1alpha1.ComplianceScanList{},
&compv1alpha1.ComplianceRemediationList{},
&compv1alpha1.ComplianceSuiteList{},
}
for _, obj := range coObjs {
err := AddToFrameworkScheme(apis.AddToScheme, obj)
if err != nil {
return fmt.Errorf("failed to add custom resource scheme to framework: %v", err)
}
}
// Additional testing objects
testObjs := [1]dynclient.ObjectList{
&configv1.OAuthList{},
}
for _, obj := range testObjs {
err := AddToFrameworkScheme(configv1.Install, obj)
if err != nil {
return fmt.Errorf("failed to add configv1 resource scheme to framework: %v", err)
}
}
// MCO objects
if f.Platform != "rosa" {
mcoObjs := [2]dynclient.ObjectList{
&mcfgv1.MachineConfigPoolList{},
&mcfgv1.MachineConfigList{},
}
for _, obj := range mcoObjs {
err := AddToFrameworkScheme(mcfgapi.Install, obj)
if err != nil {
return fmt.Errorf("failed to add custom resource scheme to framework: %v", err)
}
}
}
// ClusterClaim objects
if f.Platform == "rosa" {
ccObjs := [1]dynclient.ObjectList{
&clusterv1alpha1.ClusterClaimList{},
}
for _, obj := range ccObjs {
err := AddToFrameworkScheme(clusterv1alpha1.Install, obj)
if err != nil {
return fmt.Errorf("failed to add custom resource scheme to framework: %v", err)
}
}
}
// OpenShift objects
ocpObjs := [2]dynclient.ObjectList{
&imagev1.ImageStreamList{},
&imagev1.ImageStreamTagList{},
}
for _, obj := range ocpObjs {
if err := AddToFrameworkScheme(ocpapi.Install, obj); err != nil {
return fmt.Errorf("failed to add custom resource scheme to framework: %v", err)
}
}
//Schedule objects
scObjs := [1]dynclient.ObjectList{
&schedulingv1.PriorityClassList{},
}
for _, obj := range scObjs {
if err := AddToFrameworkScheme(schedulingv1.AddToScheme, obj); err != nil {
return fmt.Errorf("TEST SETUP: failed to add custom resource scheme to framework: %v", err)
}
}
// ValidatingAdmissionPolicy objects
vapObjs := [1]dynclient.ObjectList{
&admissionregistrationv1.ValidatingAdmissionPolicyList{},
}
for _, obj := range vapObjs {
if err := AddToFrameworkScheme(admissionregistrationv1.AddToScheme, obj); err != nil {
return fmt.Errorf("failed to add admissionregistration resource scheme to framework: %v", err)
}
}
return nil
}
func (f *Framework) initializeMetricsTestResources() error {
if _, err := f.KubeClient.RbacV1().ClusterRoles().Create(context.TODO(), &v1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "co-metrics-client",
},
Rules: []v1.PolicyRule{
{
NonResourceURLs: []string{
"/metrics-co",
},
Verbs: []string{
"get",
},
},
},
}, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
if _, err := f.KubeClient.RbacV1().ClusterRoleBindings().Create(context.TODO(), &v1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "co-metrics-client",
},
Subjects: []v1.Subject{
{
Kind: "ServiceAccount",
Name: "default",
Namespace: f.OperatorNamespace,
},
},
RoleRef: v1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "co-metrics-client",
},
}, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
if _, err := f.KubeClient.CoreV1().Secrets(f.OperatorNamespace).Create(context.TODO(), &core.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "metrics-token",
Namespace: f.OperatorNamespace,
Annotations: map[string]string{
"kubernetes.io/service-account.name": "default",
},
},
Type: "kubernetes.io/service-account-token",
}, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
return nil
}
func (f *Framework) replaceNamespaceFromManifest() error {
log.Printf("updating manifest %s with namespace %s\n", *f.NamespacedManPath, f.OperatorNamespace)
if f.NamespacedManPath == nil {
return fmt.Errorf("no namespaced manifest given as test argument (operator-sdk might have changed)")
}
c, err := f.readFile(f.NamespacedManPath)
if err != nil {
return err
}
newContents := strings.Replace(string(c), "openshift-compliance", f.OperatorNamespace, -1)
// #nosec
err = os.WriteFile(*f.NamespacedManPath, []byte(newContents), 0644)
if err != nil {
return fmt.Errorf("error writing namespaced manifest file: %s", err)
}
return nil
}
func (f *Framework) WaitForDeployment(name string, replicas int, retryInterval, timeout time.Duration) error {
err := wait.Poll(retryInterval, timeout, func() (done bool, err error) {
deployment, err := f.KubeClient.AppsV1().Deployments(f.OperatorNamespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
log.Printf("Waiting for availability of Deployment: %s in Namespace: %s \n", name, f.OperatorNamespace)
return false, nil
}
return false, err
}
if int(deployment.Status.AvailableReplicas) >= replicas {
return true, nil
}
log.Printf("Waiting for full availability of %s deployment (%d/%d)\n", name,
deployment.Status.AvailableReplicas, replicas)
return false, nil
})
if err != nil {
return err
}
log.Printf("Deployment available (%d/%d)\n", replicas, replicas)
return nil
}
func (f *Framework) ensureTestNamespaceExists() error {
// create namespace only if it doesn't already exist
_, err := f.KubeClient.CoreV1().Namespaces().Get(context.TODO(), f.OperatorNamespace, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
ns := &core.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: f.OperatorNamespace,
Labels: map[string]string{
psapi.EnforceLevelLabel: string(psapi.LevelPrivileged),
"security.openshift.io/scc.podSecurityLabelSync": "false",
"openshift.io/cluster-monitoring": "true",
},
},
}
log.Printf("creating namespace %s", f.OperatorNamespace)
_, err = f.KubeClient.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
return fmt.Errorf("namespace %s already exists: %w", f.OperatorNamespace, err)
} else if err != nil {
return err
}
return nil
} else if apierrors.IsAlreadyExists(err) {
log.Printf("using existing namespace %s", f.OperatorNamespace)
return nil
} else {
return nil
}
}
func (f *Framework) WaitForProfileDeprecatedWarning(t *testing.T, scanName string, profileName string) error {
polledScan := &compv1alpha1.ComplianceScan{}
// Wait for profile deprecation warning event
err := wait.Poll(RetryInterval, Timeout, func() (bool, error) {
getErr := f.Client.Get(context.TODO(), types.NamespacedName{Name: scanName, Namespace: f.OperatorNamespace}, polledScan)
if getErr != nil {
t.Log(getErr)
return false, nil
}
profileEventList, getEventErr := f.KubeClient.CoreV1().Events(f.OperatorNamespace).List(context.TODO(), metav1.ListOptions{
FieldSelector: "reason=DeprecatedProfile",
})
if getEventErr != nil {
t.Log(getEventErr)
return false, nil
}
tailoredProfileEventList, getEventErr := f.KubeClient.CoreV1().Events(f.OperatorNamespace).List(context.TODO(), metav1.ListOptions{
FieldSelector: "reason=DeprecatedTailoredProfile",
})
if getEventErr != nil {
t.Log(getEventErr)
return false, nil
}
re := regexp.MustCompile(fmt.Sprintf(".*%s.*", profileName))
for _, item := range profileEventList.Items {
if item.InvolvedObject.Name == polledScan.Name && re.MatchString(item.Message) {
t.Logf("Found ComplianceScan deprecated profile event: %s", item.Message)
return true, nil
}
}
for _, item := range tailoredProfileEventList.Items {
if item.InvolvedObject.Name == polledScan.Name && re.MatchString(item.Message) {
t.Logf("Found ComplianceScan deprecated profile event: %s", item.Message)
return true, nil
}
}
return false, nil
})
if err != nil {
t.Fatalf("No ComplianceScan event for profile \"%s\" found", profileName)
return err
}
return nil
}
func (f *Framework) WaitForDuplicatedVariableWarning(t *testing.T, tpName string, variableName string) error {
polledTailoredProfile := &compv1alpha1.TailoredProfile{}
// Wait for profile deprecation warning event
err := wait.Poll(RetryInterval, Timeout, func() (bool, error) {
getErr := f.Client.Get(context.TODO(), types.NamespacedName{Name: tpName, Namespace: f.OperatorNamespace}, polledTailoredProfile)
if getErr != nil {
t.Log(getErr)
return false, nil
}
duplicateValuesEventList, getEventErr := f.KubeClient.CoreV1().Events(f.OperatorNamespace).List(context.TODO(), metav1.ListOptions{
FieldSelector: "reason=DuplicatedSetValue",
})
if getEventErr != nil {
t.Log(getEventErr)
return false, nil
}
re := regexp.MustCompile(fmt.Sprintf(".*%s.*", variableName))
for _, item := range duplicateValuesEventList.Items {
if item.InvolvedObject.Name == polledTailoredProfile.Name && re.MatchString(item.Message) {
t.Logf("Found TailoredProfile duplicated variable event: %s", item.Message)
return true, nil
}
}
return false, nil
})
if err != nil {
t.Fatalf("No TailoredProfile event for variable \"%s\" found", variableName)
return err
}
return nil
}
// waitForProfileBundleStatus will poll until the compliancescan that we're
// lookingfor reaches a certain status, or until a timeout is reached.
func (f *Framework) WaitForProfileBundleStatus(name string, status compv1alpha1.DataStreamStatusType) error {
pb := &compv1alpha1.ProfileBundle{}
var lastErr error
// retry and ignore errors until timeout
timeouterr := wait.Poll(RetryInterval, Timeout, func() (bool, error) {
lastErr = f.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: f.OperatorNamespace}, pb)
if lastErr != nil {
if apierrors.IsNotFound(lastErr) {
log.Printf("waiting for availability of %s ProfileBundle\n", name)
return false, nil
}
log.Printf("retrying due to error: %s\n", lastErr)
return false, nil
}
if pb.Status.DataStreamStatus == status {
return true, nil
}
log.Printf("waiting ProfileBundle %s to become %s (%s)\n", name, status, pb.Status.DataStreamStatus)
return false, nil
})
if timeouterr != nil {
return fmt.Errorf("ProfileBundle %s failed to reach state %s", name, status)
}
log.Printf("ProfileBundle ready (%s)\n", pb.Status.DataStreamStatus)
return nil
}
func (f *Framework) GetReadyProfileBundle(name, namespace string) (*compv1alpha1.ProfileBundle, error) {
if err := f.WaitForProfileBundleStatus(name, compv1alpha1.DataStreamValid); err != nil {
return nil, err
}
pb := &compv1alpha1.ProfileBundle{}
if err := f.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, pb); err != nil {
return nil, err
}
return pb, nil
}
func (f *Framework) updateScanSettingsForDebug() error {
if f.Platform == "rosa" {
fmt.Printf("bypassing ScanSettings test setup because it's not supported on %s\n", f.Platform)
return nil
}
for _, ssName := range []string{"default", "default-auto-apply"} {
ss := &compv1alpha1.ScanSetting{}
sskey := types.NamespacedName{Name: ssName, Namespace: f.OperatorNamespace}
if err := f.Client.Get(context.TODO(), sskey, ss); err != nil {
return err
}
ssCopy := ss.DeepCopy()
ssCopy.Debug = true
if err := f.Client.Update(context.TODO(), ssCopy); err != nil {
return err
}
}
return nil
}
func (f *Framework) ensureE2EScanSettings() error {
if f.Platform == "rosa" {
fmt.Printf("bypassing ScanSettings test setup because it's not supported on %s\n", f.Platform)
return nil
}
for _, ssName := range []string{"default", "default-auto-apply"} {
ss := &compv1alpha1.ScanSetting{}
sskey := types.NamespacedName{Name: ssName, Namespace: f.OperatorNamespace}
if err := f.Client.Get(context.TODO(), sskey, ss); err != nil {
return err
}
ssCopy := ss.DeepCopy()
ssCopy.ObjectMeta = metav1.ObjectMeta{
Name: "e2e-" + ssName,
Namespace: f.OperatorNamespace,
}
ssCopy.Roles = []string{
TestPoolName,
}
ssCopy.Debug = true
if err := f.Client.Create(context.TODO(), ssCopy, nil); err != nil {
return err
}
}
return nil
}
func (f *Framework) deleteScanSettings(name string) error {
if f.Platform == "rosa" {
fmt.Printf("bypassing ScanSettings test setup because it's not supported on %s\n", f.Platform)
return nil
}
ss := &compv1alpha1.ScanSetting{}
sskey := types.NamespacedName{Name: name, Namespace: f.OperatorNamespace}
if err := f.Client.Get(context.TODO(), sskey, ss); err != nil {
return err
}
err := f.Client.Delete(context.TODO(), ss)
if err != nil {
return fmt.Errorf("failed to cleanup scan setting %s: %w", name, err)
}
return nil
}
func (f *Framework) createMachineConfigPool(n string) error {
if f.Platform == "rosa" {
fmt.Printf("bypassing MachineConfigPool test setup because it's not supported on %s\n", f.Platform)
return nil
}
// get the worker pool
w := "worker"
p := &mcfgv1.MachineConfigPool{}
getErr := backoff.RetryNotify(
func() error {
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: w}, p)
if apierrors.IsNotFound(err) {
// Can't recover from this
log.Printf("Could not find the %s Machine Config Pool to modify: %s", w, err)
}
// might be a transcient error
return err
},
defaultBackoff,
func(err error, interval time.Duration) {
log.Printf("error while getting MachineConfig pool to create sub-pool from: %s. Retrying after %s", err, interval)
})
if getErr != nil {
return fmt.Errorf("failed to get Machine Config Pool %s to create sub-pool from: %w", w, getErr)
}
nodeList, err := f.getNodesForPool(p)
if err != nil {
return err
}
// pick the first node in the list so we only have a pool of one
node := nodeList.Items[0]
// create a new pool with a subset of the nodes
l := fmt.Sprintf("node-role.kubernetes.io/%s", n)
// label nodes
nodeCopy := node.DeepCopy()
nodeCopy.Labels[l] = ""
log.Printf("adding label %s to node %s\n", l, node.Name)
updateErr := backoff.RetryNotify(
func() error {
return f.Client.Update(context.TODO(), nodeCopy)
},
defaultBackoff,
func(err error, interval time.Duration) {
log.Printf("failed to label node %s: %s... retrying after %s", node.Name, err, interval)
})
if updateErr != nil {
log.Printf("failed to label node %s: %s\n", node.Name, l)
return fmt.Errorf("couldn't label node %s: %w", node.Name, updateErr)
}
nodeLabel := make(map[string]string)
nodeLabel[l] = ""
poolLabels := make(map[string]string)
poolLabels["pools.operator.machineconfiguration.openshift.io/e2e"] = ""
newPool := &mcfgv1.MachineConfigPool{
ObjectMeta: metav1.ObjectMeta{Name: n, Labels: poolLabels},
Spec: mcfgv1.MachineConfigPoolSpec{
NodeSelector: &metav1.LabelSelector{
MatchLabels: nodeLabel,
},
MachineConfigSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: mcfgv1.MachineConfigRoleLabelKey,
Operator: metav1.LabelSelectorOpIn,
Values: []string{w, n},
},
},
},
},
}
// We create but don't clean up, we'll call a function for this since we need to
// re-label hosts first.
createErr := backoff.RetryNotify(
func() error {
err := f.Client.Create(context.TODO(), newPool, nil)
if apierrors.IsAlreadyExists(err) {
return nil
}
return err
},
defaultBackoff,
func(err error, interval time.Duration) {
log.Printf("failed to create Machine Config Pool %s: %s... retrying after %s", n, err, interval)
})
if createErr != nil {
return fmt.Errorf("failed to create Machine Config Pool %s: %w", n, createErr)
}
// wait for pool to come up
err = wait.PollImmediate(machineOperationRetryInterval, machineOperationTimeout, func() (bool, error) {
pool := mcfgv1.MachineConfigPool{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: n}, &pool)
if err != nil {
log.Printf("failed to find Machine Config Pool %s\n", n)
return false, err
}
for _, c := range pool.Status.Conditions {
if c.Type == mcfgv1.MachineConfigPoolUpdated {
if c.Status == core.ConditionTrue {
return true, nil
}
}
}
log.Printf("%s Machine Config Pool has not updated... retrying\n", n)
return false, nil
})
if err != nil {
return fmt.Errorf("failed waiting for Machine Config Pool %s to become available: %w", n, err)
}
log.Printf("successfully created Machine Config Pool %s\n", n)
return nil
}
// validatingAdmissionPolicyExists checks if a ValidatingAdmissionPolicy with the given name exists
func (f *Framework) validatingAdmissionPolicyExists(name string) (bool, error) {
vap := &admissionregistrationv1.ValidatingAdmissionPolicy{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: name}, vap)
if err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func (f *Framework) createInvalidMachineConfigPool(n string) error {
if f.Platform == "rosa" {
fmt.Printf("bypassing MachineConfigPool test setup because it's not supported on %s\n", f.Platform)
return nil
}
// Check if ValidatingAdmissionPolicy exists
vapExists, err := f.validatingAdmissionPolicyExists("custom-machine-config-pool-selector")
if err != nil {
return fmt.Errorf("failed to check ValidatingAdmissionPolicy: %w", err)
}
p := &mcfgv1.MachineConfigPool{
ObjectMeta: metav1.ObjectMeta{Name: n},
Spec: mcfgv1.MachineConfigPoolSpec{
Paused: false,
},
}
// Only add selectors if ValidatingAdmissionPolicy exists
// This ensures backward compatibility with older clusters
if vapExists {
log.Printf("ValidatingAdmissionPolicy 'custom-machine-config-pool-selector' exists, adding minimal selectors to MachineConfigPool %s\n", n)
// Add minimal selectors to pass ValidatingAdmissionPolicy
// This pool is still "invalid" for testing as no nodes match this selector
p.Spec.NodeSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{
"node-role.kubernetes.io/e2e-invalid": "",
},
}
p.Spec.MachineConfigSelector = &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: "machineconfiguration.openshift.io/role",
Operator: metav1.LabelSelectorOpIn,
Values: []string{"worker"},
},
},
}
} else {
log.Printf("ValidatingAdmissionPolicy 'custom-machine-config-pool-selector' not found, creating MachineConfigPool %s without selectors (legacy mode)\n", n)
}
createErr := backoff.RetryNotify(
func() error {
err := f.Client.Create(context.TODO(), p, nil)
if apierrors.IsAlreadyExists(err) {
log.Printf("Machine Config Pool %s already exists", n)
return nil
}
return err
},
defaultBackoff,
func(err error, interval time.Duration) {
log.Printf("error creating Machine Config Pool %s: %s... retrying after %s", n, err, interval)
})
if createErr != nil {
return fmt.Errorf("failed to create Machine Config Pool %s: %w", n, createErr)
}
return nil
}
func (f *Framework) cleanUpMachineConfigPool(n string) error {
if f.Platform == "rosa" {
fmt.Printf("bypassing MachineConfigPool cleanup because it's not supported on %s\n", f.Platform)
return nil
}
p := &mcfgv1.MachineConfigPool{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: n}, p)
if err != nil {
return fmt.Errorf("failed to get Machine Config Pool %s for cleanup: %w", n, err)
}
log.Printf("cleaning up Machine Config Pool %s", n)
err = f.Client.Delete(context.TODO(), p)
if err != nil {
return fmt.Errorf("failed to cleanup Machine Config Pool %s: %w", n, err)
}
return nil
}
func (f *Framework) restoreNodeLabelsForPool(n string) error {
if f.Platform == "rosa" {
fmt.Printf("bypassing node label restoration because MachineConfigPools are not supported on %s\n", f.Platform)
return nil
}
p := &mcfgv1.MachineConfigPool{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: n}, p)
if err != nil {
return fmt.Errorf("failed to get Machine Config Pool %s for cleanup: %w", n, err)
}
nodeList, err := f.getNodesForPool(p)
nodes := nodeList.Items
if err != nil {
return fmt.Errorf("failed to find nodes while cleaning up Machine Config Pool %s: %w", n, err)
}
rmPoolLabel := utils.GetFirstNodeRoleLabel(p.Spec.NodeSelector.MatchLabels)
err = f.removeLabelFromNode(rmPoolLabel, nodes)
if err != nil {
return err
}
// Unlabeling the nodes triggers an update of the affected nodes because the nodes
// will then start using a different rendered pool. e.g a node that used to be labeled
// with "e2e,worker" and becomes labeled with "worker" switches from "rendered-e2e-*"
// to "rendered-worker-*". If we didn't wait, the node might have tried to use the
// e2e pool that would be gone when we remove it with the next call
err = f.waitForNodesToHaveARenderedPool(nodes, n)
if err != nil {
return fmt.Errorf("failed removing nodes from Machine Config Pool %s: %w", n, err)
}
err = wait.PollImmediate(machineOperationRetryInterval, machineOperationTimeout, func() (bool, error) {
pool := mcfgv1.MachineConfigPool{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: n}, &pool)
if err != nil {
return false, fmt.Errorf("failed to get Machine Config Pool %s: %w", n, err)
}
for _, c := range pool.Status.Conditions {
if c.Type == mcfgv1.MachineConfigPoolUpdated && c.Status == core.ConditionTrue {
return true, nil
}
}
log.Printf("the Machine Config Pool %s has not updated yet\n", n)
return false, nil
})
if err != nil {
return fmt.Errorf("failed waiting for nodes to reboot after being unlabeled: %w", err)
}
return nil
}
func (f *Framework) getNodesForPool(p *mcfgv1.MachineConfigPool) (core.NodeList, error) {
var nodeList core.NodeList
opts := &dynclient.ListOptions{
LabelSelector: labels.SelectorFromSet(p.Spec.NodeSelector.MatchLabels),
}
listErr := backoff.Retry(
func() error {
return f.Client.List(context.TODO(), &nodeList, opts)
},
defaultBackoff)
if listErr != nil {
return nodeList, fmt.Errorf("couldn't list nodes with selector %s: %w", p.Spec.NodeSelector.MatchLabels, listErr)
}
return nodeList, nil
}
func (f *Framework) removeLabelFromNode(l string, nodes []core.Node) error {
for _, n := range nodes {
c := n.DeepCopy()
delete(c.Labels, l)
fmt.Printf("removing label %s from node %s\n", l, c.Name)
err := f.Client.Update(context.TODO(), c)
if err != nil {
return fmt.Errorf("failed to remove label %s from node %s: %s", l, c.Name, err)
}
}
return nil
}
// waitForNodesToHaveARenderedPool waits until all nodes passed through a
// parameter transition to a rendered configuration from a pool. A typical
// use-case is when a node is unlabeled from a pool and must wait until Machine
// Config Operator makes the node use the other available pool. Only then it is
// safe to remove the pool the node was labeled with, otherwise the node might
// still use the deleted pool on next reboot and enter a Degraded state.
func (f *Framework) waitForNodesToHaveARenderedPool(nodes []core.Node, n string) error {
p := &mcfgv1.MachineConfigPool{}
err := f.Client.Get(context.TODO(), types.NamespacedName{Name: n}, p)
if err != nil {
return fmt.Errorf("failed to find Machine Config Pool %s: %w", n, err)
}
fmt.Printf("waiting for nodes to reach %s\n", p.Spec.Configuration.Name)
return wait.PollImmediateInfinite(machineOperationRetryInterval, func() (bool, error) {
for _, loopNode := range nodes {
node := &core.Node{}
err := backoff.Retry(func() error {