forked from kubevirt/kubevirt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vmi_lifecycle_test.go
1900 lines (1587 loc) · 82 KB
/
vmi_lifecycle_test.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
/*
* This file is part of the KubeVirt project
*
* 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.
*
* Copyright 2017, 2018 Red Hat, Inc.
*
*/
package tests_test
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
"kubevirt.io/kubevirt/tests/framework/checks"
expect "github.com/google/goexpect"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gstruct"
k8sv1 "k8s.io/api/core/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/rand"
k8sWatch "k8s.io/apimachinery/pkg/watch"
v1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/kubevirt/pkg/controller"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-controller/services"
"kubevirt.io/kubevirt/pkg/virt-controller/watch"
device_manager "kubevirt.io/kubevirt/pkg/virt-handler/device-manager"
nodelabellerutil "kubevirt.io/kubevirt/pkg/virt-handler/node-labeller/util"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/converter"
"kubevirt.io/kubevirt/tests"
"kubevirt.io/kubevirt/tests/clientcmd"
"kubevirt.io/kubevirt/tests/console"
cd "kubevirt.io/kubevirt/tests/containerdisk"
"kubevirt.io/kubevirt/tests/flags"
"kubevirt.io/kubevirt/tests/libnode"
"kubevirt.io/kubevirt/tests/libvmi"
"kubevirt.io/kubevirt/tests/testsuite"
"kubevirt.io/kubevirt/tests/util"
"kubevirt.io/kubevirt/tests/watcher"
)
func newCirrosVMI() *v1.VirtualMachineInstance {
return tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
}
func addNodeAffinityToVMI(vmi *v1.VirtualMachineInstance, nodeName string) {
vmi.Spec.Affinity = &k8sv1.Affinity{
NodeAffinity: &k8sv1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &k8sv1.NodeSelector{
NodeSelectorTerms: []k8sv1.NodeSelectorTerm{
{
MatchExpressions: []k8sv1.NodeSelectorRequirement{
{Key: "kubernetes.io/hostname", Operator: k8sv1.NodeSelectorOpIn, Values: []string{nodeName}},
},
},
},
},
},
}
}
var _ = Describe("[rfe_id:273][crit:high][arm64][vendor:[email protected]][level:component][sig-compute]VMIlifecycle", func() {
var err error
var virtClient kubecli.KubevirtClient
var vmi *v1.VirtualMachineInstance
var allowEmulation *bool
const fakeLibvirtLogFilters = "3:remote 4:event 3:util.json 3:util.object 3:util.dbus 3:util.netlink 3:node_device 3:rpc 3:access 1:*"
BeforeEach(func() {
virtClient, err = kubecli.GetKubevirtClient()
util.PanicOnError(err)
vmi = tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))
})
AfterEach(func() {
// Not every test causes virt-handler to restart, but a few different contexts do.
// This check is fast and non-intrusive if virt-handler is already running.
testsuite.EnsureKVMPresent()
})
Context("when virt-handler is deleted", func() {
It("[Serial][test_id:4716]should label the node with kubevirt.io/schedulable=false", func() {
pods, err := virtClient.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s", v1.AppLabel, "virt-handler"),
})
Expect(err).ToNot(HaveOccurred())
Expect(pods.Items).ToNot(BeEmpty())
pod := pods.Items[0]
handlerNamespace := pod.GetNamespace()
By("setting up a watch on Nodes")
nodeWatch, err := virtClient.CoreV1().Nodes().Watch(context.Background(), metav1.ListOptions{})
Expect(err).ToNot(HaveOccurred())
err = virtClient.CoreV1().Pods(handlerNamespace).Delete(context.Background(), pod.Name, metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
Eventually(nodeWatch.ResultChan(), 120*time.Second).Should(Receive(WithTransform(func(e k8sWatch.Event) metav1.ObjectMeta {
node, ok := e.Object.(*k8sv1.Node)
Expect(ok).To(BeTrue())
return node.ObjectMeta
}, MatchFields(IgnoreExtras, Fields{
"Name": Equal(pod.Spec.NodeName),
"Labels": HaveKeyWithValue(v1.NodeSchedulable, "false"),
}))), "Failed to observe change in schedulable label")
})
})
Describe("[rfe_id:273][crit:high][vendor:[email protected]][level:component]Creating a VirtualMachineInstance", func() {
It("[test_id:1619]should success", func() {
_, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
})
It("[test_id:1620]should start it", func() {
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
})
It("[test_id:6095]should start in paused state if start strategy set to paused", func() {
strategy := v1.StartStrategyPaused
vmi.Spec.StartStrategy = &strategy
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
tests.WaitForVMICondition(virtClient, vmi, v1.VirtualMachineInstancePaused, 30)
By("Unpausing VMI")
command := clientcmd.NewRepeatableVirtctlCommand("unpause", "vmi", "--namespace", util.NamespaceTestDefault, vmi.Name)
Expect(command()).To(Succeed())
tests.WaitForVMIConditionRemovedOrFalse(virtClient, vmi, v1.VirtualMachineInstancePaused, 30)
})
It("[test_id:1621]should attach virt-launcher to it", func() {
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
By("Getting virt-launcher logs")
logs := func() string { return getVirtLauncherLogs(virtClient, vmi) }
Eventually(logs,
11*time.Second,
500*time.Millisecond).
Should(ContainSubstring("Found PID for"))
})
It("[test_id:3195]should carry annotations to pod", func() {
vmi.Annotations = map[string]string{
"testannotation": "annotation from vmi",
}
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)
Expect(pod).NotTo(BeNil())
Expect(pod.Annotations).To(HaveKeyWithValue("testannotation", "annotation from vmi"), "annotation should be carried to the pod")
})
It("[test_id:3196]should carry kubernetes and kubevirt annotations to pod", func() {
vmi.Annotations = map[string]string{
"kubevirt.io/test": "test",
"kubernetes.io/test": "test",
}
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)
Expect(pod).NotTo(BeNil())
Expect(pod.Annotations).To(HaveKey("kubevirt.io/test"), "kubevirt annotation should not be carried to the pod")
Expect(pod.Annotations).To(HaveKey("kubernetes.io/test"), "kubernetes annotation should not be carried to the pod")
})
It("Should prevent eviction when EvictionStratgy: External", func() {
strategy := v1.EvictionStrategyExternal
vmi.Spec.EvictionStrategy = &strategy
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)
Expect(pod).ToNot(BeNil())
By("calling evict on VMI's pod")
err = virtClient.CoreV1().Pods(vmi.Namespace).EvictV1beta1(context.Background(), &policyv1beta1.Eviction{ObjectMeta: metav1.ObjectMeta{Name: pod.Name}})
// The "too many requests" err is what get's returned when an
// eviction would invalidate a pdb. This is what we want to see here.
Expect(errors.IsTooManyRequests(err)).To(BeTrue())
By("should have evacuation node name set on vmi status")
Consistently(func() error {
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)
Expect(pod).ToNot(BeNil())
Expect(pod.DeletionTimestamp).To(BeNil())
vmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(vmi.Status.EvacuationNodeName).ToNot(Equal(""))
return nil
}, 20*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
})
It("[test_id:1622]should log libvirtd logs", func() {
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
By("Getting virt-launcher logs")
logs := func() string { return getVirtLauncherLogs(virtClient, vmi) }
Eventually(logs,
11*time.Second,
500*time.Millisecond).
Should(ContainSubstring("libvirt version: "))
Eventually(logs,
2*time.Second,
500*time.Millisecond).
Should(ContainSubstring(`"subcomponent":"libvirt"`))
})
DescribeTable("log libvirtd debug logs should be", func(vmiLabels, vmiAnnotations map[string]string, expectDebugLogs bool) {
var err error
vmi := tests.NewRandomVMI()
vmi.Labels = vmiLabels
vmi.Annotations = vmiAnnotations
vmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Create VMI successfully")
tests.WaitForSuccessfulVMIStart(vmi)
By("Getting virt-launcher logs")
logs := func() string { return getVirtLauncherLogs(virtClient, vmi) }
const totalTestTime = 2 * time.Second
const checkIntervalTime = 500 * time.Millisecond
const logEntryToSearch = "QEMU_MONITOR_SEND_MSG"
const subcomponent = `"subcomponent":"libvirt"`
// There are plenty of strings we can use to identify the debug logs.
// Here we use something we deeply care about when in debug mode.
if expectDebugLogs {
Eventually(logs,
totalTestTime,
checkIntervalTime).
Should(And(ContainSubstring(logEntryToSearch), ContainSubstring(subcomponent)))
} else {
Consistently(logs,
totalTestTime,
checkIntervalTime).
ShouldNot(And(ContainSubstring(logEntryToSearch), ContainSubstring(subcomponent)))
}
},
Entry("[test_id:3197]enabled when debugLogs label defined", map[string]string{"debugLogs": "true"}, nil, true),
Entry("[test_id:8530]enabled when customLogFilters defined", nil, map[string]string{v1.CustomLibvirtLogFiltersAnnotation: fakeLibvirtLogFilters}, true),
Entry("[test_id:8531]enabled when log verbosity is high", map[string]string{"logVerbosity": "10"}, nil, true),
Entry("[test_id:8532]disabled when log verbosity is low", map[string]string{"logVerbosity": "2"}, nil, false),
Entry("[test_id:8533]disabled when log verbosity, debug logs and customLogFilters are not defined", nil, nil, false),
)
It("[test_id:1623]should reject POST if validation webhook deems the spec invalid", func() {
// Add a disk that doesn't map to a volume.
// This should get rejected which tells us the webhook validator is working.
vmi.Spec.Domain.Devices.Disks = append(vmi.Spec.Domain.Devices.Disks, v1.Disk{
Name: "testdisk",
})
vmi.Spec.Domain.Devices.Disks = append(vmi.Spec.Domain.Devices.Disks, v1.Disk{
Name: "testdisk2",
})
result := virtClient.RestClient().Post().Resource("virtualmachineinstances").Namespace(util.NamespaceTestDefault).Body(vmi).Do(context.Background())
// Verify validation failed.
statusCode := 0
result.StatusCode(&statusCode)
Expect(statusCode).To(Equal(http.StatusUnprocessableEntity), "VMI should be rejected as unprocessable")
reviewResponse := &metav1.Status{}
body, _ := result.Raw()
err = json.Unmarshal(body, reviewResponse)
Expect(err).To(BeNil(), "Result should be unmarshallable")
Expect(reviewResponse.Details.Causes).To(HaveLen(2), "There should be 2 thing wrong in response")
Expect(reviewResponse.Details.Causes[0].Field).To(Equal("spec.domain.devices.disks[1].name"))
Expect(reviewResponse.Details.Causes[1].Field).To(Equal("spec.domain.devices.disks[2].name"))
})
It("[test_id:1624]should reject PATCH if schema is invalid", func() {
err := virtClient.RestClient().Post().Resource("virtualmachineinstances").Namespace(util.NamespaceTestDefault).Body(vmi).Do(context.Background()).Error()
Expect(err).To(BeNil(), "Send POST successfully")
// Add a disk without a volume reference (this is in valid)
patchStr := fmt.Sprintf("{\"apiVersion\":\"kubevirt.io/%s\",\"kind\":\"VirtualMachineInstance\",\"spec\":{\"domain\":{\"devices\":{\"disks\":[{\"disk\":{\"bus\":\"virtio\"},\"name\":\"fakedisk\"}]}}}}", v1.ApiLatestVersion)
result := virtClient.RestClient().Patch(types.MergePatchType).Resource("virtualmachineinstances").Namespace(util.NamespaceTestDefault).Name(vmi.Name).Body([]byte(patchStr)).Do(context.Background())
// Verify validation failed.
statusCode := 0
result.StatusCode(&statusCode)
Expect(statusCode).To(Equal(http.StatusUnprocessableEntity), "The entity should be unprocessable")
})
Context("when name is longer than 63 characters", func() {
BeforeEach(func() {
vmi = tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))
vmi.Name = "testvmi" + rand.String(63)
})
It("[test_id:1625]should start it", func() {
By("Creating a VirtualMachineInstance with a long name")
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "cannot create VirtualMachineInstance %q: %v", vmi.Name, err)
Expect(len(vmi.Name)).To(BeNumerically(">", 63), "VirtualMachineInstance %q name is not longer than 63 characters", vmi.Name)
By("Waiting until it starts")
tests.WaitForSuccessfulVMIStart(vmi)
vmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "cannot fetch VirtualMachineInstance %q: %v", vmi.Name, err)
By("Obtaining serial console")
Expect(console.LoginToAlpine(vmi)).To(Succeed(), "VirtualMachineInstance %q console is not accessible: %v", vmi.Name, err)
})
})
Context("when it already exist", func() {
It("[test_id:1626]should be rejected", func() {
By("Creating a VirtualMachineInstance")
err := virtClient.RestClient().Post().Resource("virtualmachineinstances").Namespace(util.NamespaceTestDefault).Body(vmi).Do(context.Background()).Error()
Expect(err).To(BeNil(), "Should create VMI successfully")
By("Creating the same VirtualMachineInstance second time")
b, err := virtClient.RestClient().Post().Resource("virtualmachineinstances").Namespace(util.NamespaceTestDefault).Body(vmi).DoRaw(context.Background())
Expect(err).ToNot(BeNil(), "Second VMI should be rejected")
By("Checking that POST return status equals to 409")
status := metav1.Status{}
err = json.Unmarshal(b, &status)
Expect(err).To(BeNil(), "Response should be decoded successfully from json")
Expect(status.Code).To(Equal(int32(http.StatusConflict)), "There should be conflict with existing VMI")
})
})
Context("with boot order", func() {
DescribeTable("[rfe_id:273][crit:high][vendor:[email protected]][level:component]should be able to boot from selected disk", func(alpineBootOrder uint, cirrosBootOrder uint, consoleText string, wait int) {
By("defining a VirtualMachineInstance with an Alpine disk")
vmi = tests.NewRandomVMIWithEphemeralDiskAndUserdataHighMemory(cd.ContainerDiskFor(cd.ContainerDiskAlpine), "#!/bin/sh\n\necho 'hi'\n")
By("adding a Cirros Disk")
tests.AddEphemeralDisk(vmi, "disk2", v1.DiskBusVirtio, cd.ContainerDiskFor(cd.ContainerDiskCirros))
By("setting boot order")
vmi = tests.AddBootOrderToDisk(vmi, "disk0", &alpineBootOrder)
vmi = tests.AddBootOrderToDisk(vmi, "disk2", &cirrosBootOrder)
By("starting VirtualMachineInstance")
vmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "VMI should be created successfully")
By("Waiting the VirtualMachineInstance start")
tests.WaitForSuccessfulVMIStart(vmi)
By("Checking console text")
err = console.SafeExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: "\n"},
&expect.BExp{R: consoleText},
}, wait)
Expect(err).ToNot(HaveOccurred(), "Should match the console in VMI")
},
Entry("[test_id:1627]Alpine as first boot", uint(1), uint(2), "Welcome to Alpine", 90),
Entry("[test_id:1628]Cirros as first boot", uint(2), uint(1), "cirros", 90),
)
})
Context("with user-data", func() {
Context("without k8s secret", func() {
It("[test_id:1629][posneg:negative]should not be able to start virt-launcher pod", func() {
userData := fmt.Sprintf("#!/bin/sh\n\necho 'hi'\n")
vmi = tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), userData)
for _, volume := range vmi.Spec.Volumes {
if volume.CloudInitNoCloud != nil {
spec := volume.CloudInitNoCloud
spec.UserDataBase64 = ""
spec.UserDataSecretRef = &k8sv1.LocalObjectReference{Name: "nonexistent"}
break
}
}
By("Starting a VirtualMachineInstance")
vmi = tests.RunVMIAndExpectScheduling(vmi, 30)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
launcher := libvmi.GetPodByVirtualMachineInstance(vmi, vmi.Namespace)
watcher.New(launcher).
SinceWatchedObjectResourceVersion().
Timeout(60*time.Second).
Watch(ctx, func(event *k8sv1.Event) bool {
if event.Type == "Warning" && event.Reason == "FailedMount" {
return true
}
return false
},
"event of type Warning, reason = FailedMount")
})
It("[test_id:1630]should log warning and proceed once the secret is there", func() {
userData := fmt.Sprintf("#!/bin/sh\n\necho 'hi'\n")
userData64 := ""
vmi = tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), userData)
for _, volume := range vmi.Spec.Volumes {
if volume.CloudInitNoCloud != nil {
spec := volume.CloudInitNoCloud
userData64 = spec.UserDataBase64
spec.UserDataBase64 = ""
spec.UserDataSecretRef = &k8sv1.LocalObjectReference{Name: "nonexistent"}
break
}
}
By("Starting a VirtualMachineInstance")
createdVMI := tests.RunVMIAndExpectScheduling(vmi, 30)
launcher := libvmi.GetPodByVirtualMachineInstance(createdVMI, createdVMI.Namespace)
// Wait until we see that starting the VirtualMachineInstance is failing
By(fmt.Sprintf("Checking that VirtualMachineInstance start failed: starting at %v", time.Now()))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
event := watcher.New(launcher).Timeout(60*time.Second).SinceWatchedObjectResourceVersion().WaitFor(ctx, watcher.WarningEvent, "FailedMount")
Expect(event.Message).To(SatisfyAny(
ContainSubstring(`secret "nonexistent" not found`),
ContainSubstring(`secrets "nonexistent" not found`), // for k8s 1.11.x
), "VMI should not be started")
// Creat nonexistent secret, so that the VirtualMachineInstance can recover
By("Creating a user-data secret")
secret := k8sv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "nonexistent",
Namespace: vmi.Namespace,
Labels: map[string]string{
util.SecretLabel: "nonexistent",
},
},
Type: "Opaque",
Data: map[string][]byte{
"userdata": []byte(userData64),
},
}
_, err = virtClient.CoreV1().Secrets(vmi.Namespace).Create(context.Background(), &secret, metav1.CreateOptions{})
Expect(err).ToNot(HaveOccurred(), "Should create secret successfully")
// Wait for the VirtualMachineInstance to be started, allow warning events to occur
By("Checking that VirtualMachineInstance start succeeded")
watcher.New(createdVMI).SinceWatchedObjectResourceVersion().Timeout(60*time.Second).WaitFor(ctx, watcher.NormalEvent, v1.Started)
})
})
})
Context("with nodeselector", func() {
It("[test_id:5760]should check if vm's with non existing nodeselector is not running and node selector is not updated", func() {
vmi := libvmi.NewCirros()
By("setting nodeselector with non-existing-os label")
vmi.Spec.NodeSelector = map[string]string{k8sv1.LabelOSStable: "not-existing-os"}
vmi = tests.RunVMIAndExpectScheduling(vmi, 30)
pods, err := virtClient.CoreV1().Pods(util.NamespaceTestDefault).List(context.Background(), metav1.ListOptions{})
Expect(err).ToNot(HaveOccurred())
for _, pod := range pods.Items {
for _, owner := range pod.GetOwnerReferences() {
if owner.Name == vmi.Name {
break
}
}
Expect(pod.Spec.NodeSelector[k8sv1.LabelOSStable]).To(Equal("not-existing-os"), "pod should have node selector")
Expect(pod.Status.Phase).To(Equal(k8sv1.PodPending), "pod has to be in pending state")
for _, condition := range pod.Status.Conditions {
if condition.Type == k8sv1.PodScheduled {
Expect(condition.Reason).To(Equal(k8sv1.PodReasonUnschedulable), "condition reason has to be unschedulable")
}
}
}
})
It("[test_id:5761]should check if vm with valid node selector is scheduled and running and node selector is not updated", func() {
vmi := libvmi.NewCirros()
vmi.Spec.NodeSelector = map[string]string{k8sv1.LabelOSStable: "linux"}
tests.RunVMIAndExpectLaunch(vmi, 60)
pods, err := virtClient.CoreV1().Pods(util.NamespaceTestDefault).List(context.Background(), metav1.ListOptions{})
Expect(err).ToNot(HaveOccurred())
for _, pod := range pods.Items {
for _, owner := range pod.GetOwnerReferences() {
if owner.Name == vmi.Name {
break
}
}
Expect(pod.Spec.NodeSelector[k8sv1.LabelOSStable]).To(Equal("linux"), "pod should have node selector")
Expect(pod.Status.Phase).To(Equal(k8sv1.PodRunning), "pod has to be in running state")
for _, condition := range pod.Status.Conditions {
if condition.Type == k8sv1.ContainersReady {
Expect(condition.Reason).To(Equal(""), "condition reason has to be empty")
}
}
}
})
})
Context("when virt-launcher crashes", func() {
It("[Serial][test_id:1631]should be stopped and have Failed phase", func() {
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Should create VMI successfully")
nodeName := tests.WaitForSuccessfulVMIStart(vmi).Status.NodeName
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
By("Crashing the virt-launcher")
vmiKiller, err := pkillAllLaunchers(virtClient, nodeName)
Expect(err).To(BeNil(), "Should create vmi-killer pod to kill virt-launcher successfully")
watcher.New(vmiKiller).SinceWatchedObjectResourceVersion().Timeout(60*time.Second).WaitFor(ctx, watcher.NormalEvent, v1.Started)
By("Waiting for the vm to be stopped")
watcher.New(vmi).SinceWatchedObjectResourceVersion().Timeout(60*time.Second).WaitFor(ctx, watcher.WarningEvent, v1.Stopped)
By("Checking that VirtualMachineInstance has 'Failed' phase")
Eventually(func() v1.VirtualMachineInstancePhase {
vmi, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI successfully")
return vmi.Status.Phase
}, 10, 1).Should(Equal(v1.Failed), "VMI should be failed")
})
})
Context("[Serial]when virt-handler crashes", func() {
// FIXME: This test has the issues that it tests a lot of different timing scenarios in an intransparent way:
// e.g. virt-handler can die before or after virt-launcher. If we wait until virt-handler is dead before we
// kill virt-launcher then we don't know if virt-handler already restarted.
// Also the virt-handler crash-loop plays a role here. We could also change the daemon-set but then we would not check the crash behaviour.
It("[test_id:1632]should recover and continue management", func() {
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Should submit VMI successfully")
// Start a VirtualMachineInstance
nodeName := tests.WaitForSuccessfulVMIStart(vmi).Status.NodeName
// Kill virt-handler on the node the VirtualMachineInstance is active on.
By("Crashing the virt-handler")
err = pkillHandler(virtClient, nodeName)
Expect(err).To(BeNil(), "Should kill virt-handler successfully")
// Crash the VirtualMachineInstance and verify a recovered version of virt-handler processes the crash
By("Killing the VirtualMachineInstance")
err = pkillAllVMIs(virtClient, nodeName)
Expect(err).To(BeNil(), "Should kill VMI successfully")
// Give virt-handler some time. It can greatly vary when virt-handler will be ready again
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
By("Checking that VirtualMachineInstance has 'Failed' phase")
Eventually(func() v1.VirtualMachineInstancePhase {
vmi, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI successfully")
return vmi.Status.Phase
}, 240*time.Second, 1*time.Second).Should(Equal(v1.Failed), "VMI should be failed")
By(fmt.Sprintf("Waiting for %q %q event after the resource version %q", watcher.WarningEvent, v1.Stopped, vmi.ResourceVersion))
watcher.New(vmi).Timeout(60*time.Second).SinceWatchedObjectResourceVersion().WaitFor(ctx, watcher.WarningEvent, v1.Stopped)
By("checking that it can still start VMIs")
newVMI := newCirrosVMI()
newVMI.Spec.NodeSelector = map[string]string{"kubernetes.io/hostname": nodeName}
newVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(newVMI)
Expect(err).To(BeNil())
tests.WaitForSuccessfulVMIStart(newVMI)
})
})
Context("[Serial]when virt-handler is responsive", func() {
It("[test_id:1633]should indicate that a node is ready for vmis", func() {
By("adding a heartbeat annotation and a schedulable label to the node")
nodes := libnode.GetAllSchedulableNodes(virtClient)
Expect(nodes.Items).ToNot(BeEmpty(), "There should be some compute node")
for _, node := range nodes.Items {
Expect(node.Annotations[v1.VirtHandlerHeartbeat]).ToNot(BeEmpty(), "Nodes should have be ready for VMI")
}
node := &nodes.Items[0]
node, err = virtClient.CoreV1().Nodes().Patch(context.Background(), node.Name, types.StrategicMergePatchType, []byte(fmt.Sprintf(`{"metadata": { "labels": {"%s": "false"}}}`, v1.NodeSchedulable)), metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred(), "Should patch node successfully")
timestamp := node.Annotations[v1.VirtHandlerHeartbeat]
By("setting the schedulable label back to true")
Eventually(func() string {
n, err := virtClient.CoreV1().Nodes().Get(context.Background(), node.Name, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get nodes successfully")
return n.Labels[v1.NodeSchedulable]
}, 5*time.Minute, 2*time.Second).Should(Equal("true"), "Nodes should be schedulable")
By("updating the heartbeat roughly every minute")
Expect(func() string {
n, err := virtClient.CoreV1().Nodes().Get(context.Background(), node.Name, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get nodes successfully")
return n.Labels[v1.VirtHandlerHeartbeat]
}()).ShouldNot(Equal(timestamp), "Should not have old vmi heartbeat")
})
It("[test_id:3198]device plugins should re-register if the kubelet restarts", func() {
By("starting a VMI on a node")
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil(), "Should submit VMI successfully")
// Start a VirtualMachineInstance
nodeName := tests.WaitForSuccessfulVMIStart(vmi).Status.NodeName
By("triggering a device plugin re-registration on that node")
pod, err := kubecli.NewVirtHandlerClient(virtClient).Namespace(flags.KubeVirtInstallNamespace).ForNode(nodeName).Pod()
Expect(err).ToNot(HaveOccurred())
_, _, err = tests.ExecuteCommandOnPodV2(virtClient, pod,
"virt-handler",
[]string{
"rm",
// We want to fail if the file does not exist, but don't want to be asked
// if we really want to remove write-protected files
"--interactive=never",
device_manager.SocketPath("kvm"),
})
Expect(err).ToNot(HaveOccurred())
By("checking if we see the device plugin restart in the logs")
virtHandlerPod, err := kubecli.NewVirtHandlerClient(virtClient).Namespace(flags.KubeVirtInstallNamespace).ForNode(nodeName).Pod()
Expect(err).ToNot(HaveOccurred(), "Should get virthandler client for node")
handlerName := virtHandlerPod.GetObjectMeta().GetName()
handlerNamespace := virtHandlerPod.GetObjectMeta().GetNamespace()
seconds := int64(10)
logsQuery := virtClient.CoreV1().Pods(handlerNamespace).GetLogs(handlerName, &k8sv1.PodLogOptions{SinceSeconds: &seconds, Container: "virt-handler"})
Eventually(func() string {
data, err := logsQuery.DoRaw(context.Background())
Expect(err).ToNot(HaveOccurred(), "Should get logs")
return string(data)
}, 60, 1).Should(
ContainSubstring(
fmt.Sprintf("device socket file for device %s was removed, kubelet probably restarted.", "kvm"),
), "Should log device plugin restart")
// This is a little bit arbitrar
// Background is that new pods go into a crash loop if the devices are still report but virt-handler
// re-registers exactly during that moment. This is not too bad, since normally kubelet itself deletes
// the socket and knows that the devices are not there. However we have to wait in this test a little bit.
time.Sleep(10 * time.Second)
By("starting another VMI on the same node, to verify devices still work")
newVMI := newCirrosVMI()
newVMI.Spec.NodeSelector = map[string]string{"kubernetes.io/hostname": nodeName}
newVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(newVMI)
Expect(err).To(BeNil())
tests.WaitForSuccessfulVMIStart(newVMI)
})
})
Context("[Serial]when virt-handler is not responsive", func() {
var vmi *v1.VirtualMachineInstance
var nodeName string
var virtHandler *k8sv1.Pod
var virtHandlerAvailablePods int32
BeforeEach(func() {
// Schedule a vmi and make sure that virt-handler gets evicted from the node where the vmi was started
vmi = tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "echo hi!")
vmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI successfully")
// Ensure that the VMI is running. This is necessary to ensure that virt-handler is fully responsible for
// the VMI. Otherwise virt-controller may move the VMI to failed instead of the node controller.
nodeName = tests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi).Status.NodeName
virtHandler, err = kubecli.NewVirtHandlerClient(virtClient).Namespace(flags.KubeVirtInstallNamespace).ForNode(nodeName).Pod()
Expect(err).ToNot(HaveOccurred(), "Should get virthandler client")
ds, err := virtClient.AppsV1().DaemonSets(virtHandler.Namespace).Get(context.Background(), "virt-handler", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get virthandler daemonset")
// Save virt-handler number of desired pods
virtHandlerAvailablePods = ds.Status.DesiredNumberScheduled
kv := util.GetCurrentKv(virtClient)
kv.Spec.Workloads = &v1.ComponentConfig{
NodePlacement: &v1.NodePlacement{
Affinity: &k8sv1.Affinity{
NodeAffinity: &k8sv1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &k8sv1.NodeSelector{
NodeSelectorTerms: []k8sv1.NodeSelectorTerm{
{MatchExpressions: []k8sv1.NodeSelectorRequirement{
{Key: "kubernetes.io/hostname", Operator: "NotIn", Values: []string{nodeName}},
}},
},
},
},
},
},
}
_, err = virtClient.KubeVirt(kv.Namespace).Update(kv)
Expect(err).ToNot(HaveOccurred(), "Should update kubevirt infra placement")
Eventually(func() bool {
_, err := virtClient.CoreV1().Pods(virtHandler.Namespace).Get(context.Background(), virtHandler.Name, metav1.GetOptions{})
return errors.IsNotFound(err)
}, 120*time.Second, 1*time.Second).Should(BeTrue(), "The virthandler pod should be gone")
})
It("[test_id:1634]the node controller should mark the node as unschedulable when the virt-handler heartbeat has timedout", func() {
// Update virt-handler heartbeat, to trigger a timeout
data := []byte(fmt.Sprintf(`{"metadata": { "labels": { "%s": "true" }, "annotations": {"%s": "%s"}}}`, v1.NodeSchedulable, v1.VirtHandlerHeartbeat, nowAsJSONWithOffset(-10*time.Minute)))
_, err = virtClient.CoreV1().Nodes().Patch(context.Background(), nodeName, types.StrategicMergePatchType, data, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred(), "Should patch node successfully")
// Delete vmi pod
pods, err := virtClient.CoreV1().Pods(vmi.Namespace).List(context.Background(), metav1.ListOptions{
LabelSelector: v1.CreatedByLabel + "=" + string(vmi.GetUID()),
})
Expect(err).ToNot(HaveOccurred(), "Should list pods successfully")
Expect(pods.Items).To(HaveLen(1), "There should be only one VMI pod")
var gracePeriod int64 = 0
Expect(virtClient.CoreV1().Pods(vmi.Namespace).Delete(context.Background(), pods.Items[0].Name, metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriod,
})).To(Succeed(), "The vmi pod should be deleted successfully")
// it will take at least 45 seconds until the vmi is gone, check the schedulable state in the meantime
By("marking the node as not schedulable")
Eventually(func() string {
node, err := virtClient.CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get node successfully")
return node.Labels[v1.NodeSchedulable]
}, 20*time.Second, 1*time.Second).Should(Equal("false"), "The node should not be schedulable")
By("moving stuck vmis to failed state")
Eventually(func() v1.VirtualMachineInstancePhase {
failedVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get vmi successfully")
return failedVMI.Status.Phase
}, 180*time.Second, 1*time.Second).Should(Equal(v1.Failed))
Eventually(func() string {
failedVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get vmi successfully")
return failedVMI.Status.Reason
}, 180*time.Second, 1*time.Second).Should(Equal(watch.NodeUnresponsiveReason))
err = virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
testsuite.RestoreKubeVirtResource()
// Wait until virt-handler ds will have expected number of pods
Eventually(func() bool {
ds, err := virtClient.AppsV1().DaemonSets(virtHandler.Namespace).Get(context.Background(), "virt-handler", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get virthandler successfully")
return ds.Status.NumberAvailable == virtHandlerAvailablePods &&
ds.Status.CurrentNumberScheduled == virtHandlerAvailablePods &&
ds.Status.DesiredNumberScheduled == virtHandlerAvailablePods &&
ds.Status.NumberReady == virtHandlerAvailablePods &&
ds.Status.UpdatedNumberScheduled == virtHandlerAvailablePods
}, 180*time.Second, 1*time.Second).Should(BeTrue(), "Virthandler should be ready to work")
})
})
Context("[Serial]with node tainted", func() {
var nodes *k8sv1.NodeList
var err error
BeforeEach(func() {
Eventually(func() []k8sv1.Node {
nodes = libnode.GetAllSchedulableNodes(virtClient)
return nodes.Items
}, 60*time.Second, 1*time.Second).ShouldNot(BeEmpty(), "There should be some compute node")
// Taint first node with "NoSchedule"
data := []byte(`{"spec":{"taints":[{"effect":"NoSchedule","key":"test","timeAdded":null,"value":"123"}]}}`)
_, err = virtClient.CoreV1().Nodes().Patch(context.Background(), nodes.Items[0].Name, types.StrategicMergePatchType, data, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred(), "Should patch node")
})
AfterEach(func() {
// Untaint first node
data := []byte(`{"spec":{"taints":[]}}`)
_, err = virtClient.CoreV1().Nodes().Patch(context.Background(), nodes.Items[0].Name, types.StrategicMergePatchType, data, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred(), "Should patch node")
})
It("[test_id:1635]the vmi with tolerations should be scheduled", func() {
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
vmi.Spec.Tolerations = []k8sv1.Toleration{{Key: "test", Value: "123"}}
addNodeAffinityToVMI(vmi, nodes.Items[0].Name)
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
tests.WaitForSuccessfulVMIStart(vmi)
})
It("[test_id:1636]the vmi without tolerations should not be scheduled", func() {
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
addNodeAffinityToVMI(vmi, nodes.Items[0].Name)
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
By("Waiting for the VirtualMachineInstance to be unschedulable")
Eventually(func() string {
curVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI")
scheduledCond := controller.NewVirtualMachineInstanceConditionManager().
GetCondition(curVMI, v1.VirtualMachineInstanceConditionType(k8sv1.PodScheduled))
if scheduledCond != nil {
return scheduledCond.Reason
}
return ""
}, 60*time.Second, 1*time.Second).Should(Equal(k8sv1.PodReasonUnschedulable), "VMI should be unschedulable")
})
})
Context("with affinity", func() {
var nodes *k8sv1.NodeList
var err error
BeforeEach(func() {
nodes = libnode.GetAllSchedulableNodes(virtClient)
Expect(nodes.Items).ToNot(BeEmpty(), "There should be some compute node")
})
It("[test_id:1637]the vmi with node affinity and no conflicts should be scheduled", func() {
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
addNodeAffinityToVMI(vmi, nodes.Items[0].Name)
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
tests.WaitForSuccessfulVMIStart(vmi)
curVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI")
Expect(curVMI.Status.NodeName).To(Equal(nodes.Items[0].Name), "Updated VMI name run on the same node")
})
It("[test_id:1638]the vmi with node affinity and anti-pod affinity should not be scheduled", func() {
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
addNodeAffinityToVMI(vmi, nodes.Items[0].Name)
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
tests.WaitForSuccessfulVMIStart(vmi)
curVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI")
Expect(curVMI.Status.NodeName).To(Equal(nodes.Items[0].Name), "VMI should run on the same node")
vmiB := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
addNodeAffinityToVMI(vmiB, nodes.Items[0].Name)
vmiB.Spec.Affinity.PodAntiAffinity = &k8sv1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []k8sv1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{Key: v1.CreatedByLabel, Operator: metav1.LabelSelectorOpIn, Values: []string{string(curVMI.GetUID())}},
},
},
TopologyKey: "kubernetes.io/hostname",
},
},
}
_, err = virtClient.VirtualMachineInstance(vmiB.Namespace).Create(vmiB)
Expect(err).ToNot(HaveOccurred(), "Should create VMIB")
By("Waiting for the VirtualMachineInstance to be unschedulable")
Eventually(func() string {
curVmiB, err := virtClient.VirtualMachineInstance(vmiB.Namespace).Get(vmiB.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMIB")
scheduledCond := controller.NewVirtualMachineInstanceConditionManager().
GetCondition(curVmiB, v1.VirtualMachineInstanceConditionType(k8sv1.PodScheduled))
if scheduledCond != nil {
return scheduledCond.Reason
}
return ""
}, 60*time.Second, 1*time.Second).Should(Equal(k8sv1.PodReasonUnschedulable), "VMI should be unchedulable")
})
})
Context("[Serial]with default cpu model", func() {
var originalConfig v1.KubeVirtConfiguration
var supportedCpuModels []string
//store old kubevirt-config
BeforeEach(func() {
// arm64 does not support cpu model
checks.SkipIfARM64(testsuite.Arch, "arm64 does not support cpu model")
nodes := libnode.GetAllSchedulableNodes(virtClient)
supportedCpuModels = tests.GetSupportedCPUModels(*nodes)
kv := util.GetCurrentKv(virtClient)
originalConfig = kv.Spec.Configuration
})
//replace new kubevirt-config with old config
AfterEach(func() {
tests.UpdateKubeVirtConfigValueAndWait(originalConfig)
})
It("[test_id:3199]should set default cpu model when vmi doesn't have it set", func() {
if len(supportedCpuModels) < 1 {
Skip("Must have at least one supported cpuModel for this test")
}
config := originalConfig.DeepCopy()
defaultCPUModel := supportedCpuModels[0]
config.CPUModel = defaultCPUModel
tests.UpdateKubeVirtConfigValueAndWait(*config)
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
tests.WaitForSuccessfulVMIStart(vmi)
curVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI")
Expect(curVMI.Spec.Domain.CPU.Model).To(Equal(defaultCPUModel), "Expected default CPU model")
})
It("[test_id:3200]should not set default cpu model when vmi has it set", func() {
if len(supportedCpuModels) < 2 {
Skip("Must have at least two supported cpuModels for this test")
}
defaultCPUModel := supportedCpuModels[0]
vmiCPUModel := supportedCpuModels[1]
config := originalConfig.DeepCopy()
config.CPUModel = defaultCPUModel
tests.UpdateKubeVirtConfigValueAndWait(*config)
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
vmi.Spec.Domain.CPU = &v1.CPU{
Model: vmiCPUModel,
}
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")
tests.WaitForSuccessfulVMIStart(vmi)
curVMI, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred(), "Should get VMI")
Expect(curVMI.Spec.Domain.CPU.Model).To(Equal(vmiCPUModel), "Expected vmi CPU model")
})
It("[sig-compute][test_id:3201]should set cpu model to default when vmi does not have it set and default cpu model is not set", func() {
vmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
_, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(vmi)
Expect(err).ToNot(HaveOccurred(), "Should create VMI")