-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathsteps.go
More file actions
2153 lines (1938 loc) · 83.2 KB
/
steps.go
File metadata and controls
2153 lines (1938 loc) · 83.2 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 steps
import (
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/cucumber/godog"
jsonpatch "github.com/evanphx/json-patch"
"github.com/google/go-cmp/cmp"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
"github.com/spf13/pflag"
"github.com/stretchr/testify/require"
"helm.sh/helm/v3/pkg/release"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
k8sresource "k8s.io/cli-runtime/pkg/resource"
"k8s.io/component-base/featuregate"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
ocv1 "github.com/operator-framework/operator-controller/api/v1"
"github.com/operator-framework/operator-controller/internal/operator-controller/features"
)
const (
olmDeploymentName = "operator-controller-controller-manager"
timeout = 5 * time.Minute
tick = 1 * time.Second
)
var (
olmNamespace = "olmv1-system"
kubeconfigPath string
k8sCli string
deployImageRegistry = sync.OnceValue(func() error {
if os.Getenv("KIND_CLUSTER_NAME") == "" {
return nil
}
cmd := exec.Command("bash", "-c", "make image-registry")
dir, _ := os.LookupEnv("ROOT_DIR")
if dir == "" {
return fmt.Errorf("ROOT_DIR environment variable not set")
}
cmd.Dir = dir
cmd.Env = append(os.Environ(), fmt.Sprintf("KUBECONFIG=%s", kubeconfigPath))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
})
)
func RegisterSteps(sc *godog.ScenarioContext) {
sc.Step(`^OLM is available$`, OLMisAvailable)
sc.Step(`^(?i)bundle "([^"]+)" is installed in version "([^"]+)"$`, BundleInstalled)
sc.Step(`^(?i)ClusterExtension is applied(?:\s+.*)?$`, ResourceIsApplied)
sc.Step(`^(?i)ClusterExtension is updated to version "([^"]+)"$`, ClusterExtensionVersionUpdate)
sc.Step(`^(?i)ClusterExtension is updated(?:\s+.*)?$`, ResourceIsApplied)
sc.Step(`^(?i)ClusterExtension is available$`, ClusterExtensionIsAvailable)
sc.Step(`^(?i)ClusterExtension is rolled out$`, ClusterExtensionIsRolledOut)
sc.Step(`^(?i)ClusterExtension resources are created and labeled$`, ClusterExtensionResourcesCreatedAndAreLabeled)
sc.Step(`^(?i)ClusterExtension is removed$`, ClusterExtensionIsRemoved)
sc.Step(`^(?i)ClusterExtension (?:latest generation )?has (?:been )?reconciled(?: the latest generation)?$`, ClusterExtensionReconciledLatestGeneration)
sc.Step(`^(?i)the ClusterExtension's constituent resources are removed$`, ClusterExtensionResourcesRemoved)
sc.Step(`^(?i)ClusterExtension reports "([^"]+)" as active revision(s?)$`, ClusterExtensionReportsActiveRevisions)
sc.Step(`^(?i)ClusterExtension reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+) and Message:$`, ClusterExtensionReportsCondition)
sc.Step(`^(?i)ClusterExtension reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+) and Message includes:$`, ClusterExtensionReportsConditionWithMessageFragment)
sc.Step(`^(?i)ClusterExtension reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+)$`, ClusterExtensionReportsConditionWithoutMsg)
sc.Step(`^(?i)ClusterExtension reports ([[:alnum:]]+) as ([[:alnum:]]+)$`, ClusterExtensionReportsConditionWithoutReason)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+)$`, ClusterObjectSetReportsConditionWithoutMsg)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+) and Message:$`, ClusterObjectSetReportsConditionWithMsg)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+) and Message includes:$`, ClusterObjectSetReportsConditionWithMessageFragment)
sc.Step(`^(?i)ClusterExtension reports ([[:alnum:]]+) transition between (\d+) and (\d+) minutes since its creation$`, ClusterExtensionReportsConditionTransitionTime)
sc.Step(`^(?i)ClusterObjectSet is applied(?:\s+.*)?$`, ResourceIsApplied)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" reconciliation is triggered$`, TriggerClusterObjectSetReconciliation)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" has observed phase "([^"]+)" with a non-empty digest$`, ClusterObjectSetHasObservedPhase)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" is archived$`, ClusterObjectSetIsArchived)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" contains annotation "([^"]+)" with value$`, ClusterObjectSetHasAnnotationWithValue)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" has label "([^"]+)" with value "([^"]+)"$`, ClusterObjectSetHasLabelWithValue)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" phase objects are not found or not owned by the revision$`, ClusterObjectSetObjectsNotFoundOrNotOwned)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" phase objects are managed in Kubernetes secrets$`, ClusterObjectSetPhaseObjectsManagedInSecrets)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" referred secrets exist in "([^"]+)" namespace$`, ClusterObjectSetReferredSecretsExist)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" referred secrets are immutable$`, ClusterObjectSetReferredSecretsAreImmutable)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" referred secrets contain labels$`, ClusterObjectSetReferredSecretsContainLabels)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" referred secrets are owned by the object set$`, ClusterObjectSetReferredSecretsOwnedByObjectSet)
sc.Step(`^(?i)ClusterObjectSet "([^"]+)" referred secrets have type "([^"]+)"$`, ClusterObjectSetReferredSecretsHaveType)
sc.Step(`^(?i)resource "([^"]+)" is installed$`, ResourceAvailable)
sc.Step(`^(?i)resource "([^"]+)" is available$`, ResourceAvailable)
sc.Step(`^(?i)resource "([^"]+)" is removed$`, ResourceRemoved)
sc.Step(`^(?i)resource "([^"]+)" is (?:eventually not found|not installed)$`, ResourceEventuallyNotFound)
sc.Step(`^(?i)resource "([^"]+)" exists$`, ResourceAvailable)
sc.Step(`^(?i)resource is applied$`, ResourceIsApplied)
sc.Step(`^(?i)resource "deployment/test-operator" reports as (not ready|ready)$`, MarkTestOperatorNotReady)
sc.Step(`^(?i)resource apply fails with error msg containing "([^"]+)"$`, ResourceApplyFails)
sc.Step(`^(?i)resource "([^"]+)" is eventually restored$`, ResourceRestored)
sc.Step(`^(?i)resource "([^"]+)" matches$`, ResourceMatches)
sc.Step(`^(?i)rollout restart is performed on "([^"]+)"$`, RolloutRestartIsPerformed)
sc.Step(`^(?i)annotations are added to "([^"]+)"$`, AnnotationsAreAdded)
sc.Step(`^(?i)labels are added to "([^"]+)"$`, LabelsAreAdded)
sc.Step(`^(?i)resource "([^"]+)" has annotations$`, ResourceHasAnnotations)
sc.Step(`^(?i)resource "([^"]+)" has labels$`, ResourceHasLabels)
sc.Step(`^(?i)deployment "([^"]+)" pod template has annotation "([^"]+)"$`, DeploymentPodTemplateHasAnnotation)
sc.Step(`^(?i)deployment "([^"]+)" rollout is complete$`, DeploymentRolloutIsComplete)
sc.Step(`^(?i)deployment "([^"]+)" has (\d+) replica sets?$`, DeploymentHasReplicaSets)
sc.Step(`^(?i)ClusterExtension reconciliation is triggered$`, TriggerClusterExtensionReconciliation)
sc.Step(`^(?i)ServiceAccount "([^"]*)" with permissions to install extensions is available in "([^"]*)" namespace$`, ServiceAccountWithNeededPermissionsIsAvailableInGivenNamespace)
sc.Step(`^(?i)ServiceAccount "([^"]*)" with needed permissions is available in test namespace$`, ServiceAccountWithNeededPermissionsIsAvailableInTestNamespace)
sc.Step(`^(?i)ServiceAccount "([^"]*)" without create permissions is available in test namespace$`, ServiceAccountWithoutCreatePermissionsIsAvailableInTestNamespace)
sc.Step(`^(?i)ServiceAccount "([^"]*)" is available in test namespace$`, ServiceAccountIsAvailableInNamespace)
sc.Step(`^(?i)ServiceAccount "([^"]*)" in test namespace is cluster admin$`, ServiceAccountWithClusterAdminPermissionsIsAvailableInNamespace)
sc.Step(`^(?i)ServiceAccount "([^"]+)" in test namespace has permissions to fetch "([^"]+)" metrics$`, ServiceAccountWithFetchMetricsPermissions)
sc.Step(`^(?i)ServiceAccount "([^"]+)" sends request to "([^"]+)" endpoint of "([^"]+)" service$`, SendMetricsRequest)
sc.Step(`^"([^"]+)" catalog is updated to version "([^"]+)"$`, CatalogIsUpdatedToVersion)
sc.Step(`^(?i)ClusterCatalog "([^"]+)" is updated to version "([^"]+)"$`, CatalogIsUpdatedToVersion)
sc.Step(`^"([^"]+)" catalog serves bundles$`, CatalogServesBundles)
sc.Step(`^(?i)ClusterCatalog "([^"]+)" serves bundles$`, CatalogServesBundles)
sc.Step(`^"([^"]+)" catalog image version "([^"]+)" is also tagged as "([^"]+)"$`, TagCatalogImage)
sc.Step(`^(?i)ClusterCatalog "([^"]+)" image version "([^"]+)" is also tagged as "([^"]+)"$`, TagCatalogImage)
sc.Step(`^(?i)ClusterCatalog "([^"]+)" is deleted$`, CatalogIsDeleted)
sc.Step(`^(?i)operator "([^"]+)" target namespace is "([^"]+)"$`, OperatorTargetNamespace)
sc.Step(`^(?i)Prometheus metrics are returned in the response$`, PrometheusMetricsAreReturned)
sc.Step(`^(?i)min value for (ClusterExtension|ClusterObjectSet) ((?:\.[a-zA-Z]+)+) is set to (\d+)$`, SetCRDFieldMinValue)
sc.Step(`^(?i)the current ClusterExtension is tracked for cleanup$`, TrackCurrentClusterExtensionForCleanup)
// TLS profile enforcement steps — deployment configuration
sc.Step(`^(?i)the "([^"]+)" deployment is configured with custom TLS minimum version "([^"]+)"$`, ConfigureDeploymentWithCustomTLSVersion)
sc.Step(`^(?i)the "([^"]+)" deployment is configured with custom TLS version "([^"]+)", ciphers "([^"]+)", and curves "([^"]+)"$`, ConfigureDeploymentWithCustomTLSFull)
// TLS profile enforcement steps — connection assertions
sc.Step(`^(?i)the "([^"]+)" metrics endpoint accepts a TLS 1\.3 connection$`, MetricsEndpointAcceptsTLS13)
sc.Step(`^(?i)the "([^"]+)" metrics endpoint rejects a TLS 1\.2 connection$`, MetricsEndpointRejectsTLS12)
sc.Step(`^(?i)the "([^"]+)" metrics endpoint negotiates cipher "([^"]+)" over TLS 1\.2$`, MetricsEndpointNegotiatesTLS12Cipher)
sc.Step(`^(?i)the "([^"]+)" metrics endpoint rejects a TLS 1\.2 connection offering only cipher "([^"]+)"$`, MetricsEndpointRejectsTLS12ConnectionWithCipher)
sc.Step(`^(?i)the "([^"]+)" metrics endpoint accepts a TLS 1\.2 connection with cipher "([^"]+)" and curve "([^"]+)"$`, MetricsEndpointAcceptsTLS12ConnectionWithCurve)
sc.Step(`^(?i)the "([^"]+)" metrics endpoint rejects a TLS 1\.2 connection with cipher "([^"]+)" and only curve "([^"]+)"$`, MetricsEndpointRejectsTLS12ConnectionWithCurve)
// Upgrade-specific steps
sc.Step(`^(?i)the latest stable OLM release is installed$`, LatestStableOLMReleaseIsInstalled)
sc.Step(`^(?i)OLM is upgraded$`, OLMIsUpgraded)
sc.Step(`^(?i)(catalogd|operator-controller) is ready to reconcile resources$`, ComponentIsReadyToReconcile)
sc.Step(`^(?i)all (ClusterCatalog|ClusterExtension) resources are reconciled$`, allResourcesAreReconciled)
sc.Step(`^(?i)(ClusterCatalog|ClusterExtension) is reconciled$`, ResourceTypeIsReconciled)
sc.Step(`^(?i)ClusterCatalog reports ([[:alnum:]]+) as ([[:alnum:]]+) with Reason ([[:alnum:]]+)$`, ClusterCatalogReportsCondition)
}
func init() {
flagSet := pflag.CommandLine
flagSet.StringVar(&k8sCli, "k8s.cli", "kubectl", "Path to k8s cli")
if v, found := os.LookupEnv("KUBECONFIG"); found {
kubeconfigPath = v
} else {
home, err := os.UserHomeDir()
if err != nil {
panic(fmt.Sprintf("cannot determine user home directory: %v", err))
}
flagSet.StringVar(&kubeconfigPath, "kubeconfig", filepath.Join(home, ".kube", "config"), "Paths to a kubeconfig. Only required if out-of-cluster.")
}
}
func k8sClient(args ...string) (string, error) {
cmd := exec.Command(k8sCli, args...)
logger.V(1).Info("Running", "command", strings.Join(cmd.Args, " "))
cmd.Env = append(os.Environ(), fmt.Sprintf("KUBECONFIG=%s", kubeconfigPath))
b, err := cmd.Output()
if err != nil {
logger.V(1).Info("Failed to run", "command", strings.Join(cmd.Args, " "), "stderr", stderrOutput(err), "error", err)
}
output := string(b)
logger.V(1).Info("Output", "command", strings.Join(cmd.Args, " "), "output", output)
return output, err
}
func k8scliWithInput(yaml string, args ...string) (string, error) {
cmd := exec.Command(k8sCli, args...)
cmd.Stdin = bytes.NewBufferString(yaml)
cmd.Env = append(os.Environ(), fmt.Sprintf("KUBECONFIG=%s", kubeconfigPath))
b, err := cmd.Output()
return string(b), err
}
// OLMisAvailable waits for the OLM operator-controller deployment to become available. Polls with timeout.
func OLMisAvailable(ctx context.Context) error {
require.Eventually(godog.T(ctx), func() bool {
v, err := k8sClient("get", "deployment", "-n", olmNamespace, olmDeploymentName, "-o", "jsonpath='{.status.conditions[?(@.type==\"Available\")].status}'")
if err != nil {
return false
}
return v == "'True'"
}, timeout, tick)
return nil
}
// BundleInstalled waits for the ClusterExtension to report the specified bundle name and version as installed. Polls with timeout.
func BundleInstalled(ctx context.Context, name, version string) error {
sc := scenarioCtx(ctx)
waitFor(ctx, func() bool {
v, err := k8sClient("get", "clusterextension", sc.clusterExtensionName, "-o", "jsonpath={.status.install.bundle}")
if err != nil {
return false
}
var bundle map[string]interface{}
if err := json.Unmarshal([]byte(v), &bundle); err != nil {
return false
}
return bundle["name"] == name && bundle["version"] == version
})
return nil
}
func toUnstructured(yamlContent string) (*unstructured.Unstructured, error) {
var u map[string]any
if err := yaml.Unmarshal([]byte(yamlContent), &u); err != nil {
return nil, err
}
return &unstructured.Unstructured{Object: u}, nil
}
func substituteScenarioVars(content string, sc *scenarioContext) string {
vars := map[string]string{
"TEST_NAMESPACE": sc.namespace,
"NAME": sc.clusterExtensionName,
"COS_NAME": sc.clusterObjectSetName,
"CATALOG_IMG": "docker-registry.operator-controller-e2e.svc.cluster.local:5000/e2e/test-catalog:v1",
}
if v, found := os.LookupEnv("CATALOG_IMG"); found {
vars["CATALOG_IMG"] = v
}
return templateContent(content, vars)
}
// ResourceApplyFails waits for kubectl apply of the provided YAML to fail with the expected error message. Polls with timeout.
func ResourceApplyFails(ctx context.Context, errMsg string, yamlTemplate *godog.DocString) error {
sc := scenarioCtx(ctx)
yamlContent := substituteScenarioVars(yamlTemplate.Content, sc)
_, err := toUnstructured(yamlContent)
if err != nil {
return fmt.Errorf("failed to parse resource yaml: %v", err)
}
waitFor(ctx, func() bool {
_, err := k8scliWithInput(yamlContent, "apply", "-f", "-")
if err == nil {
return false
}
if stdErr := stderrOutput(err); !strings.Contains(stdErr, errMsg) {
return false
}
return true
})
return nil
}
// TrackCurrentClusterExtensionForCleanup saves the current ClusterExtension name in the cleanup list
// so it gets deleted at the end of the scenario. Call this before applying a second ClusterExtension
// in the same scenario, because ResourceIsApplied overwrites the tracked name.
func TrackCurrentClusterExtensionForCleanup(ctx context.Context) error {
sc := scenarioCtx(ctx)
if sc.clusterExtensionName != "" {
sc.addedResources = append(sc.addedResources, resource{name: sc.clusterExtensionName, kind: "clusterextension"})
}
return nil
}
// ClusterExtensionVersionUpdate patches the ClusterExtension's catalog version to the specified value.
func ClusterExtensionVersionUpdate(ctx context.Context, version string) error {
sc := scenarioCtx(ctx)
patch := map[string]any{
"spec": map[string]any{
"source": map[string]any{
"catalog": map[string]any{
"version": version,
},
},
},
}
pb, err := json.Marshal(patch)
if err != nil {
return err
}
_, err = k8sClient("patch", "clusterextension", sc.clusterExtensionName, "--type", "merge", "-p", string(pb))
return err
}
// ResourceIsApplied applies the provided YAML resource to the cluster and in case of ClusterExtension or ClusterObjectSet it captures
// its name in the test context so that it can be referred to in later steps with ${NAME} or ${COS_NAME}, respectively
func ResourceIsApplied(ctx context.Context, yamlTemplate *godog.DocString) error {
sc := scenarioCtx(ctx)
yamlContent := substituteScenarioVars(yamlTemplate.Content, sc)
res, err := toUnstructured(yamlContent)
if err != nil {
return fmt.Errorf("failed to parse resource yaml: %v", err)
}
out, err := k8scliWithInput(yamlContent, "apply", "-f", "-")
if err != nil {
return fmt.Errorf("failed to apply resource %v; err: %w; stderr: %s", out, err, stderrOutput(err))
}
if res.GetKind() == "ClusterExtension" {
sc.clusterExtensionName = res.GetName()
} else if res.GetKind() == "ClusterObjectSet" {
sc.clusterObjectSetName = res.GetName()
} else {
namespace := res.GetNamespace()
if namespace == "" {
namespace = sc.namespace
}
sc.addedResources = append(sc.addedResources, resource{
name: res.GetName(),
kind: strings.ToLower(res.GetKind()),
namespace: namespace,
})
}
return nil
}
// ClusterExtensionIsAvailable waits for the ClusterExtension's Installed condition to be True. Polls with timeout.
func ClusterExtensionIsAvailable(ctx context.Context) error {
sc := scenarioCtx(ctx)
require.Eventually(godog.T(ctx), func() bool {
v, err := k8sClient("get", "clusterextension", sc.clusterExtensionName, "-o", "jsonpath={.status.conditions[?(@.type==\"Installed\")].status}")
if err != nil {
return false
}
return v == "True"
}, timeout, tick)
return nil
}
// ClusterExtensionReconciledLatestGeneration waits for the ClusterExtension's observedGeneration to match its metadata generation. Polls with timeout.
func ClusterExtensionReconciledLatestGeneration(ctx context.Context) error {
sc := scenarioCtx(ctx)
waitFor(ctx, func() bool {
// Get both generation and observedGeneration in a single kubectl call
output, err := k8sClient("get", "clusterextension", sc.clusterExtensionName,
"-o", "jsonpath={.metadata.generation},{.status.conditions[?(@.type=='Progressing')].observedGeneration}")
if err != nil || output == "" {
return false
}
parts := strings.Split(output, ",")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return false
}
// Both exist and are equal means reconciliation happened
return parts[0] == parts[1]
})
return nil
}
// ClusterExtensionIsRolledOut waits for the ClusterExtension's Progressing condition to be True with reason Succeeded,
// then gathers its constituent resources into the scenario context. Polls with timeout.
func ClusterExtensionIsRolledOut(ctx context.Context) error {
sc := scenarioCtx(ctx)
require.Eventually(godog.T(ctx), func() bool {
v, err := k8sClient("get", "clusterextension", sc.clusterExtensionName, "-o", "jsonpath={.status.conditions[?(@.type==\"Progressing\")]}")
if err != nil {
return false
}
var condition map[string]interface{}
if err := json.Unmarshal([]byte(v), &condition); err != nil {
return false
}
return condition["status"] == "True" && condition["reason"] == "Succeeded" && condition["type"] == "Progressing"
}, timeout, tick)
// Save ClusterExtension resources to test context for posterior checks
if err := sc.GatherClusterExtensionObjects(); err != nil {
return err
}
return nil
}
// ClusterExtensionResourcesCreatedAndAreLabeled verifies each constituent resource has the expected OLM owner-kind
// and owner-name labels. Polls with timeout per resource.
func ClusterExtensionResourcesCreatedAndAreLabeled(ctx context.Context) error {
sc := scenarioCtx(ctx)
if len(sc.GetClusterExtensionObjects()) == 0 {
return fmt.Errorf("extension objects not found in context")
}
for _, obj := range sc.GetClusterExtensionObjects() {
waitFor(ctx, func() bool {
kind := obj.GetObjectKind().GroupVersionKind().Kind
clusterObj, err := getResource(kind, obj.GetName(), obj.GetNamespace())
if err != nil {
logger.V(1).Error(err, "error getting resource", "name", obj.GetName(), "namespace", obj.GetNamespace(), "kind", kind)
return false
}
labels := clusterObj.GetLabels()
if labels == nil {
logger.V(1).Info("no labels found for resource", "name", obj.GetName(), "namespace", obj.GetNamespace(), "kind", kind)
return false
}
for key, expectedValue := range map[string]string{
"olm.operatorframework.io/owner-kind": "ClusterExtension",
"olm.operatorframework.io/owner-name": sc.clusterExtensionName,
} {
if labels[key] != expectedValue {
logger.V(1).Info("invalid resource label value", "name", obj.GetName(), "namespace", obj.GetNamespace(), "kind", kind, "label", key, "expected", expectedValue, "actual", labels["olm.operatorframework.io/owner-kind"])
return false
}
}
return true
})
}
return nil
}
// ClusterExtensionIsRemoved deletes the current ClusterExtension, saving its state for potential restore checks.
func ClusterExtensionIsRemoved(ctx context.Context) error {
sc := scenarioCtx(ctx)
return ResourceRemoved(ctx, fmt.Sprintf("clusterextension/%s", sc.clusterExtensionName))
}
// ClusterExtensionResourcesRemoved waits for each previously gathered constituent resource to be deleted. Polls with timeout per resource.
func ClusterExtensionResourcesRemoved(ctx context.Context) error {
sc := scenarioCtx(ctx)
if len(sc.GetClusterExtensionObjects()) == 0 {
return fmt.Errorf("extension objects not found in context")
}
for _, obj := range sc.GetClusterExtensionObjects() {
if err := ResourceEventuallyNotFound(ctx, fmt.Sprintf("%s/%s", obj.GetObjectKind().GroupVersionKind().Kind, obj.GetName())); err != nil {
return err
}
}
return nil
}
func waitFor(ctx context.Context, conditionFn func() bool) {
require.Eventually(godog.T(ctx), conditionFn, timeout, tick)
}
type msgMatchFn func(string) bool
func alwaysMatch(_ string) bool { return true }
func isFeatureGateEnabled(feature featuregate.Feature) bool {
enabled, found := featureGates[feature]
return enabled && found
}
func messageComparison(ctx context.Context, msg *godog.DocString) msgMatchFn {
msgCmp := alwaysMatch
if msg != nil {
expectedMsg := substituteScenarioVars(strings.Join(strings.Fields(msg.Content), " "), scenarioCtx(ctx))
msgCmp = func(actual string) bool {
return actual == expectedMsg
}
}
return msgCmp
}
func waitForCondition(ctx context.Context, resourceType, resourceName, conditionType, conditionStatus string, conditionReason *string, msgCmp msgMatchFn) error {
require.Eventually(godog.T(ctx), func() bool {
v, err := k8sClient("get", resourceType, resourceName, "-o", fmt.Sprintf("jsonpath={.status.conditions[?(@.type==\"%s\")]}", conditionType))
if err != nil {
return false
}
var condition metav1.Condition
if err := json.Unmarshal([]byte(v), &condition); err != nil {
return false
}
if condition.Status != metav1.ConditionStatus(conditionStatus) {
return false
}
if conditionReason != nil && condition.Reason != *conditionReason {
return false
}
if msgCmp != nil && !msgCmp(condition.Message) {
return false
}
return true
}, timeout, tick)
return nil
}
func waitForExtensionCondition(ctx context.Context, conditionType, conditionStatus string, conditionReason *string, msgCmp msgMatchFn) error {
sc := scenarioCtx(ctx)
return waitForCondition(ctx, "clusterextension", sc.clusterExtensionName, conditionType, conditionStatus, conditionReason, msgCmp)
}
// ClusterExtensionReportsCondition waits for the ClusterExtension to have a condition matching the specified type,
// status, reason, and exact message. Polls with timeout.
func ClusterExtensionReportsCondition(ctx context.Context, conditionType, conditionStatus, conditionReason string, msg *godog.DocString) error {
return waitForExtensionCondition(ctx, conditionType, conditionStatus, &conditionReason, messageComparison(ctx, msg))
}
// ClusterExtensionReportsConditionWithMessageFragment waits for the ClusterExtension to have a condition matching
// type, status, and reason, with a message containing the specified fragment. Polls with timeout.
func ClusterExtensionReportsConditionWithMessageFragment(ctx context.Context, conditionType, conditionStatus, conditionReason string, msgFragment *godog.DocString) error {
msgCmp := alwaysMatch
if msgFragment != nil {
expectedMsgFragment := substituteScenarioVars(strings.Join(strings.Fields(msgFragment.Content), " "), scenarioCtx(ctx))
msgCmp = func(actualMsg string) bool {
normalizedActual := strings.Join(strings.Fields(actualMsg), " ")
return strings.Contains(normalizedActual, expectedMsgFragment)
}
}
return waitForExtensionCondition(ctx, conditionType, conditionStatus, &conditionReason, msgCmp)
}
// ClusterExtensionReportsConditionWithoutMsg waits for the ClusterExtension to have a condition matching type,
// status, and reason, without checking the message. Polls with timeout.
func ClusterExtensionReportsConditionWithoutMsg(ctx context.Context, conditionType, conditionStatus, conditionReason string) error {
return ClusterExtensionReportsCondition(ctx, conditionType, conditionStatus, conditionReason, nil)
}
// ClusterExtensionReportsConditionWithoutReason waits for the ClusterExtension to have a condition matching type
// and status, without checking reason or message. Polls with timeout.
func ClusterExtensionReportsConditionWithoutReason(ctx context.Context, conditionType, conditionStatus string) error {
return waitForExtensionCondition(ctx, conditionType, conditionStatus, nil, nil)
}
// ClusterExtensionReportsConditionTransitionTime asserts that a condition's lastTransitionTime falls within
// the specified minute range since the ClusterExtension's creation.
func ClusterExtensionReportsConditionTransitionTime(ctx context.Context, conditionType string, minMinutes, maxMinutes int) error {
sc := scenarioCtx(ctx)
t := godog.T(ctx)
// Get the ClusterExtension's creation timestamp and condition's lastTransitionTime
v, err := k8sClient("get", "clusterextension", sc.clusterExtensionName, "-o",
fmt.Sprintf("jsonpath={.metadata.creationTimestamp},{.status.conditions[?(@.type==\"%s\")].lastTransitionTime}", conditionType))
require.NoError(t, err)
parts := strings.Split(v, ",")
require.Len(t, parts, 2, "expected creationTimestamp and lastTransitionTime but got: %s", v)
creationTimestamp, err := time.Parse(time.RFC3339, parts[0])
require.NoError(t, err, "failed to parse creationTimestamp")
lastTransitionTime, err := time.Parse(time.RFC3339, parts[1])
require.NoError(t, err, "failed to parse lastTransitionTime")
transitionDuration := lastTransitionTime.Sub(creationTimestamp)
minDuration := time.Duration(minMinutes) * time.Minute
maxDuration := time.Duration(maxMinutes) * time.Minute
require.GreaterOrEqual(t, transitionDuration, minDuration,
"condition %s transitioned too early: %v since creation (expected >= %v)", conditionType, transitionDuration, minDuration)
require.LessOrEqual(t, transitionDuration, maxDuration,
"condition %s transitioned too late: %v since creation (expected <= %v)", conditionType, transitionDuration, maxDuration)
return nil
}
// ClusterExtensionReportsActiveRevisions waits for the ClusterExtension's active revisions to match the expected
// set of revision names. Polls with timeout.
func ClusterExtensionReportsActiveRevisions(ctx context.Context, rawRevisionNames string) error {
sc := scenarioCtx(ctx)
expectedRevisionNames := sets.New[string]()
for _, rev := range strings.Split(rawRevisionNames, ",") {
expectedRevisionNames.Insert(substituteScenarioVars(strings.TrimSpace(rev), sc))
}
waitFor(ctx, func() bool {
v, err := k8sClient("get", "clusterextension", sc.clusterExtensionName, "-o", "jsonpath={.status.activeRevisions}")
if err != nil {
return false
}
var activeRevisions []ocv1.RevisionStatus
if err := json.Unmarshal([]byte(v), &activeRevisions); err != nil {
return false
}
activeRevisionsNames := sets.New[string]()
for _, rev := range activeRevisions {
activeRevisionsNames.Insert(rev.Name)
}
return activeRevisionsNames.Equal(expectedRevisionNames)
})
return nil
}
// ClusterObjectSetReportsConditionWithoutMsg waits for the named ClusterObjectSet to have a condition
// matching type, status, and reason. Polls with timeout.
func ClusterObjectSetReportsConditionWithoutMsg(ctx context.Context, revisionName, conditionType, conditionStatus, conditionReason string) error {
return waitForCondition(ctx, "clusterobjectset", substituteScenarioVars(revisionName, scenarioCtx(ctx)), conditionType, conditionStatus, &conditionReason, nil)
}
// ClusterObjectSetReportsConditionWithMsg waits for the named ClusterObjectSet to have a condition
// matching type, status, reason, and message. Polls with timeout.
func ClusterObjectSetReportsConditionWithMsg(ctx context.Context, revisionName, conditionType, conditionStatus, conditionReason string, msg *godog.DocString) error {
return waitForCondition(ctx, "clusterobjectset", substituteScenarioVars(revisionName, scenarioCtx(ctx)), conditionType, conditionStatus, &conditionReason, messageComparison(ctx, msg))
}
// ClusterObjectSetReportsConditionWithMessageFragment waits for the named ClusterObjectSet to have a condition
// matching type, status, reason, with a message containing the specified fragment. Polls with timeout.
func ClusterObjectSetReportsConditionWithMessageFragment(ctx context.Context, revisionName, conditionType, conditionStatus, conditionReason string, msgFragment *godog.DocString) error {
msgCmp := alwaysMatch
if msgFragment != nil {
expectedMsgFragment := substituteScenarioVars(strings.Join(strings.Fields(msgFragment.Content), " "), scenarioCtx(ctx))
msgCmp = func(actualMsg string) bool {
normalizedActual := strings.Join(strings.Fields(actualMsg), " ")
return strings.Contains(normalizedActual, expectedMsgFragment)
}
}
return waitForCondition(ctx, "clusterobjectset", substituteScenarioVars(revisionName, scenarioCtx(ctx)), conditionType, conditionStatus, &conditionReason, msgCmp)
}
// TriggerClusterObjectSetReconciliation annotates the named ClusterObjectSet
// to trigger a new reconciliation cycle.
func TriggerClusterObjectSetReconciliation(ctx context.Context, cosName string) error {
sc := scenarioCtx(ctx)
cosName = substituteScenarioVars(cosName, sc)
_, err := k8sClient("annotate", "clusterobjectset", cosName, "--overwrite",
fmt.Sprintf("e2e-trigger=%d", time.Now().UnixNano()))
return err
}
// ClusterObjectSetHasObservedPhase waits for the named ClusterObjectSet to have
// an observedPhases entry matching the given phase name with a non-empty digest. Polls with timeout.
func ClusterObjectSetHasObservedPhase(ctx context.Context, cosName, phaseName string) error {
sc := scenarioCtx(ctx)
cosName = substituteScenarioVars(cosName, sc)
phaseName = substituteScenarioVars(phaseName, sc)
waitFor(ctx, func() bool {
out, err := k8sClient("get", "clusterobjectset", cosName, "-o",
fmt.Sprintf(`jsonpath={.status.observedPhases[?(@.name=="%s")].digest}`, phaseName))
if err != nil {
return false
}
return strings.TrimSpace(out) != ""
})
return nil
}
// ClusterObjectSetIsArchived waits for the named ClusterObjectSet to have Progressing=False
// with reason Archived. Polls with timeout.
func ClusterObjectSetIsArchived(ctx context.Context, revisionName string) error {
return waitForCondition(ctx, "clusterobjectset", substituteScenarioVars(revisionName, scenarioCtx(ctx)), "Progressing", "False", ptr.To("Archived"), nil)
}
// ClusterObjectSetHasAnnotationWithValue waits for the named ClusterObjectSet to have the specified
// annotation with the expected value. Polls with timeout.
func ClusterObjectSetHasAnnotationWithValue(ctx context.Context, revisionName, annotationKey string, annotationValue *godog.DocString) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
expectedValue := ""
if annotationValue != nil {
expectedValue = annotationValue.Content
}
waitFor(ctx, func() bool {
obj, err := getResource("clusterobjectset", revisionName, "")
if err != nil {
logger.V(1).Error(err, "failed to get clusterobjectset", "name", revisionName)
return false
}
if obj.GetAnnotations() == nil {
return false
}
return obj.GetAnnotations()[annotationKey] == expectedValue
})
return nil
}
// ClusterObjectSetHasLabelWithValue waits for the named ClusterObjectSet to have the specified label
// with the expected value. Polls with timeout.
func ClusterObjectSetHasLabelWithValue(ctx context.Context, revisionName, labelKey, labelValue string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
labelValue = substituteScenarioVars(labelValue, sc)
waitFor(ctx, func() bool {
obj, err := getResource("clusterobjectset", revisionName, "")
if err != nil {
logger.V(1).Error(err, "failed to get clusterobjectset", "name", revisionName)
return false
}
if obj.GetLabels() == nil {
return false
}
return obj.GetLabels()[labelKey] == labelValue
})
return nil
}
// ClusterObjectSetObjectsNotFoundOrNotOwned waits for all objects described in the named
// ClusterObjectSet's phases to either not exist on the cluster or not contain the revision
// in their ownerReferences. Polls with timeout.
func ClusterObjectSetObjectsNotFoundOrNotOwned(ctx context.Context, revisionName string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
// Get the ClusterObjectSet to extract its phase objects
var rev ocv1.ClusterObjectSet
waitFor(ctx, func() bool {
out, err := k8sClient("get", "clusterobjectset", revisionName, "-o", "json")
if err != nil {
return false
}
return json.Unmarshal([]byte(out), &rev) == nil
})
// For each object in each phase, verify it either doesn't exist or
// doesn't have the ClusterObjectSet in its ownerReferences
for i, phase := range rev.Spec.Phases {
for j, phaseObj := range phase.Objects {
var obj *unstructured.Unstructured
switch {
case phaseObj.Ref.Name != "":
resolved, err := resolveObjectRef(phaseObj.Ref)
if err != nil {
return fmt.Errorf("resolving ref in phase %q object %d: %w", phase.Name, j, err)
}
obj = resolved
case len(phaseObj.Object.Object) > 0:
obj = &phaseObj.Object
default:
return fmt.Errorf("clusterobjectset %q phase %d object %d has neither ref nor inline object", revisionName, i, j)
}
kind := obj.GetKind()
name := obj.GetName()
namespace := obj.GetNamespace()
if kind == "" {
return fmt.Errorf("clusterobjectset %q has a phase object with empty kind", revisionName)
}
if name == "" {
return fmt.Errorf("clusterobjectset %q has a phase object with empty name (kind %q, namespace %q)", revisionName, kind, namespace)
}
waitFor(ctx, func() bool {
args := []string{"get", kind, name, "--ignore-not-found", "-o", "json"}
if namespace != "" {
args = append(args, "-n", namespace)
}
out, err := k8sClient(args...)
if err != nil {
return false
}
// If output is empty, the resource does not exist — condition satisfied
if strings.TrimSpace(out) == "" {
return true
}
clusterObj, err := toUnstructured(out)
if err != nil {
return false
}
// Check that no ownerReference points to this ClusterObjectSet
for _, ref := range clusterObj.GetOwnerReferences() {
if ref.Kind == ocv1.ClusterObjectSetKind && ref.Name == revisionName && ref.UID == rev.UID {
logger.V(1).Info("object still owned by revision",
"kind", kind, "name", name, "namespace", namespace,
"revision", revisionName)
return false
}
}
return true
})
}
}
return nil
}
// ClusterObjectSetPhaseObjectsManagedInSecrets verifies that every object in every phase of the named
// ClusterObjectSet uses a ref (not an inline object). Polls with timeout.
func ClusterObjectSetPhaseObjectsManagedInSecrets(ctx context.Context, revisionName string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
waitFor(ctx, func() bool {
obj, err := getResource("clusterobjectset", revisionName, "")
if err != nil {
return false
}
phases, ok, _ := unstructured.NestedSlice(obj.Object, "spec", "phases")
if !ok || len(phases) == 0 {
return false
}
for _, p := range phases {
phase, ok := p.(map[string]interface{})
if !ok {
return false
}
objects, ok, _ := unstructured.NestedSlice(phase, "objects")
if !ok || len(objects) == 0 {
return false
}
for _, o := range objects {
obj, ok := o.(map[string]interface{})
if !ok {
return false
}
ref, refOK, _ := unstructured.NestedMap(obj, "ref")
if !refOK || len(ref) == 0 {
logger.V(1).Info("object does not use ref", "revision", revisionName)
return false
}
name, _, _ := unstructured.NestedString(ref, "name")
if name == "" {
logger.V(1).Info("ref has empty name", "revision", revisionName)
return false
}
}
}
return true
})
return nil
}
// ClusterObjectSetReferredSecretsExist verifies that all Secrets referenced by the named
// ClusterObjectSet's phase objects exist in the given namespace. Polls with timeout.
func ClusterObjectSetReferredSecretsExist(ctx context.Context, revisionName, namespace string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
namespace = substituteScenarioVars(strings.TrimSpace(namespace), sc)
secretNames, err := collectReferredSecretNames(ctx, revisionName)
if err != nil {
return err
}
for _, name := range secretNames {
waitFor(ctx, func() bool {
_, err := getResource("secret", name, namespace)
return err == nil
})
}
return nil
}
// ClusterObjectSetReferredSecretsAreImmutable verifies that all referred Secrets for the named
// ClusterObjectSet are immutable. Polls with timeout.
func ClusterObjectSetReferredSecretsAreImmutable(ctx context.Context, revisionName string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
secrets, err := listReferredSecrets(ctx, revisionName)
if err != nil {
return err
}
if len(secrets) == 0 {
return fmt.Errorf("no referred secrets found for revision %q", revisionName)
}
for _, s := range secrets {
if s.Immutable == nil || !*s.Immutable {
return fmt.Errorf("referred secret %s/%s is not immutable", s.Namespace, s.Name)
}
}
return nil
}
// ClusterObjectSetReferredSecretsContainLabels verifies that all referred Secrets for the named
// ClusterObjectSet have the expected labels specified in the data table. Polls with timeout.
func ClusterObjectSetReferredSecretsContainLabels(ctx context.Context, revisionName string, table *godog.Table) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
expected, err := parseKeyValueTable(table)
if err != nil {
return fmt.Errorf("invalid labels table: %w", err)
}
for k, v := range expected {
expected[k] = substituteScenarioVars(v, sc)
}
waitFor(ctx, func() bool {
secrets, err := listReferredSecrets(ctx, revisionName)
if err != nil || len(secrets) == 0 {
return false
}
for _, s := range secrets {
if _, _, ok := matchLabels(s.Labels, expected); !ok {
return false
}
}
return true
})
return nil
}
// ClusterObjectSetReferredSecretsOwnedByObjectSet verifies that all referred Secrets for the named
// ClusterObjectSet have an ownerReference pointing to the ClusterObjectSet with controller=true.
func ClusterObjectSetReferredSecretsOwnedByObjectSet(ctx context.Context, revisionName string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
cosObj, err := getResource("clusterobjectset", revisionName, "")
if err != nil {
return fmt.Errorf("getting ClusterObjectSet %q: %w", revisionName, err)
}
cosUID := cosObj.GetUID()
secrets, err := listReferredSecrets(ctx, revisionName)
if err != nil {
return err
}
if len(secrets) == 0 {
return fmt.Errorf("no referred secrets found for revision %q", revisionName)
}
for _, s := range secrets {
found := false
for _, ref := range s.OwnerReferences {
if ref.Kind == ocv1.ClusterObjectSetKind && ref.Name == revisionName && ref.UID == cosUID {
if ref.Controller == nil || !*ref.Controller {
return fmt.Errorf("secret %s/%s has ownerReference to ClusterObjectSet but controller is not true", s.Namespace, s.Name)
}
found = true
break
}
}
if !found {
return fmt.Errorf("secret %s/%s does not have ownerReference to ClusterObjectSet %q (uid %s)", s.Namespace, s.Name, revisionName, cosUID)
}
}
return nil
}
// ClusterObjectSetReferredSecretsHaveType verifies that all referred Secrets for the named
// ClusterObjectSet have the specified Secret type.
func ClusterObjectSetReferredSecretsHaveType(ctx context.Context, revisionName, expectedType string) error {
sc := scenarioCtx(ctx)
revisionName = substituteScenarioVars(strings.TrimSpace(revisionName), sc)
secrets, err := listReferredSecrets(ctx, revisionName)
if err != nil {
return err
}
if len(secrets) == 0 {
return fmt.Errorf("no referred secrets found for revision %q", revisionName)
}
for _, s := range secrets {
if string(s.Type) != expectedType {
return fmt.Errorf("secret %s/%s has type %q, expected %q", s.Namespace, s.Name, s.Type, expectedType)
}
}
return nil
}
// collectReferredSecretNames returns the unique set of Secret names referenced by the ClusterObjectSet's phase objects.
func collectReferredSecretNames(ctx context.Context, revisionName string) ([]string, error) {
var names []string
seen := sets.New[string]()
var obj *unstructured.Unstructured
waitFor(ctx, func() bool {
var err error
obj, err = getResource("clusterobjectset", revisionName, "")
return err == nil
})
phases, _, _ := unstructured.NestedSlice(obj.Object, "spec", "phases")
for _, p := range phases {
phase, ok := p.(map[string]interface{})
if !ok {
continue
}
objects, _, _ := unstructured.NestedSlice(phase, "objects")
for _, o := range objects {
phaseObj, ok := o.(map[string]interface{})
if !ok {
continue
}
name, _, _ := unstructured.NestedString(phaseObj, "ref", "name")
if name != "" && !seen.Has(name) {
seen.Insert(name)
names = append(names, name)
}
}
}
if len(names) == 0 {
return nil, fmt.Errorf("no referred secret names found in ClusterObjectSet %q", revisionName)
}
return names, nil
}
// listReferredSecrets lists all Secrets in the OLM namespace that have the revision-name label