-
Notifications
You must be signed in to change notification settings - Fork 934
/
expectations.go
904 lines (796 loc) · 34.3 KB
/
expectations.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
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package common
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"math"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
appsv1 "k8s.io/api/apps/v1"
coordinationv1 "k8s.io/api/coordination/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/transport"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
corev1beta1 "sigs.k8s.io/karpenter/pkg/apis/v1beta1"
pscheduling "sigs.k8s.io/karpenter/pkg/controllers/provisioning/scheduling"
"sigs.k8s.io/karpenter/pkg/scheduling"
"sigs.k8s.io/karpenter/pkg/test"
)
func (env *Environment) ExpectCreated(objects ...client.Object) {
GinkgoHelper()
for _, object := range objects {
Eventually(func(g Gomega) {
object.SetLabels(lo.Assign(object.GetLabels(), map[string]string{
test.DiscoveryLabel: "unspecified",
}))
g.Expect(env.Client.Create(env, object)).To(Succeed())
}).WithTimeout(time.Second * 10).Should(Succeed())
}
}
func (env *Environment) ExpectDeleted(objects ...client.Object) {
GinkgoHelper()
for _, object := range objects {
Eventually(func(g Gomega) {
g.Expect(client.IgnoreNotFound(env.Client.Delete(env, object, client.PropagationPolicy(metav1.DeletePropagationForeground), &client.DeleteOptions{GracePeriodSeconds: ptr.Int64(0)}))).To(Succeed())
}).WithTimeout(time.Second * 10).Should(Succeed())
}
}
// ExpectUpdated will update objects in the cluster to match the inputs.
// WARNING: This ignores the resource version check, which can result in
// overwriting changes made by other controllers in the cluster.
// This is useful in ensuring that we can clean up resources by patching
// out finalizers.
// Grab the object before making the updates to reduce the chance of this race.
func (env *Environment) ExpectUpdated(objects ...client.Object) {
GinkgoHelper()
for _, o := range objects {
Eventually(func(g Gomega) {
current := o.DeepCopyObject().(client.Object)
g.Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(current), current)).To(Succeed())
if current.GetResourceVersion() != o.GetResourceVersion() {
logging.FromContext(env).Infof("detected an update to an object (%s) with an outdated resource version, did you get the latest version of the object before patching?", lo.Must(apiutil.GVKForObject(o, env.Client.Scheme())))
}
o.SetResourceVersion(current.GetResourceVersion())
g.Expect(env.Client.Update(env.Context, o)).To(Succeed())
}).WithTimeout(time.Second * 10).Should(Succeed())
}
}
// ExpectCreatedOrUpdated can update objects in the cluster to match the inputs.
// WARNING: ExpectUpdated ignores the resource version check, which can result in
// overwriting changes made by other controllers in the cluster.
// This is useful in ensuring that we can clean up resources by patching
// out finalizers.
// Grab the object before making the updates to reduce the chance of this race.
func (env *Environment) ExpectCreatedOrUpdated(objects ...client.Object) {
GinkgoHelper()
for _, o := range objects {
current := o.DeepCopyObject().(client.Object)
err := env.Client.Get(env, client.ObjectKeyFromObject(current), current)
if err != nil {
if errors.IsNotFound(err) {
env.ExpectCreated(o)
} else {
Fail(fmt.Sprintf("Getting object %s, %v", client.ObjectKeyFromObject(o), err))
}
} else {
env.ExpectUpdated(o)
}
}
}
func (env *Environment) ExpectSettings() (res []v1.EnvVar) {
GinkgoHelper()
d := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Namespace: "kube-system", Name: "karpenter"}, d)).To(Succeed())
Expect(d.Spec.Template.Spec.Containers).To(HaveLen(1))
return lo.Map(d.Spec.Template.Spec.Containers[0].Env, func(v v1.EnvVar, _ int) v1.EnvVar {
return *v.DeepCopy()
})
}
func (env *Environment) ExpectSettingsReplaced(vars ...v1.EnvVar) {
GinkgoHelper()
d := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Namespace: "kube-system", Name: "karpenter"}, d)).To(Succeed())
Expect(d.Spec.Template.Spec.Containers).To(HaveLen(1))
stored := d.DeepCopy()
d.Spec.Template.Spec.Containers[0].Env = vars
if !equality.Semantic.DeepEqual(d, stored) {
By("replacing environment variables for karpenter deployment")
Expect(env.Client.Patch(env.Context, d, client.StrategicMergeFrom(stored))).To(Succeed())
env.EventuallyExpectKarpenterRestarted()
}
}
func (env *Environment) ExpectSettingsOverridden(vars ...v1.EnvVar) {
GinkgoHelper()
d := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Namespace: "kube-system", Name: "karpenter"}, d)).To(Succeed())
Expect(d.Spec.Template.Spec.Containers).To(HaveLen(1))
stored := d.DeepCopy()
for _, v := range vars {
if _, i, ok := lo.FindIndexOf(d.Spec.Template.Spec.Containers[0].Env, func(e v1.EnvVar) bool {
return e.Name == v.Name
}); ok {
d.Spec.Template.Spec.Containers[0].Env[i] = v
} else {
d.Spec.Template.Spec.Containers[0].Env = append(d.Spec.Template.Spec.Containers[0].Env, v)
}
}
if !equality.Semantic.DeepEqual(d, stored) {
By("overriding environment variables for karpenter deployment")
Expect(env.Client.Patch(env.Context, d, client.StrategicMergeFrom(stored))).To(Succeed())
env.EventuallyExpectKarpenterRestarted()
}
}
func (env *Environment) ExpectSettingsRemoved(vars ...v1.EnvVar) {
GinkgoHelper()
varNames := sets.New[string](lo.Map(vars, func(v v1.EnvVar, _ int) string { return v.Name })...)
d := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Namespace: "kube-system", Name: "karpenter"}, d)).To(Succeed())
Expect(d.Spec.Template.Spec.Containers).To(HaveLen(1))
stored := d.DeepCopy()
d.Spec.Template.Spec.Containers[0].Env = lo.Reject(d.Spec.Template.Spec.Containers[0].Env, func(v v1.EnvVar, _ int) bool {
return varNames.Has(v.Name)
})
if !equality.Semantic.DeepEqual(d, stored) {
By("removing environment variables for karpenter deployment")
Expect(env.Client.Patch(env.Context, d, client.StrategicMergeFrom(stored))).To(Succeed())
env.EventuallyExpectKarpenterRestarted()
}
}
func (env *Environment) ExpectConfigMapExists(key types.NamespacedName) *v1.ConfigMap {
GinkgoHelper()
cm := &v1.ConfigMap{}
Expect(env.Client.Get(env, key, cm)).To(Succeed())
return cm
}
func (env *Environment) ExpectConfigMapDataReplaced(key types.NamespacedName, data ...map[string]string) (changed bool) {
GinkgoHelper()
cm := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
}
err := env.Client.Get(env, key, cm)
Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred())
stored := cm.DeepCopy()
cm.Data = lo.Assign(data...) // Completely replace the data
// If the data hasn't changed, we can just return and not update anything
if equality.Semantic.DeepEqual(stored, cm) {
return false
}
// Update the configMap to update the settings
env.ExpectCreatedOrUpdated(cm)
return true
}
func (env *Environment) ExpectConfigMapDataOverridden(key types.NamespacedName, data ...map[string]string) (changed bool) {
GinkgoHelper()
cm := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
}
err := env.Client.Get(env, key, cm)
Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred())
stored := cm.DeepCopy()
cm.Data = lo.Assign(append([]map[string]string{cm.Data}, data...)...)
// If the data hasn't changed, we can just return and not update anything
if equality.Semantic.DeepEqual(stored, cm) {
return false
}
// Update the configMap to update the settings
env.ExpectCreatedOrUpdated(cm)
return true
}
func (env *Environment) ExpectPodENIEnabled() {
GinkgoHelper()
env.ExpectDaemonSetEnvironmentVariableUpdated(types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_POD_ENI", "true", "aws-node")
}
func (env *Environment) ExpectPodENIDisabled() {
GinkgoHelper()
env.ExpectDaemonSetEnvironmentVariableUpdated(types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_POD_ENI", "false", "aws-node")
}
func (env *Environment) ExpectPrefixDelegationEnabled() {
GinkgoHelper()
env.ExpectDaemonSetEnvironmentVariableUpdated(types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_PREFIX_DELEGATION", "true", "aws-node")
}
func (env *Environment) ExpectPrefixDelegationDisabled() {
GinkgoHelper()
env.ExpectDaemonSetEnvironmentVariableUpdated(types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_PREFIX_DELEGATION", "false", "aws-node")
}
func (env *Environment) ExpectExists(obj client.Object) client.Object {
GinkgoHelper()
Eventually(func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(obj), obj)).To(Succeed())
}).WithTimeout(time.Second * 5).Should(Succeed())
return obj
}
func (env *Environment) EventuallyExpectBound(pods ...*v1.Pod) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, pod := range pods {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(pod), pod)).To(Succeed())
g.Expect(pod.Spec.NodeName).ToNot(BeEmpty())
}
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectHealthy(pods ...*v1.Pod) {
GinkgoHelper()
env.EventuallyExpectHealthyWithTimeout(-1, pods...)
}
func (env *Environment) EventuallyExpectHealthyWithTimeout(timeout time.Duration, pods ...*v1.Pod) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, pod := range pods {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(pod), pod)).To(Succeed())
g.Expect(pod.Status.Conditions).To(ContainElement(And(
HaveField("Type", Equal(v1.PodReady)),
HaveField("Status", Equal(v1.ConditionTrue)),
)))
}
}).WithTimeout(timeout).Should(Succeed())
}
func (env *Environment) EventuallyExpectKarpenterRestarted() {
GinkgoHelper()
By("rolling out the new karpenter deployment")
env.EventuallyExpectRollout("karpenter", "kube-system")
env.ExpectKarpenterLeaseOwnerChanged()
}
func (env *Environment) ExpectKarpenterLeaseOwnerChanged() {
GinkgoHelper()
By("waiting for a new karpenter pod to hold the lease")
pods := env.ExpectKarpenterPods()
Eventually(func(g Gomega) {
name := env.ExpectActiveKarpenterPodName()
g.Expect(lo.ContainsBy(pods, func(p *v1.Pod) bool {
return p.Name == name
})).To(BeTrue())
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectRollout(name, namespace string) {
GinkgoHelper()
By("restarting the deployment")
deploy := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: name, Namespace: namespace}, deploy)).To(Succeed())
stored := deploy.DeepCopy()
restartedAtAnnotation := map[string]string{
"kubectl.kubernetes.io/restartedAt": time.Now().Format(time.RFC3339),
}
deploy.Spec.Template.Annotations = lo.Assign(deploy.Spec.Template.Annotations, restartedAtAnnotation)
Expect(env.Client.Patch(env.Context, deploy, client.StrategicMergeFrom(stored))).To(Succeed())
By("waiting for the newly generated deployment to rollout")
Eventually(func(g Gomega) {
podList := &v1.PodList{}
g.Expect(env.Client.List(env.Context, podList, client.InNamespace(namespace))).To(Succeed())
pods := lo.Filter(podList.Items, func(p v1.Pod, _ int) bool {
return p.Annotations["kubectl.kubernetes.io/restartedAt"] == restartedAtAnnotation["kubectl.kubernetes.io/restartedAt"]
})
g.Expect(len(pods)).To(BeNumerically("==", lo.FromPtr(deploy.Spec.Replicas)))
for _, pod := range pods {
g.Expect(pod.Status.Conditions).To(ContainElement(And(
HaveField("Type", Equal(v1.PodReady)),
HaveField("Status", Equal(v1.ConditionTrue)),
)))
g.Expect(pod.Status.Phase).To(Equal(v1.PodRunning))
}
}).Should(Succeed())
}
func (env *Environment) ExpectKarpenterPods() []*v1.Pod {
GinkgoHelper()
podList := &v1.PodList{}
Expect(env.Client.List(env.Context, podList, client.MatchingLabels{
"app.kubernetes.io/instance": "karpenter",
})).To(Succeed())
return lo.Map(podList.Items, func(p v1.Pod, _ int) *v1.Pod { return &p })
}
func (env *Environment) ExpectActiveKarpenterPodName() string {
GinkgoHelper()
lease := &coordinationv1.Lease{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: "karpenter-leader-election", Namespace: "kube-system"}, lease)).To(Succeed())
// Holder identity for lease is always in the format "<pod-name>_<pseudo-random-value>
holderArr := strings.Split(lo.FromPtr(lease.Spec.HolderIdentity), "_")
Expect(len(holderArr)).To(BeNumerically(">", 0))
return holderArr[0]
}
func (env *Environment) ExpectActiveKarpenterPod() *v1.Pod {
GinkgoHelper()
podName := env.ExpectActiveKarpenterPodName()
pod := &v1.Pod{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: podName, Namespace: "kube-system"}, pod)).To(Succeed())
return pod
}
func (env *Environment) EventuallyExpectPendingPodCount(selector labels.Selector, numPods int) {
GinkgoHelper()
Eventually(func(g Gomega) {
g.Expect(env.Monitor.PendingPodsCount(selector)).To(Equal(numPods))
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectBoundPodCount(selector labels.Selector, numPods int) []*v1.Pod {
GinkgoHelper()
var res []*v1.Pod
Eventually(func(g Gomega) {
res = []*v1.Pod{}
podList := &v1.PodList{}
g.Expect(env.Client.List(env.Context, podList, client.MatchingLabelsSelector{Selector: selector})).To(Succeed())
for i := range podList.Items {
if podList.Items[i].Spec.NodeName != "" {
res = append(res, &podList.Items[i])
}
}
g.Expect(res).To(HaveLen(numPods))
}).Should(Succeed())
return res
}
func (env *Environment) EventuallyExpectHealthyPodCount(selector labels.Selector, numPods int) []*v1.Pod {
By(fmt.Sprintf("waiting for %d pods matching selector %s to be ready", numPods, selector.String()))
GinkgoHelper()
return env.EventuallyExpectHealthyPodCountWithTimeout(-1, selector, numPods)
}
func (env *Environment) EventuallyExpectHealthyPodCountWithTimeout(timeout time.Duration, selector labels.Selector, numPods int) []*v1.Pod {
GinkgoHelper()
var pods []*v1.Pod
Eventually(func(g Gomega) {
pods = env.Monitor.RunningPods(selector)
g.Expect(pods).To(HaveLen(numPods))
}).WithTimeout(timeout).Should(Succeed())
return pods
}
func (env *Environment) ExpectPodsMatchingSelector(selector labels.Selector) []*v1.Pod {
GinkgoHelper()
podList := &v1.PodList{}
Expect(env.Client.List(env.Context, podList, client.MatchingLabelsSelector{Selector: selector})).To(Succeed())
return lo.ToSlicePtr(podList.Items)
}
func (env *Environment) EventuallyExpectUniqueNodeNames(selector labels.Selector, uniqueNames int) {
GinkgoHelper()
Eventually(func(g Gomega) {
pods := env.Monitor.RunningPods(selector)
nodeNames := sets.NewString()
for _, pod := range pods {
nodeNames.Insert(pod.Spec.NodeName)
}
g.Expect(len(nodeNames)).To(BeNumerically("==", uniqueNames))
}).Should(Succeed())
}
func (env *Environment) eventuallyExpectScaleDown() {
GinkgoHelper()
Eventually(func(g Gomega) {
// expect the current node count to be what it was when the test started
g.Expect(env.Monitor.NodeCount()).To(Equal(env.StartingNodeCount))
}).Should(Succeed(), fmt.Sprintf("expected scale down to %d nodes, had %d", env.StartingNodeCount, env.Monitor.NodeCount()))
}
func (env *Environment) EventuallyExpectNotFound(objects ...client.Object) {
GinkgoHelper()
env.EventuallyExpectNotFoundAssertion(objects...).Should(Succeed())
}
func (env *Environment) EventuallyExpectNotFoundAssertion(objects ...client.Object) AsyncAssertion {
return Eventually(func(g Gomega) {
for _, object := range objects {
err := env.Client.Get(env, client.ObjectKeyFromObject(object), object)
g.Expect(errors.IsNotFound(err)).To(BeTrue())
}
})
}
func (env *Environment) ExpectCreatedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
createdNodes := env.Monitor.CreatedNodes()
Expect(len(createdNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d created nodes, had %d (%v)", count, len(createdNodes), NodeNames(createdNodes)))
return createdNodes
}
func (env *Environment) ExpectNodeCount(comparator string, count int) {
GinkgoHelper()
nodeList := &v1.NodeList{}
Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
Expect(len(nodeList.Items)).To(BeNumerically(comparator, count))
}
func (env *Environment) ExpectNodeClaimCount(comparator string, count int) {
GinkgoHelper()
nodeClaimList := &corev1beta1.NodeClaimList{}
Expect(env.Client.List(env, nodeClaimList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
Expect(len(nodeClaimList.Items)).To(BeNumerically(comparator, count))
}
func NodeClaimNames(nodeClaims []*corev1beta1.NodeClaim) []string {
return lo.Map(nodeClaims, func(n *corev1beta1.NodeClaim, index int) string {
return n.Name
})
}
func NodeNames(nodes []*v1.Node) []string {
return lo.Map(nodes, func(n *v1.Node, index int) string {
return n.Name
})
}
func (env *Environment) ConsistentlyExpectNodeCount(comparator string, count int, duration time.Duration) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("expecting nodes to be %s to %d for %s", comparator, count, duration))
nodeList := &v1.NodeList{}
Consistently(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodes, had %d (%v) for %s", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items)), duration))
}, duration.String()).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) ConsistentlyExpectNoDisruptions(nodeCount int, duration time.Duration) (taintedNodes []*v1.Node) {
GinkgoHelper()
return env.ConsistentlyExpectDisruptionsWithNodeCount(0, nodeCount, duration)
}
// ConsistentlyExpectDisruptionsWithNodeCount will continually ensure that there are exactly disruptingNodes with totalNodes (including replacements and existing nodes)
func (env *Environment) ConsistentlyExpectDisruptionsWithNodeCount(disruptingNodes, totalNodes int, duration time.Duration) (taintedNodes []*v1.Node) {
GinkgoHelper()
nodes := []v1.Node{}
Consistently(func(g Gomega) {
// Ensure we don't change our NodeClaims
nodeClaimList := &corev1beta1.NodeClaimList{}
g.Expect(env.Client.List(env, nodeClaimList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(nodeClaimList.Items).To(HaveLen(totalNodes))
nodeList := &v1.NodeList{}
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(nodeList.Items).To(HaveLen(totalNodes))
nodes = lo.Filter(nodeList.Items, func(n v1.Node, _ int) bool {
_, ok := lo.Find(n.Spec.Taints, func(t v1.Taint) bool {
return corev1beta1.IsDisruptingTaint(t)
})
return ok
})
g.Expect(nodes).To(HaveLen(disruptingNodes))
}, duration).Should(Succeed())
return lo.ToSlicePtr(nodes)
}
func (env *Environment) EventuallyExpectTaintedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for tainted nodes to be %s to %d", comparator, count))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.MatchingFields{"spec.taints[*].karpenter.sh/disruption": "disrupting"})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d tainted nodes, had %d (%v)", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) EventuallyExpectNodesUntaintedWithTimeout(timeout time.Duration, nodes ...*v1.Node) {
GinkgoHelper()
By(fmt.Sprintf("waiting for %d nodes to be untainted", len(nodes)))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.MatchingFields{"spec.taints[*].karpenter.sh/disruption": "disrupting"})).To(Succeed())
taintedNodeNames := lo.Map(nodeList.Items, func(n v1.Node, _ int) string { return n.Name })
g.Expect(taintedNodeNames).ToNot(ContainElements(lo.Map(nodes, func(n *v1.Node, _ int) interface{} { return n.Name })...))
}).WithTimeout(timeout).Should(Succeed())
}
func (env *Environment) EventuallyExpectNodeClaimCount(comparator string, count int) []*corev1beta1.NodeClaim {
GinkgoHelper()
By(fmt.Sprintf("waiting for nodes to be %s to %d", comparator, count))
nodeClaimList := &corev1beta1.NodeClaimList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeClaimList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(nodeClaimList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodeclaims, had %d (%v)", count, len(nodeClaimList.Items), NodeClaimNames(lo.ToSlicePtr(nodeClaimList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeClaimList.Items)
}
func (env *Environment) EventuallyExpectNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for nodes to be %s to %d", comparator, count))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodes, had %d (%v)", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) EventuallyExpectNodeCountWithSelector(comparator string, count int, selector labels.Selector) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for nodes with selector %v to be %s to %d", selector, comparator, count))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel}, client.MatchingLabelsSelector{Selector: selector})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodes, had %d (%v)", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) EventuallyExpectCreatedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for created nodes to be %s to %d", comparator, count))
var createdNodes []*v1.Node
Eventually(func(g Gomega) {
createdNodes = env.Monitor.CreatedNodes()
g.Expect(len(createdNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d created nodes, had %d (%v)", count, len(createdNodes), NodeNames(createdNodes)))
}).Should(Succeed())
return createdNodes
}
func (env *Environment) EventuallyExpectDeletedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for deleted nodes to be %s to %d", comparator, count))
var deletedNodes []*v1.Node
Eventually(func(g Gomega) {
deletedNodes = env.Monitor.DeletedNodes()
g.Expect(len(deletedNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d deleted nodes, had %d (%v)", count, len(deletedNodes), NodeNames(deletedNodes)))
}).Should(Succeed())
return deletedNodes
}
func (env *Environment) EventuallyExpectDeletedNodeCountWithSelector(comparator string, count int, selector labels.Selector) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for deleted nodes with selector %v to be %s to %d", selector, comparator, count))
var deletedNodes []*v1.Node
Eventually(func(g Gomega) {
deletedNodes = env.Monitor.DeletedNodes()
deletedNodes = lo.Filter(deletedNodes, func(n *v1.Node, _ int) bool {
return selector.Matches(labels.Set(n.Labels))
})
g.Expect(len(deletedNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d deleted nodes, had %d (%v)", count, len(deletedNodes), NodeNames(deletedNodes)))
}).Should(Succeed())
return deletedNodes
}
func (env *Environment) EventuallyExpectInitializedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for initialized nodes to be %s to %d", comparator, count))
var nodes []*v1.Node
Eventually(func(g Gomega) {
nodes = env.Monitor.CreatedNodes()
nodes = lo.Filter(nodes, func(n *v1.Node, _ int) bool {
return n.Labels[corev1beta1.NodeInitializedLabelKey] == "true"
})
g.Expect(len(nodes)).To(BeNumerically(comparator, count))
}).Should(Succeed())
return nodes
}
func (env *Environment) EventuallyExpectCreatedNodeClaimCount(comparator string, count int) []*corev1beta1.NodeClaim {
GinkgoHelper()
By(fmt.Sprintf("waiting for created nodeclaims to be %s to %d", comparator, count))
nodeClaimList := &corev1beta1.NodeClaimList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env.Context, nodeClaimList)).To(Succeed())
g.Expect(len(nodeClaimList.Items)).To(BeNumerically(comparator, count))
}).Should(Succeed())
return lo.Map(nodeClaimList.Items, func(nc corev1beta1.NodeClaim, _ int) *corev1beta1.NodeClaim {
return &nc
})
}
func (env *Environment) EventuallyExpectNodeClaimsReady(nodeClaims ...*corev1beta1.NodeClaim) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, nc := range nodeClaims {
temp := &corev1beta1.NodeClaim{}
g.Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(nc), temp)).Should(Succeed())
g.Expect(temp.StatusConditions().IsHappy()).To(BeTrue())
}
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectExpired(nodeClaims ...*corev1beta1.NodeClaim) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, nc := range nodeClaims {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(nc), nc)).To(Succeed())
g.Expect(nc.StatusConditions().GetCondition(corev1beta1.Expired).IsTrue()).To(BeTrue())
}
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectDrifted(nodeClaims ...*corev1beta1.NodeClaim) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, nc := range nodeClaims {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(nc), nc)).To(Succeed())
g.Expect(nc.StatusConditions().GetCondition(corev1beta1.Drifted).IsTrue()).To(BeTrue())
}
}).Should(Succeed())
}
func (env *Environment) ConsistentlyExpectNodeClaimsNotDrifted(duration time.Duration, nodeClaims ...*corev1beta1.NodeClaim) {
GinkgoHelper()
nodeClaimNames := lo.Map(nodeClaims, func(nc *corev1beta1.NodeClaim, _ int) string { return nc.Name })
By(fmt.Sprintf("consistently expect nodeclaims %s not to be drifted for %s", nodeClaimNames, duration))
Consistently(func(g Gomega) {
for _, nc := range nodeClaims {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(nc), nc)).To(Succeed())
g.Expect(nc.StatusConditions().GetCondition(corev1beta1.Drifted)).To(BeNil())
}
}, duration).Should(Succeed())
}
func (env *Environment) EventuallyExpectEmpty(nodeClaims ...*corev1beta1.NodeClaim) {
GinkgoHelper()
Eventually(func(g Gomega) {
for _, nc := range nodeClaims {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(nc), nc)).To(Succeed())
g.Expect(nc.StatusConditions().GetCondition(corev1beta1.Empty).IsTrue()).To(BeTrue())
}
}).Should(Succeed())
}
func (env *Environment) GetNode(nodeName string) v1.Node {
GinkgoHelper()
var node v1.Node
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: nodeName}, &node)).To(Succeed())
return node
}
func (env *Environment) ExpectNoCrashes() {
GinkgoHelper()
for k, v := range env.Monitor.RestartCount("kube-system") {
if strings.Contains(k, "karpenter") && v > 0 {
Fail("expected karpenter containers to not crash")
}
}
}
var (
lastLogged = metav1.Now()
)
func (env *Environment) printControllerLogs(options *v1.PodLogOptions) {
fmt.Println("------- START CONTROLLER LOGS -------")
defer fmt.Println("------- END CONTROLLER LOGS -------")
if options.SinceTime == nil {
options.SinceTime = lastLogged.DeepCopy()
lastLogged = metav1.Now()
}
pods := env.ExpectKarpenterPods()
for _, pod := range pods {
temp := options.DeepCopy() // local version of the log options
fmt.Printf("------- pod/%s -------\n", pod.Name)
if len(pod.Status.ContainerStatuses) > 0 && pod.Status.ContainerStatuses[0].RestartCount > 0 {
fmt.Printf("[PREVIOUS CONTAINER LOGS]\n")
temp.Previous = true
}
stream, err := env.KubeClient.CoreV1().Pods("kube-system").GetLogs(pod.Name, temp).Stream(env.Context)
if err != nil {
logging.FromContext(env.Context).Errorf("fetching controller logs: %s", err)
return
}
log := &bytes.Buffer{}
_, err = io.Copy(log, stream)
Expect(err).ToNot(HaveOccurred())
logging.FromContext(env.Context).Info(log)
}
}
func (env *Environment) EventuallyExpectMinUtilization(resource v1.ResourceName, comparator string, value float64) {
GinkgoHelper()
Eventually(func(g Gomega) {
g.Expect(env.Monitor.MinUtilization(resource)).To(BeNumerically(comparator, value))
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectAvgUtilization(resource v1.ResourceName, comparator string, value float64) {
GinkgoHelper()
Eventually(func(g Gomega) {
g.Expect(env.Monitor.AvgUtilization(resource)).To(BeNumerically(comparator, value))
}, 10*time.Minute).Should(Succeed())
}
func (env *Environment) ExpectDaemonSetEnvironmentVariableUpdated(obj client.ObjectKey, name, value string, containers ...string) {
GinkgoHelper()
ds := &appsv1.DaemonSet{}
Expect(env.Client.Get(env.Context, obj, ds)).To(Succeed())
if len(containers) == 0 {
Expect(len(ds.Spec.Template.Spec.Containers)).To(BeNumerically("==", 1))
containers = append(containers, ds.Spec.Template.Spec.Containers[0].Name)
}
patch := client.StrategicMergeFrom(ds.DeepCopy())
containerNames := sets.New(containers...)
for ci := range ds.Spec.Template.Spec.Containers {
c := &ds.Spec.Template.Spec.Containers[ci]
if !containerNames.Has(c.Name) {
continue
}
// If the env var already exists, update its value. Otherwise, create a new var.
if _, i, ok := lo.FindIndexOf(c.Env, func(e v1.EnvVar) bool {
return e.Name == name
}); ok {
c.Env[i].Value = value
} else {
c.Env = append(c.Env, v1.EnvVar{Name: name, Value: value})
}
}
Expect(env.Client.Patch(env.Context, ds, patch)).To(Succeed())
}
// ForcePodsToSpread ensures that currently scheduled pods get spread evenly across all passed nodes by deleting pods off of existing
// nodes and waiting them to reschedule. This is useful for scenarios where you want to force the nodes be underutilized
// but you want to keep a consistent count of nodes rather than leaving around empty ones.
func (env *Environment) ForcePodsToSpread(nodes ...*v1.Node) {
GinkgoHelper()
// Get the total count of pods across
podCount := 0
for _, n := range nodes {
podCount += len(env.ExpectActivePodsForNode(n.Name))
}
maxPodsPerNode := int(math.Ceil(float64(podCount) / float64(len(nodes))))
By(fmt.Sprintf("forcing %d pods to spread across %d nodes", podCount, len(nodes)))
start := time.Now()
for {
var nodePods []*v1.Pod
node, found := lo.Find(nodes, func(n *v1.Node) bool {
nodePods = env.ExpectActivePodsForNode(n.Name)
return len(nodePods) > maxPodsPerNode
})
if !found {
break
}
// Set the nodes to unschedulable so that the pods won't reschedule.
Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(node), node)).To(Succeed())
stored := node.DeepCopy()
node.Spec.Unschedulable = true
Expect(env.Client.Patch(env.Context, node, client.StrategicMergeFrom(stored))).To(Succeed())
for _, pod := range nodePods[maxPodsPerNode:] {
env.ExpectDeleted(pod)
}
Eventually(func(g Gomega) {
g.Expect(len(env.ExpectActivePodsForNode(node.Name))).To(Or(Equal(maxPodsPerNode), Equal(maxPodsPerNode-1)))
}).WithTimeout(5 * time.Second).Should(Succeed())
// TODO: Consider moving this time check to an Eventually poll. This gets a little tricker with helper functions
// since you need to make sure that your Expectation helper functions are scoped to to your "g Gomega" scope
// so that you don't fail the first time you get a failure on your expectation
if time.Since(start) > time.Minute*15 {
Fail("forcing pods to spread failed due to a timeout")
}
}
for _, n := range nodes {
stored := n.DeepCopy()
n.Spec.Unschedulable = false
Expect(env.Client.Patch(env.Context, n, client.StrategicMergeFrom(stored))).To(Succeed())
}
}
func (env *Environment) ExpectActivePodsForNode(nodeName string) []*v1.Pod {
GinkgoHelper()
podList := &v1.PodList{}
Expect(env.Client.List(env, podList, client.MatchingFields{"spec.nodeName": nodeName}, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
return lo.Filter(lo.ToSlicePtr(podList.Items), func(p *v1.Pod, _ int) bool {
return p.DeletionTimestamp.IsZero()
})
}
func (env *Environment) ExpectCABundle() string {
// Discover CA Bundle from the REST client. We could alternatively
// have used the simpler client-go InClusterConfig() method.
// However, that only works when Karpenter is running as a Pod
// within the same cluster it's managing.
GinkgoHelper()
transportConfig, err := env.Config.TransportConfig()
Expect(err).ToNot(HaveOccurred())
_, err = transport.TLSConfigFor(transportConfig) // fills in CAData!
Expect(err).ToNot(HaveOccurred())
logging.FromContext(env.Context).Debugf("Discovered caBundle, length %d", len(transportConfig.TLS.CAData))
return base64.StdEncoding.EncodeToString(transportConfig.TLS.CAData)
}
func (env *Environment) GetDaemonSetCount(np *corev1beta1.NodePool) int {
GinkgoHelper()
// Performs the same logic as the scheduler to get the number of daemonset
// pods that we estimate we will need to schedule as overhead to each node
daemonSetList := &appsv1.DaemonSetList{}
Expect(env.Client.List(env.Context, daemonSetList)).To(Succeed())
return lo.CountBy(daemonSetList.Items, func(d appsv1.DaemonSet) bool {
p := &v1.Pod{Spec: d.Spec.Template.Spec}
nodeClaimTemplate := pscheduling.NewNodeClaimTemplate(np)
if err := scheduling.Taints(nodeClaimTemplate.Spec.Taints).Tolerates(p); err != nil {
return false
}
if err := nodeClaimTemplate.Requirements.Compatible(scheduling.NewPodRequirements(p), scheduling.AllowUndefinedWellKnownLabels); err != nil {
return false
}
return true
})
}