/
util.go
1866 lines (1652 loc) · 71.4 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package util
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/google/go-cmp/cmp"
. "github.com/onsi/gomega"
configv1 "github.com/openshift/api/config/v1"
routev1 "github.com/openshift/api/route/v1"
routev1client "github.com/openshift/client-go/route/clientset/versioned"
hyperv1 "github.com/openshift/hypershift/api/hypershift/v1beta1"
"github.com/openshift/hypershift/cmd/cluster/core"
hcmetrics "github.com/openshift/hypershift/hypershift-operator/controllers/hostedcluster/metrics"
"github.com/openshift/hypershift/hypershift-operator/controllers/manifests"
"github.com/openshift/hypershift/support/conditions"
suppconfig "github.com/openshift/hypershift/support/config"
"github.com/openshift/hypershift/support/util"
support "github.com/openshift/hypershift/support/util"
"github.com/openshift/library-go/test/library/metrics"
promapi "github.com/prometheus/client_golang/api"
prometheusv1 "github.com/prometheus/client_golang/api/prometheus/v1"
promv1 "github.com/prometheus/client_golang/api/prometheus/v1"
promconfig "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
prommodel "github.com/prometheus/common/model"
"go.uber.org/zap/zaptest"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
appsv1 "k8s.io/api/apps/v1"
authenticationv1 "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
kapierror "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
k8s "k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/utils/pointer"
capiv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
crclient "sigs.k8s.io/controller-runtime/pkg/client"
)
var expectedKasManagementComponents = []string{
"cluster-network-operator",
"ignition-server",
"cluster-storage-operator",
"csi-snapshot-controller-operator",
"machine-approver",
"cluster-autoscaler",
"cluster-node-tuning-operator",
"capi-provider-controller-manager",
"capi-provider",
"cluster-api",
"etcd",
"control-plane-operator",
"control-plane-pki-operator",
"hosted-cluster-config-operator",
"cloud-controller-manager",
"olm-collect-profiles",
"aws-ebs-csi-driver-operator",
}
func UpdateObject[T crclient.Object](t *testing.T, ctx context.Context, client crclient.Client, original T, mutate func(obj T)) error {
return wait.PollImmediateWithContext(ctx, time.Second, time.Minute*1, func(ctx context.Context) (done bool, err error) {
if err := client.Get(ctx, crclient.ObjectKeyFromObject(original), original); err != nil {
t.Logf("failed to retrieve object %s, will retry: %v", original.GetName(), err)
return false, nil
}
obj := original.DeepCopyObject().(T)
mutate(obj)
if err := client.Patch(ctx, obj, crclient.MergeFrom(original)); err != nil {
t.Logf("failed to patch object %s, will retry: %v", original.GetName(), err)
if errors.IsConflict(err) {
return false, nil
}
return false, err
}
return true, nil
})
}
// DeleteNamespace deletes and finalizes the given namespace, logging any failures
// along the way.
func DeleteNamespace(t *testing.T, ctx context.Context, client crclient.Client, namespace string) error {
t.Logf("Deleting namespace: %s", namespace)
err := wait.PollImmediateWithContext(ctx, 10*time.Second, 20*time.Minute, func(ctx context.Context) (done bool, err error) {
ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}
if err := client.Delete(ctx, ns, &crclient.DeleteOptions{}); err != nil {
if errors.IsNotFound(err) {
return true, nil
}
t.Logf("Failed to delete namespace: %s, will retry: %v", namespace, err)
return false, nil
}
return true, nil
})
if err != nil {
return fmt.Errorf("failed to delete namespace: %w", err)
}
t.Logf("Waiting for namespace to be finalized. Namespace: %s", namespace)
err = wait.PollImmediateWithContext(ctx, 10*time.Second, 20*time.Minute, func(ctx context.Context) (done bool, err error) {
ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}
if err := client.Get(ctx, crclient.ObjectKeyFromObject(ns), ns); err != nil {
if errors.IsNotFound(err) {
return true, nil
}
t.Logf("Failed to get namespace: %s. %v", namespace, err)
return false, nil
}
return false, nil
})
if err != nil {
return fmt.Errorf("namespace still exists after deletion timeout: %v", err)
}
t.Logf("Deleted namespace: %s", namespace)
return nil
}
func WaitForGuestKubeConfig(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) ([]byte, error) {
start := time.Now()
t.Logf("Waiting for hostedcluster kubeconfig to be published. Namespace: %s, name: %s", hostedCluster.Namespace, hostedCluster.Name)
var guestKubeConfigSecret corev1.Secret
err := wait.PollImmediateWithContext(ctx, 1*time.Second, 30*time.Minute, func(ctx context.Context) (done bool, err error) {
if err = client.Get(ctx, crclient.ObjectKeyFromObject(hostedCluster), hostedCluster); err != nil {
return false, nil
}
if hostedCluster.Status.KubeConfig == nil {
return false, nil
}
key := crclient.ObjectKey{
Namespace: hostedCluster.Namespace,
Name: hostedCluster.Status.KubeConfig.Name,
}
if err := client.Get(ctx, key, &guestKubeConfigSecret); err != nil {
return false, nil
}
return true, nil
})
if err != nil {
return nil, fmt.Errorf("kubeconfig didn't become available: %w", err)
}
t.Logf("Found kubeconfig for cluster in %s. Namespace: %s, name: %s", time.Since(start).Round(time.Second), hostedCluster.Namespace, hostedCluster.Name)
// TODO: this key should probably be published or an API constant
data, hasData := guestKubeConfigSecret.Data["kubeconfig"]
if !hasData {
return nil, fmt.Errorf("kubeconfig secret is missing kubeconfig key")
}
return data, nil
}
func WaitForGuestClient(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) crclient.Client {
g := NewWithT(t)
start := time.Now()
guestKubeConfigSecretData, err := WaitForGuestKubeConfig(t, ctx, client, hostedCluster)
g.Expect(err).NotTo(HaveOccurred(), "couldn't get kubeconfig")
guestConfig, err := clientcmd.RESTConfigFromKubeConfig(guestKubeConfigSecretData)
g.Expect(err).NotTo(HaveOccurred(), "couldn't load guest kubeconfig")
t.Logf("Waiting for a successful connection to the guest apiserver")
var guestClient crclient.Client
// Mulham: increased timeout from 5m to 15m as guest kubeconfig/API server takes longer to report available after switching from private to public
waitForGuestClientCtx, cancel := context.WithTimeout(ctx, 15*time.Minute)
defer cancel()
// SOA TTL is 60s. If DNS lookup fails on the api-* name, it is unlikely to succeed in less than 60s.
err = wait.PollImmediateWithContext(waitForGuestClientCtx, 35*time.Second, 30*time.Minute, func(ctx context.Context) (done bool, err error) {
kubeClient, err := crclient.New(guestConfig, crclient.Options{Scheme: scheme})
if err != nil {
t.Logf("attempt to connect failed: %s", err)
return false, nil
}
guestClient = kubeClient
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), "failed to establish a connection to the guest apiserver")
t.Logf("Successfully connected to the guest apiserver in %s", time.Since(start).Round(time.Second))
return guestClient
}
func WaitForNReadyNodes(t *testing.T, ctx context.Context, client crclient.Client, n int32, platform hyperv1.PlatformType) []corev1.Node {
g := NewWithT(t)
start := time.Now()
// waitTimeout for nodes to become Ready
waitTimeout := 30 * time.Minute
switch platform {
case hyperv1.PowerVSPlatform:
waitTimeout = 60 * time.Minute
case hyperv1.KubevirtPlatform:
waitTimeout = 60 * time.Minute
}
t.Logf("Waiting for nodes to become ready. Want: %v", n)
nodes := &corev1.NodeList{}
readyNodeCount := 0
err := wait.PollImmediateWithContext(ctx, 5*time.Second, waitTimeout, func(ctx context.Context) (done bool, err error) {
err = client.List(ctx, nodes)
if err != nil {
return false, nil
}
var readyNodes []string
for _, node := range nodes.Items {
for _, cond := range node.Status.Conditions {
if cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {
readyNodes = append(readyNodes, node.Name)
g.Expect(node.Labels[hyperv1.NodePoolLabel]).NotTo(BeEmpty())
}
}
}
if len(readyNodes) != int(n) {
readyNodeCount = len(readyNodes)
return false, nil
}
t.Logf("All nodes are ready. Count: %v", len(nodes.Items))
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("failed to ensure guest nodes became ready, ready: (%d/%d): ", readyNodeCount, n))
t.Logf("All nodes for nodepool appear to be ready in %s. Count: %v", time.Since(start).Round(time.Second), n)
return nodes.Items
}
func WaitForNReadyNodesByNodePool(t *testing.T, ctx context.Context, client crclient.Client, n int32, platform hyperv1.PlatformType, nodePoolName string) []corev1.Node {
g := NewWithT(t)
start := time.Now()
// waitTimeout for nodes to become Ready
waitTimeout := 30 * time.Minute
switch platform {
case hyperv1.KubevirtPlatform:
waitTimeout = 45 * time.Minute
case hyperv1.PowerVSPlatform:
waitTimeout = 60 * time.Minute
}
t.Logf("Waiting for nodes to become ready by NodePool. NodePool: %s Want: %v", nodePoolName, n)
nodesFromNodePool := []corev1.Node{}
err := wait.PollImmediateWithContext(ctx, 5*time.Second, waitTimeout, func(ctx context.Context) (done bool, err error) {
nodes := &corev1.NodeList{}
err = client.List(ctx, nodes)
if err != nil {
return false, nil
}
if len(nodes.Items) == 0 {
return false, nil
}
for _, node := range nodes.Items {
if node.Labels["hypershift.openshift.io/nodePool"] == nodePoolName {
for _, cond := range node.Status.Conditions {
if cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {
nodesFromNodePool = append(nodesFromNodePool, node)
}
}
}
}
if len(nodesFromNodePool) != int(n) {
nodesFromNodePool = nil
return false, nil
}
t.Logf("All nodes are ready. Count: %v", len(nodesFromNodePool))
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("failed to ensure guest nodes became ready, ready: (%d/%d): ", len(nodesFromNodePool), n))
t.Logf("All nodes for NodePool %s appear to be ready in %s. Count: %v", nodePoolName, time.Since(start).Round(time.Second), n)
return nodesFromNodePool
}
func WaitForImageRollout(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster, image string) {
start := time.Now()
g := NewWithT(t)
var rolloutIncompleteReason, prevRolloutIncompleteReason string
t.Logf("Waiting for hostedcluster to rollout image. Namespace: %s, name: %s, image: %s", hostedCluster.Namespace, hostedCluster.Name, image)
err := wait.PollImmediateWithContext(ctx, 10*time.Second, 30*time.Minute, func(ctx context.Context) (done bool, err error) {
latest := hostedCluster.DeepCopy()
err = client.Get(ctx, crclient.ObjectKeyFromObject(latest), latest)
if err != nil {
t.Errorf("Failed to get hostedcluster: %v", err)
return false, nil
}
available := meta.FindStatusCondition(latest.Status.Conditions, string(hyperv1.HostedClusterAvailable))
progressing := meta.FindStatusCondition(latest.Status.Conditions, string(hyperv1.HostedClusterProgressing))
switch {
case available == nil:
rolloutIncompleteReason = fmt.Sprintf("status.conditions[type==%s] does not exist", hyperv1.HostedClusterAvailable)
case available.Status != metav1.ConditionTrue:
rolloutIncompleteReason = fmt.Sprintf("status.conditions[type==%s] %q (expected %q): %s %s: %s", available.Type, available.Status, metav1.ConditionTrue, available.LastTransitionTime, available.Reason, available.Message)
case progressing == nil:
rolloutIncompleteReason = fmt.Sprintf("status.conditions[type==%s] does not exist", hyperv1.HostedClusterProgressing)
case progressing.Status != metav1.ConditionFalse:
rolloutIncompleteReason = fmt.Sprintf("status.conditions[type==%s] %q (expected %q): %s %s: %s", progressing.Type, progressing.Status, metav1.ConditionFalse, progressing.LastTransitionTime, progressing.Reason, progressing.Message)
case latest.Status.Version == nil:
rolloutIncompleteReason = "nil status.version"
case latest.Status.Version.Desired.Image != image:
rolloutIncompleteReason = fmt.Sprintf("status.version.desired.image is %q, but we want %q", latest.Status.Version.Desired.Image, image)
case len(latest.Status.Version.History) == 0:
rolloutIncompleteReason = "status.version.history has no entries"
case latest.Status.Version.History[0].Image != latest.Status.Version.Desired.Image:
rolloutIncompleteReason = fmt.Sprintf("status.version.history[0].image is %q, but we want %q", latest.Status.Version.History[0].Image, latest.Status.Version.Desired.Image)
case latest.Status.Version.History[0].State != configv1.CompletedUpdate:
rolloutIncompleteReason = fmt.Sprintf("status.version.history[0].state is %q, but we want %q", latest.Status.Version.History[0].State, configv1.CompletedUpdate)
default:
rolloutIncompleteReason = ""
}
if rolloutIncompleteReason != "" {
if rolloutIncompleteReason != prevRolloutIncompleteReason {
prevRolloutIncompleteReason = rolloutIncompleteReason
t.Logf("Waiting for hostedcluster rollout. Image: %s: %s", image, rolloutIncompleteReason)
}
return false, nil
}
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("failed waiting for hostedcluster image rollout: %s", rolloutIncompleteReason))
t.Logf("Observed hostedcluster to have successfully rolled out image in %s. Namespace: %s, name: %s, image: %s", time.Since(start).Round(time.Second), hostedCluster.Namespace, hostedCluster.Name, image)
}
func WaitForConditionsOnHostedControlPlane(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster, image string) {
g := NewWithT(t)
start := time.Now()
conditions := []hyperv1.ConditionType{
hyperv1.HostedControlPlaneAvailable,
hyperv1.EtcdAvailable,
hyperv1.KubeAPIServerAvailable,
hyperv1.InfrastructureReady,
hyperv1.ValidHostedControlPlaneConfiguration,
}
var rolloutIncompleteReasons []string
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
t.Logf("Waiting for hostedcontrolplane to rollout image. Namespace: %s, name: %s, image: %s", namespace, hostedCluster.Name, image)
err := wait.PollImmediateWithContext(ctx, 10*time.Second, 30*time.Minute, func(ctx context.Context) (done bool, err error) {
cp := &hyperv1.HostedControlPlane{}
err = client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: hostedCluster.Name}, cp)
if err != nil {
t.Logf("Failed to get hostedcontrolplane: %v", err)
return false, nil
}
rolloutIncompleteReasons = make([]string, 0, len(conditions))
for _, conditionType := range conditions {
condition := meta.FindStatusCondition(cp.Status.Conditions, string(conditionType))
switch {
case condition == nil:
rolloutIncompleteReasons = append(rolloutIncompleteReasons, fmt.Sprintf("status.conditions[type==%s] does not exist", conditionType))
case condition.Status != metav1.ConditionTrue:
rolloutIncompleteReasons = append(rolloutIncompleteReasons, fmt.Sprintf("status.conditions[type==%s] %q (expected %q): %s %s: %s", condition.Type, condition.Status, metav1.ConditionTrue, condition.LastTransitionTime, condition.Reason, condition.Message))
}
}
if len(rolloutIncompleteReasons) > 0 {
t.Logf("Waiting for hostedcontrolplane rollout. Image: %s\n%s", image, strings.Join(rolloutIncompleteReasons, "\n"))
return false, nil
}
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("failed waiting for hostedcontrolplane image rollout\n%s", strings.Join(rolloutIncompleteReasons, "\n")))
t.Logf("Observed hostedcontrolplane to have successfully rolled out image in %s. Namespace: %s, name: %s, image: %s", time.Since(start).Round(time.Second), namespace, hostedCluster.Name, image)
}
// WaitForNodePoolVersion blocks until the NodePool status indicates the given
// version. If the context is closed before the version is observed, the given
// test will get an error.
func WaitForNodePoolVersion(t *testing.T, ctx context.Context, client crclient.Client, nodePool *hyperv1.NodePool, version string) {
g := NewWithT(t)
start := time.Now()
t.Logf("Waiting for nodepool %s/%s to report version %s (currently %s)", nodePool.Namespace, nodePool.Name, version, nodePool.Status.Version)
// TestInPlaceUpgradeNodePool must update nodes in the pool sequentially and it takes about 5m per node
// TestInPlaceUpgradeNodePool currently uses a single nodepool with 2 replicas so 20m should be enough time (2x expected)
err := wait.PollImmediateWithContext(ctx, 10*time.Second, 20*time.Minute, func(ctx context.Context) (done bool, err error) {
latest := nodePool.DeepCopy()
err = client.Get(ctx, crclient.ObjectKeyFromObject(nodePool), latest)
if err != nil {
t.Logf("Failed to get nodepool: %v", err)
return false, nil
}
return latest.Status.Version == version, nil
})
g.Expect(err).NotTo(HaveOccurred(), "failed waiting for nodepool version")
t.Logf("Observed nodepool %s/%s to report version %s in %s", nodePool.Namespace, nodePool.Name, version, time.Since(start).Round(time.Second))
}
func WaitForNodePoolDesiredNodes(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
g := NewWithT(t)
waitTimeout := 30 * time.Minute
err := wait.PollImmediateWithContext(ctx, 5*time.Second, waitTimeout, func(ctx context.Context) (done bool, err error) {
var nodePoolList hyperv1.NodePoolList
if err := client.List(ctx, &nodePoolList, &crclient.ListOptions{Namespace: hostedCluster.Namespace}); err != nil {
t.Fatalf("failed to list nodepools: %v", err)
}
for _, nodePool := range nodePoolList.Items {
if *nodePool.Spec.Replicas != nodePool.Status.Replicas {
t.Logf("Waiting. NodePool %q wants %v replicas but has %v", nodePool.Name, *nodePool.Spec.Replicas, nodePool.Status.Replicas)
return false, nil
}
}
return true, nil
})
g.Expect(err).NotTo(HaveOccurred(), "failed to ensure all NodePools' nodes ready")
}
func EnsureNoCrashingPods(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("EnsureNoCrashingPods", func(t *testing.T) {
var crashToleration int32
switch hostedCluster.Spec.Platform.Type {
case hyperv1.KubevirtPlatform:
kvPlatform := hostedCluster.Spec.Platform.Kubevirt
// External infra can be slow at times due to the nested nature
// of how external infra is tested within a kubevirt hcp running
// within baremetal ocp. Occasionally pods will fail with
// "Error: context deadline exceeded" reported by the kubelet. This
// seems to be an infra issue with etcd latency within the external
// infra test environment. Tolerating a single restart for random
// components helps.
//
// This toleration is not used for the default local HCP KubeVirt,
// only external infra
if kvPlatform != nil && kvPlatform.Credentials != nil {
crashToleration = 1
}
// In Azure infra, CAPK pod might crash on startup due to not being able to
// get a leader election lock lease at the early stages, due to
// "context deadline exceeded" error
if kvPlatform != nil && hostedCluster.Annotations != nil {
mgmtPlatform, annotationExists := hostedCluster.Annotations[hyperv1.ManagementPlatformAnnotation]
if annotationExists && mgmtPlatform == string(hyperv1.AzurePlatform) {
crashToleration = 1
}
}
default:
crashToleration = 0
}
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
var podList corev1.PodList
if err := client.List(ctx, &podList, crclient.InNamespace(namespace)); err != nil {
t.Fatalf("failed to list pods in namespace %s: %v", namespace, err)
}
for _, pod := range podList.Items {
// TODO: Figure out why Route kind does not exist when ingress-operator first starts
if strings.HasPrefix(pod.Name, "ingress-operator-") {
continue
}
// Seeing flakes due to https://issues.redhat.com/browse/OCPBUGS-30068
if strings.HasPrefix(pod.Name, "cloud-credential-operator-") {
continue
}
// Restart built into OLM by design by
// https://github.com/openshift/operator-framework-olm/commit/1cf358424a0cbe353428eab9a16051c6cabbd002
if strings.HasPrefix(pod.Name, "olm-operator-") {
continue
}
if strings.HasPrefix(pod.Name, "catalog-operator-") {
continue
}
if strings.Contains(pod.Name, "-catalog") {
continue
}
// Temporary workaround for https://issues.redhat.com/browse/CNV-40820
if strings.HasPrefix(pod.Name, "kubevirt-csi") {
continue
}
for _, containerStatus := range pod.Status.ContainerStatuses {
if containerStatus.RestartCount > crashToleration {
t.Errorf("Container %s in pod %s has a restartCount > 0 (%d)", containerStatus.Name, pod.Name, containerStatus.RestartCount)
}
}
}
})
}
func NoticePreemptionOrFailedScheduling(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("NoticePreemptionOrFailedScheduling", func(t *testing.T) {
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
var eventList corev1.EventList
if err := client.List(ctx, &eventList, crclient.InNamespace(namespace)); err != nil {
t.Fatalf("failed to list events in namespace %s: %v", namespace, err)
}
for _, event := range eventList.Items {
if event.Reason == "FailedScheduling" || event.Reason == "Preempted" {
// "error: " is to trigger prow syntax highlight in prow
t.Logf("error: non-fatal, observed FailedScheduling or Preempted event: %s", event.Message)
}
}
})
}
func EnsureNoPodsWithTooHighPriority(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
// Priority of the etcd priority class, nothing should ever exceed this.
const maxAllowedPriority = 100002000
t.Run("EnsureNoPodsWithTooHighPriority", func(t *testing.T) {
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
var podList corev1.PodList
if err := client.List(ctx, &podList, crclient.InNamespace(namespace)); err != nil {
t.Fatalf("failed to list pods in namespace %s: %v", namespace, err)
}
for _, pod := range podList.Items {
// Bandaid until this is fixed in the CNO
if strings.HasPrefix(pod.Name, "multus-admission-controller") {
continue
}
if pod.Spec.Priority != nil && *pod.Spec.Priority > maxAllowedPriority {
t.Errorf("pod %s with priorityClassName %s has a priority of %d with exceeds the max allowed of %d", pod.Name, pod.Spec.PriorityClassName, *pod.Spec.Priority, maxAllowedPriority)
}
}
})
}
func EnsureAllContainersHavePullPolicyIfNotPresent(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("EnsureAllContainersHavePullPolicyIfNotPresent", func(t *testing.T) {
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
var podList corev1.PodList
if err := client.List(ctx, &podList, crclient.InNamespace(namespace)); err != nil {
t.Fatalf("failed to list pods in namespace %s: %v", namespace, err)
}
for _, pod := range podList.Items {
for _, initContainer := range pod.Spec.InitContainers {
if initContainer.ImagePullPolicy != corev1.PullIfNotPresent {
t.Errorf("container %s in pod %s has doesn't have imagePullPolicy %s but %s", initContainer.Name, pod.Name, corev1.PullIfNotPresent, initContainer.ImagePullPolicy)
}
}
for _, container := range pod.Spec.Containers {
if container.ImagePullPolicy != corev1.PullIfNotPresent {
t.Errorf("container %s in pod %s has doesn't have imagePullPolicy %s but %s", container.Name, pod.Name, corev1.PullIfNotPresent, container.ImagePullPolicy)
}
}
}
})
}
func EnsureNodeCountMatchesNodePoolReplicas(t *testing.T, ctx context.Context, hostClient, guestClient crclient.Client, nodePoolNamespace string) {
t.Run("EnsureNodeCountMatchesNodePoolReplicas", func(t *testing.T) {
var nodePoolList hyperv1.NodePoolList
if err := hostClient.List(ctx, &nodePoolList, &crclient.ListOptions{Namespace: nodePoolNamespace}); err != nil {
t.Fatalf("failed to list nodepools: %v", err)
}
replicas := 0
for _, nodePool := range nodePoolList.Items {
replicas = replicas + int(*nodePool.Spec.Replicas)
}
var nodes corev1.NodeList
if err := guestClient.List(ctx, &nodes); err != nil {
t.Fatalf("failed to list nodes in guest cluster: %v", err)
}
if replicas != len(nodes.Items) {
t.Errorf("nodepool replicas %d does not match number of nodes in cluster %d", replicas, len(nodes.Items))
}
})
}
func EnsureMachineDeploymentGeneration(t *testing.T, ctx context.Context, hostClient crclient.Client, hostedCluster *hyperv1.HostedCluster, expectedGeneration int64) {
t.Run("EnsureMachineDeploymentGeneration", func(t *testing.T) {
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
var machineDeploymentList capiv1.MachineDeploymentList
if err := hostClient.List(ctx, &machineDeploymentList, crclient.InNamespace(namespace)); err != nil {
t.Fatalf("failed to list machinedeployments: %v", err)
}
for _, machineDeployment := range machineDeploymentList.Items {
if machineDeployment.Generation != expectedGeneration {
t.Errorf("machineDeployment %s does not have expected generation %d but %d", crclient.ObjectKeyFromObject(&machineDeployment), expectedGeneration, machineDeployment.Generation)
}
}
})
}
func EnsurePSANotPrivileged(t *testing.T, ctx context.Context, guestClient crclient.Client) {
t.Run("EnsurePSANotPrivileged", func(t *testing.T) {
testNamespaceName := "e2e-psa-check"
namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: testNamespaceName,
},
}
if err := guestClient.Create(ctx, namespace); err != nil {
t.Fatalf("failed to create namespace: %v", err)
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
Namespace: testNamespaceName,
},
Spec: corev1.PodSpec{
NodeSelector: map[string]string{
"e2e.openshift.io/unschedulable": "should-not-run",
},
Containers: []corev1.Container{
{Name: "first", Image: "something-innocuous"},
},
HostPID: true, // enforcement of restricted or baseline policy should reject this
},
}
err := guestClient.Create(ctx, pod)
if err == nil {
t.Errorf("pod admitted when rejection was expected")
}
if !kapierror.IsForbidden(err) {
t.Errorf("forbidden error expected, got %s", err)
}
})
}
func EnsureAPIBudget(t *testing.T, ctx context.Context, client crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("EnsureAPIBudget", func(t *testing.T) {
// Get hypershift-operator token
operatorServiceAccount := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: "operator",
Namespace: "hypershift",
},
}
if err := client.Get(ctx, crclient.ObjectKeyFromObject(operatorServiceAccount), operatorServiceAccount); err != nil {
t.Fatalf("failed to get hypershift operator service account: %v", err)
}
var secretName string
for _, secret := range operatorServiceAccount.Secrets {
if strings.HasPrefix(secret.Name, "operator-token-") {
secretName = secret.Name
break
}
}
token, err := getPrometheusToken(ctx, secretName, client)
if err != nil {
t.Fatalf("can't get token for Prometheus; %v", err)
}
// Get thanos-querier endpoint
promRoute := &routev1.Route{
ObjectMeta: metav1.ObjectMeta{
Name: "thanos-querier",
Namespace: "openshift-monitoring",
},
}
if err = client.Get(ctx, crclient.ObjectKeyFromObject(promRoute), promRoute); err != nil {
t.Skip("unable to get prometheus route, skipping")
}
if len(promRoute.Status.Ingress) == 0 {
t.Skip("unable to get prometheus ingress, skipping")
}
promEndpoint := fmt.Sprintf("https://%s", promRoute.Status.Ingress[0].Host)
// Create prometheus client
cfg := promconfig.HTTPClientConfig{
Authorization: &promconfig.Authorization{
Type: "Bearer",
Credentials: promconfig.Secret(token),
},
TLSConfig: promconfig.TLSConfig{
InsecureSkipVerify: true,
},
}
rt, err := promconfig.NewRoundTripperFromConfig(cfg, "e2e-budget-checker")
if err != nil {
t.Fatalf("failed to get create round tripper: %v", err)
}
promClient, err := promapi.NewClient(promapi.Config{
Address: promEndpoint,
RoundTripper: rt,
})
if err != nil {
t.Fatalf("failed to get create prometheus client: %v", err)
}
v1api := promv1.NewAPI(promClient)
// Compare metrics against budgets
namespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
clusterAgeMinutes := int32(time.Since(hostedCluster.CreationTimestamp.Time).Round(time.Minute).Minutes())
budgets := []struct {
name string
query string
budget float64
}{
{
name: "control-plane-operator read",
query: fmt.Sprintf(`sum by (pod) (max_over_time(hypershift:controlplane:component_api_requests_total{app="control-plane-operator", method="GET", namespace=~"%s"}[%dm]))`, namespace, clusterAgeMinutes),
budget: 4000,
},
{
name: "control-plane-operator mutate",
query: fmt.Sprintf(`sum by (pod) (max_over_time(hypershift:controlplane:component_api_requests_total{app="control-plane-operator", method!="GET", namespace=~"%s"}[%dm]))`, namespace, clusterAgeMinutes),
budget: 4200,
},
{
name: "control-plane-operator no 404 deletes",
query: fmt.Sprintf(`sum by (pod) (max_over_time(hypershift:controlplane:component_api_requests_total{app="control-plane-operator", method="DELETE", code="404", namespace=~"%s"}[%dm]))`, namespace, clusterAgeMinutes),
budget: 50,
},
// {
// name: "ignition-server p90 payload generation time",
// query: fmt.Sprintf(`sum by (namespace) (max_over_time(hypershift:controlplane:ign_payload_generation_seconds_p90{namespace="%s"}[%dm]))`, namespace, clusterAgeMinutes),
// budget: 45,
// },
// hypershift-operator budget can not be per HC so metric will be
// significantly under budget for all but the last test(s) to complete on
// a particular test cluster These budgets will also need to scale up with
// additional tests that create HostedClusters
{
name: "hypershift-operator read",
query: `sum(hypershift:operator:component_api_requests_total{method="GET"})`,
budget: 7000,
},
{
name: "hypershift-operator mutate",
query: `sum(hypershift:operator:component_api_requests_total{method!="GET"})`,
budget: 20000,
},
{
name: "hypershift-operator no 404 deletes",
query: `sum(hypershift:operator:component_api_requests_total{method="DELETE", code="404"})`,
budget: 50,
},
}
for _, budget := range budgets {
t.Run(budget.name, func(t *testing.T) {
result, _, err := v1api.Query(ctx, budget.query, time.Now())
if err != nil {
t.Fatalf("failed to query prometheus: %v", err)
}
vector, ok := result.(prommodel.Vector)
if !ok {
t.Fatal("expected vector result")
}
if len(vector) == 0 {
if budget.budget <= 50 {
t.Log("no samples returned for query with small budget, skipping check")
} else {
t.Errorf("no samples returned for query with large budget, failed check")
}
}
for _, sample := range vector {
podMsg := ""
if podName, ok := sample.Metric["pod"]; ok {
podMsg = fmt.Sprintf("pod %s ", podName)
}
if float64(sample.Value) > budget.budget {
t.Errorf("%sover budget: budget: %.0f, actual: %.0f", podMsg, budget.budget, sample.Value)
} else {
t.Logf("%swithin budget: budget: %.0f, actual: %.0f", podMsg, budget.budget, sample.Value)
}
}
})
}
})
}
func EnsureAllRoutesUseHCPRouter(t *testing.T, ctx context.Context, hostClient crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("EnsureAllRoutesUseHCPRouter", func(t *testing.T) {
for _, svc := range hostedCluster.Spec.Services {
if svc.Service == hyperv1.APIServer && svc.Type != hyperv1.Route {
t.Skip("skipping test because APIServer is not exposed through a route")
}
}
var routes routev1.RouteList
if err := hostClient.List(ctx, &routes, crclient.InNamespace(manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name))); err != nil {
t.Fatalf("failed to list routes: %v", err)
}
for _, route := range routes.Items {
original := route.DeepCopy()
util.AddHCPRouteLabel(&route)
if diff := cmp.Diff(route.GetLabels(), original.GetLabels()); diff != "" {
t.Errorf("route %s is missing the label to use the per-HCP router: %s", route.Name, diff)
}
}
})
}
func EnsureNetworkPolicies(t *testing.T, ctx context.Context, c crclient.Client, hostedCluster *hyperv1.HostedCluster) {
t.Run("EnsureNetworkPolicies", func(t *testing.T) {
if hostedCluster.Spec.Platform.Type != hyperv1.AWSPlatform {
t.Skip()
}
hcpNamespace := manifests.HostedControlPlaneNamespace(hostedCluster.Namespace, hostedCluster.Name)
t.Run("EnsureComponentsHaveNeedManagementKASAccessLabel", func(t *testing.T) {
g := NewWithT(t)
err := checkPodsHaveLabel(ctx, c, expectedKasManagementComponents, hcpNamespace, client.MatchingLabels{suppconfig.NeedManagementKASAccessLabel: "true"})
g.Expect(err).ToNot(HaveOccurred())
})
t.Run("EnsureLimitedEgressTrafficToManagementKAS", func(t *testing.T) {
g := NewWithT(t)
kubernetesEndpoint := &corev1.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes", Namespace: "default"}}
err := c.Get(ctx, client.ObjectKeyFromObject(kubernetesEndpoint), kubernetesEndpoint)
g.Expect(err).ToNot(HaveOccurred())
kasAddress := ""
for _, subset := range kubernetesEndpoint.Subsets {
if len(subset.Addresses) > 0 && len(subset.Ports) > 0 {
kasAddress = fmt.Sprintf("https://%s:%v", subset.Addresses[0].IP, subset.Ports[0].Port)
break
}
}
t.Logf("Connecting to kubernetes endpoint on: %s", kasAddress)
command := []string{
"curl",
"--connect-timeout",
"2",
"-Iks",
// Default KAS advertised address.
kasAddress,
}
// Validate cluster-version-operator is not allowed to access management KAS.
stdOut, err := RunCommandInPod(ctx, c, "cluster-version-operator", hcpNamespace, command, "cluster-version-operator")
g.Expect(err).To(HaveOccurred())
// Expect curl to timeout https://curl.se/docs/manpage.html (exit code 28).
if err != nil && !strings.Contains(err.Error(), "command terminated with exit code 28") {
t.Errorf("cluster version pod was unexpectedly allowed to reach the management KAS. stdOut: %s. stdErr: %s", stdOut, err.Error())
}
// Validate private router is not allowed to access management KAS.
if hostedCluster.Spec.Platform.Type == hyperv1.AWSPlatform {
if hostedCluster.Spec.Platform.AWS.EndpointAccess != hyperv1.Private {
// TODO (alberto): Run also in private case. Today it results in a flake:
// === CONT TestCreateClusterPrivate/EnsureHostedCluster/EnsureNetworkPolicies/EnsureLimitedEgressTrafficToManagementKAS
// util.go:851: private router pod was unexpectedly allowed to reach the management KAS. stdOut: . stdErr: Internal error occurred: error executing command in container: container is not created or running
// Should be solve with https://issues.redhat.com/browse/HOSTEDCP-1200
stdOut, err := RunCommandInPod(ctx, c, "private-router", hcpNamespace, command, "private-router")
g.Expect(err).To(HaveOccurred())
// Expect curl to timeout https://curl.se/docs/manpage.html (exit code 28).
if err != nil && !strings.Contains(err.Error(), "command terminated with exit code 28") {
t.Errorf("private router pod was unexpectedly allowed to reach the management KAS. stdOut: %s. stdErr: %s", stdOut, err.Error())
}
}
}
// Validate cluster api is allowed to access management KAS.
stdOut, err = RunCommandInPod(ctx, c, "cluster-api", hcpNamespace, command, "manager")
// Expect curl return a 403 from the KAS.
if !strings.Contains(stdOut, "HTTP/2 403") || err != nil {
t.Errorf("cluster api pod was unexpectedly not allowed to reach the management KAS. stdOut: %s. stdErr: %s", stdOut, err.Error())
}
})
})
}
func getComponentName(pod *corev1.Pod) string {
if pod.Labels["app"] != "" {
return pod.Labels["app"]
}
if pod.Labels["name"] != "" {
return pod.Labels["name"]
}
if strings.HasPrefix(pod.Labels["job-name"], "olm-collect-profiles") {
return "olm-collect-profiles"
}
return ""
}
func checkPodsHaveLabel(ctx context.Context, c crclient.Client, allowedComponents []string, namespace string, labels map[string]string) error {
// Get all Pods with wanted label.
podList := &corev1.PodList{}
err := c.List(ctx, podList, client.InNamespace(namespace), client.MatchingLabels(labels))
if err != nil {
return fmt.Errorf("failed to list pods: %w", err)
}
// Get the component name for each labelled pod and ensure it exists in the components slice
for _, pod := range podList.Items {
if pod.Labels[suppconfig.NeedManagementKASAccessLabel] == "" {
continue
}
componentName := getComponentName(&pod)
if componentName == "" {
return fmt.Errorf("unable to determine component name for pod that has NeedManagementKASAccessLabel: %s", pod.Name)
}
allowed := false
for _, component := range allowedComponents {
if component == componentName {
allowed = true
break
}
}
if !allowed {
return fmt.Errorf("NeedManagementKASAccessLabel label is not allowed on component: %s", componentName)
}
}
return nil
}
func RunCommandInPod(ctx context.Context, c crclient.Client, component, namespace string, command []string, containerName string) (string, error) {
podList := &corev1.PodList{}
if err := c.List(ctx, podList,
client.InNamespace(namespace),
client.MatchingLabels{"app": component}); err != nil {
return "", fmt.Errorf("failed to list Pods: %w", err)
}
if len(podList.Items) < 1 {
return "", fmt.Errorf("pods for component %q not found", component)
}
restConfig, err := GetConfig()
if err != nil {
return "", fmt.Errorf("failed to get restConfig; %w", err)
}
stdOut := new(bytes.Buffer)
podExecuter := PodExecOptions{
StreamOptions: StreamOptions{
IOStreams: genericclioptions.IOStreams{
Out: stdOut,
ErrOut: os.Stderr,
},
},
Command: command,
Namespace: namespace,
PodName: podList.Items[0].Name,
Config: restConfig,
ContainerName: containerName,
}
err = podExecuter.Run()
return stdOut.String(), err
}
func getPrometheusToken(ctx context.Context, secretName string, client crclient.Client) ([]byte, error) {
if secretName == "" {
return createPrometheusToken(ctx)
} else {
return getTokenFromSecret(ctx, secretName, client)
}
}
func createPrometheusToken(ctx context.Context) ([]byte, error) {
cli, err := createK8sClient()
if err != nil {
return nil, err
}
tokenReq, err := cli.CoreV1().ServiceAccounts("openshift-monitoring").CreateToken(
ctx,
"prometheus-k8s",
&authenticationv1.TokenRequest{
Spec: authenticationv1.TokenRequestSpec{
// Avoid specifying any audiences so that the token will be
// issued for the default audience of the issuer.
},
},
metav1.CreateOptions{},
)
if err != nil {
return nil, fmt.Errorf("failed to create token; %w", err)
}
return []byte(tokenReq.Status.Token), nil
}