forked from kubevirt/kubevirt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
1508 lines (1279 loc) · 57 KB
/
storage.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 Red Hat, Inc.
*
*/
package storage
import (
"context"
"fmt"
"path/filepath"
"strconv"
"strings"
"time"
"kubevirt.io/kubevirt/tests/libvmi"
"k8s.io/apimachinery/pkg/api/errors"
"kubevirt.io/kubevirt/tests/framework/checks"
storageframework "kubevirt.io/kubevirt/tests/framework/storage"
"kubevirt.io/kubevirt/tests/util"
expect "github.com/google/goexpect"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/pborman/uuid"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/rand"
v1 "kubevirt.io/api/core/v1"
virtv1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/kubecli"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
hostdisk "kubevirt.io/kubevirt/pkg/host-disk"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/converter"
"kubevirt.io/kubevirt/tests"
"kubevirt.io/kubevirt/tests/console"
cd "kubevirt.io/kubevirt/tests/containerdisk"
. "kubevirt.io/kubevirt/tests/framework/matcher"
"kubevirt.io/kubevirt/tests/libdv"
"kubevirt.io/kubevirt/tests/libnet"
"kubevirt.io/kubevirt/tests/libstorage"
"kubevirt.io/kubevirt/tests/testsuite"
"kubevirt.io/kubevirt/tests/watcher"
)
const (
failedCreateVMI = "Failed to create vmi"
failedDeleteVMI = "Failed to delete VMI"
checkingVMInstanceConsoleOut = "Checking that the VirtualMachineInstance console has expected output"
startingVMInstance = "Starting VirtualMachineInstance"
hostDiskName = "host-disk"
diskImgName = "disk.img"
// Without cloud init user data Cirros takes long time to boot,
// so provide this dummy data to make it boot faster
cirrosUserData = "#!/bin/bash\necho 'hello'\n"
)
const (
diskSerial = "FB-fb_18030C10002032"
)
type VMICreationFunc func(string) *virtv1.VirtualMachineInstance
var _ = SIGDescribe("Storage", func() {
var err error
var virtClient kubecli.KubevirtClient
BeforeEach(func() {
virtClient, err = kubecli.GetKubevirtClient()
Expect(err).ToNot(HaveOccurred())
tests.SetupAlpineHostPath()
})
Describe("Starting a VirtualMachineInstance", func() {
var vmi *virtv1.VirtualMachineInstance
var targetImagePath string
BeforeEach(func() {
vmi = nil
targetImagePath = testsuite.HostPathAlpine
})
isPausedOnIOError := func(conditions []v1.VirtualMachineInstanceCondition) bool {
for _, condition := range conditions {
if condition.Type == virtv1.VirtualMachineInstancePaused {
return condition.Status == k8sv1.ConditionTrue && condition.Reason == "PausedIOError"
}
}
return false
}
createNFSPvAndPvc := func(ipFamily k8sv1.IPFamily, nfsPod *k8sv1.Pod) string {
pvName := fmt.Sprintf("test-nfs%s", rand.String(48))
// create a new PV and PVC (PVs can't be reused)
By("create a new NFS PV and PVC")
nfsIP := libnet.GetPodIPByFamily(nfsPod, ipFamily)
ExpectWithOffset(1, nfsIP).NotTo(BeEmpty())
os := string(cd.ContainerDiskAlpine)
libstorage.CreateNFSPvAndPvc(pvName, util.NamespaceTestDefault, "1Gi", nfsIP, os)
return pvName
}
setShareable := func(vmi *virtv1.VirtualMachineInstance, diskName string) {
shareable := true
for i, d := range vmi.Spec.Domain.Devices.Disks {
if d.Name == diskName {
vmi.Spec.Domain.Devices.Disks[i].Shareable = &shareable
return
}
}
}
Context("with error disk", func() {
var (
nodeName, address, device string
pvc *k8sv1.PersistentVolumeClaim
)
BeforeEach(func() {
nodeName = tests.NodeNameWithHandler()
address, device = tests.CreateErrorDisk(nodeName)
var err error
_, pvc, err = tests.CreatePVandPVCwithFaultyDisk(nodeName, device, util.NamespaceTestDefault)
Expect(err).NotTo(HaveOccurred(), "Failed to create PV and PVC for faulty disk")
})
AfterEach(func() {
tests.RemoveSCSIDisk(nodeName, address)
})
It("should pause VMI on IO error", func() {
By("Creating VMI with faulty disk")
vmi := libvmi.NewAlpine(libvmi.WithPersistentVolumeClaim("pvc-disk", pvc.Name))
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).ToNot(HaveOccurred(), failedCreateVMI)
tests.WaitForSuccessfulVMIStartWithTimeoutIgnoreWarnings(vmi, 180)
By("Reading from disk")
Expect(console.LoginToAlpine(vmi)).To(Succeed(), "Should login")
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: "\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: "nohup sh -c \"sleep 10 && while true; do dd if=/dev/vdb of=/dev/null >/dev/null 2>/dev/null; done\" & \n"},
&expect.BExp{R: console.PromptExpression},
}, 20)).To(Succeed())
refresh := ThisVMI(vmi)
By("Expecting VMI to be paused")
Eventually(func() []v1.VirtualMachineInstanceCondition {
vmi, err := refresh()
Expect(err).ToNot(HaveOccurred())
return vmi.Status.Conditions
}, 100*time.Second, time.Second).Should(Satisfy(isPausedOnIOError))
By("Fixing the device")
tests.FixErrorDevice(nodeName)
By("Expecting VMI to NOT be paused")
Eventually(func() bool {
vmi, err := refresh()
Expect(err).ToNot(HaveOccurred())
for _, condition := range vmi.Status.Conditions {
if condition.Type == virtv1.VirtualMachineInstancePaused {
return condition.Status == k8sv1.ConditionFalse
}
}
return false
}, 100*time.Second, time.Second).Should(BeFalse())
By("Cleaning up")
err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Delete(vmi.ObjectMeta.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred(), failedDeleteVMI)
tests.WaitForVirtualMachineToDisappearWithTimeout(vmi, 180)
})
})
Context("with faulty disk", func() {
var (
nodeName string
deviceName = "error"
pv *k8sv1.PersistentVolume
pvc *k8sv1.PersistentVolumeClaim
)
BeforeEach(func() {
nodeName = tests.NodeNameWithHandler()
tests.CreateFaultyDisk(nodeName, deviceName)
var err error
pv, pvc, err = tests.CreatePVandPVCwithFaultyDisk(nodeName, "/dev/mapper/"+deviceName, util.NamespaceTestDefault)
Expect(err).NotTo(HaveOccurred(), "Failed to create PV and PVC for faulty disk")
})
AfterEach(func() {
tests.RemoveFaultyDisk(nodeName, deviceName)
err := virtClient.CoreV1().PersistentVolumes().Delete(context.Background(), pv.Name, metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
})
It("[QUARANTINE] should pause VMI on IO error", func() {
By("Creating VMI with faulty disk")
vmi := libvmi.New(
libvmi.WithPersistentVolumeClaim("disk0", pvc.Name),
libvmi.WithResourceMemory("256Mi"),
libvmi.WithNetwork(v1.DefaultPodNetwork()),
libvmi.WithInterface(libvmi.InterfaceDeviceWithMasqueradeBinding()))
vmi, err := virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).ToNot(HaveOccurred(), failedCreateVMI)
tests.WaitForSuccessfulVMIStartWithTimeoutIgnoreWarnings(vmi, 180)
refresh := ThisVMI(vmi)
By("Expecting VMI to be paused")
Eventually(func() []v1.VirtualMachineInstanceCondition {
vmi, err := refresh()
Expect(err).NotTo(HaveOccurred())
return vmi.Status.Conditions
}, 100*time.Second, time.Second).Should(Satisfy(isPausedOnIOError))
By("Cleaning up")
err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Delete(vmi.ObjectMeta.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred(), failedDeleteVMI)
tests.WaitForVirtualMachineToDisappearWithTimeout(vmi, 180)
})
})
Context("[rfe_id:3106][crit:medium][vendor:[email protected]][level:component]with Alpine PVC", func() {
newRandomVMIWithPVC := func(claimName string) *virtv1.VirtualMachineInstance {
return libvmi.New(
libvmi.WithPersistentVolumeClaim("disk0", claimName),
libvmi.WithResourceMemory("256Mi"),
libvmi.WithRng())
}
newRandomVMIWithCDRom := func(claimName string) *virtv1.VirtualMachineInstance {
return libvmi.New(
libvmi.WithCDRom("disk0", v1.DiskBusSATA, claimName),
libvmi.WithResourceMemory("256Mi"),
libvmi.WithRng())
}
Context("should be successfully", func() {
var pvName string
var nfsPod *k8sv1.Pod
AfterEach(func() {
if targetImagePath != testsuite.HostPathAlpine {
tests.DeleteAlpineWithNonQEMUPermissions()
}
})
DescribeTable("started", func(newVMI VMICreationFunc, storageEngine string, family k8sv1.IPFamily, imageOwnedByQEMU bool) {
libnet.SkipWhenClusterNotSupportIPFamily(virtClient, family)
var nodeName string
// Start the VirtualMachineInstance with the PVC attached
if storageEngine == "nfs" {
targetImage := targetImagePath
if !imageOwnedByQEMU {
targetImage, nodeName = tests.CopyAlpineWithNonQEMUPermissions()
}
nfsPod = storageframework.InitNFS(targetImage, nodeName)
pvName = createNFSPvAndPvc(family, nfsPod)
} else {
pvName = tests.DiskAlpineHostPath
}
vmi = newVMI(pvName)
if storageEngine == "nfs" {
vmi = tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 180)
} else {
vmi = tests.RunVMIAndExpectLaunch(vmi, 180)
}
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToAlpine(vmi)).To(Succeed())
},
Entry("[test_id:3130]with Disk PVC", newRandomVMIWithPVC, "", nil, true),
Entry("[test_id:3131]with CDRom PVC", newRandomVMIWithCDRom, "", nil, true),
Entry("[test_id:4618]with NFS Disk PVC using ipv4 address of the NFS pod", newRandomVMIWithPVC, "nfs", k8sv1.IPv4Protocol, true),
Entry("[Serial]with NFS Disk PVC using ipv6 address of the NFS pod", newRandomVMIWithPVC, "nfs", k8sv1.IPv6Protocol, true),
Entry("[Serial]with NFS Disk PVC using ipv4 address of the NFS pod not owned by qemu", newRandomVMIWithPVC, "nfs", k8sv1.IPv4Protocol, false),
)
})
DescribeTable("should be successfully started and stopped multiple times", func(newVMI VMICreationFunc) {
vmi = newVMI(tests.DiskAlpineHostPath)
num := 3
By("Starting and stopping the VirtualMachineInstance number of times")
for i := 1; i <= num; i++ {
vmi := tests.RunVMIAndExpectLaunch(vmi, 90)
// Verify console on last iteration to verify the VirtualMachineInstance is still booting properly
// after being restarted multiple times
if i == num {
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToAlpine(vmi)).To(Succeed())
}
err = virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
tests.WaitForVirtualMachineToDisappearWithTimeout(vmi, 120)
}
},
Entry("[test_id:3132]with Disk PVC", newRandomVMIWithPVC),
Entry("[test_id:3133]with CDRom PVC", newRandomVMIWithCDRom),
)
})
Context("[rfe_id:3106][crit:medium][vendor:[email protected]][level:component]With an emptyDisk defined", func() {
// The following case is mostly similar to the alpine PVC test above, except using different VirtualMachineInstance.
It("[test_id:3134]should create a writeable emptyDisk with the right capacity", func() {
// Start the VirtualMachineInstance with the empty disk attached
vmi = libvmi.NewCirros(
libvmi.WithResourceMemory("512M"),
libvmi.WithEmptyDisk("emptydisk1", v1.DiskBusVirtio, resource.MustParse("1G")),
)
vmi = tests.RunVMIAndExpectLaunch(vmi, 90)
Expect(console.LoginToCirros(vmi)).To(Succeed())
By("Checking that /dev/vdc has a capacity of 1G, aligned to 4k")
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: "sudo blockdev --getsize64 /dev/vdc\n"},
&expect.BExp{R: "999292928"}, // 1G in bytes rounded down to nearest 1MiB boundary
}, 10)).To(Succeed())
By("Checking if we can write to /dev/vdc")
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: "sudo mkfs.ext4 /dev/vdc\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: tests.EchoLastReturnValue},
&expect.BExp{R: console.RetValue("0")},
}, 20)).To(Succeed())
})
})
Context("[rfe_id:3106][crit:medium][vendor:[email protected]][level:component]With an emptyDisk defined and a specified serial number", func() {
// The following case is mostly similar to the alpine PVC test above, except using different VirtualMachineInstance.
It("[test_id:3135]should create a writeable emptyDisk with the specified serial number", func() {
// Start the VirtualMachineInstance with the empty disk attached
vmi = libvmi.NewAlpineWithTestTooling(
libvmi.WithMasqueradeNetworking()...,
)
vmi.Spec.Domain.Devices.Disks = append(vmi.Spec.Domain.Devices.Disks, virtv1.Disk{
Name: "emptydisk1",
Serial: diskSerial,
DiskDevice: virtv1.DiskDevice{
Disk: &virtv1.DiskTarget{
Bus: v1.DiskBusVirtio,
},
},
})
vmi.Spec.Volumes = append(vmi.Spec.Volumes, virtv1.Volume{
Name: "emptydisk1",
VolumeSource: virtv1.VolumeSource{
EmptyDisk: &virtv1.EmptyDiskSource{
Capacity: resource.MustParse("1Gi"),
},
},
})
vmi = tests.RunVMIAndExpectLaunch(vmi, 90)
Expect(console.LoginToAlpine(vmi)).To(Succeed())
By("Checking for the specified serial number")
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: "find /sys -type f -regex \".*/block/.*/serial\" | xargs cat\n"},
&expect.BExp{R: diskSerial},
}, 10)).To(Succeed())
})
})
Context("VirtIO-FS with multiple PVCs", func() {
pvc1 := "pvc-1"
pvc2 := "pvc-2"
createPVC := func(name string) {
sc, _ := libstorage.GetRWXFileSystemStorageClass()
pvc := libstorage.NewPVC(name, "1Gi", sc)
_, err = virtClient.CoreV1().PersistentVolumeClaims(util.NamespaceTestDefault).Create(context.Background(), pvc, metav1.CreateOptions{})
ExpectWithOffset(1, err).NotTo(HaveOccurred())
}
BeforeEach(func() {
checks.SkipTestIfNoFeatureGate(virtconfig.VirtIOFSGate)
createPVC(pvc1)
createPVC(pvc2)
})
AfterEach(func() {
libstorage.DeletePVC(pvc1)
libstorage.DeletePVC(pvc2)
})
DescribeTable("should be successfully started and accessible", func(option1, option2 libvmi.Option) {
virtiofsMountPath := func(pvcName string) string { return fmt.Sprintf("/mnt/virtiofs_%s", pvcName) }
virtiofsTestFile := func(virtiofsMountPath string) string { return fmt.Sprintf("%s/virtiofs_test", virtiofsMountPath) }
mountVirtiofsCommands := fmt.Sprintf(`#!/bin/bash
mkdir %s
mount -t virtiofs %s %s
touch %s
mkdir %s
mount -t virtiofs %s %s
touch %s
`, virtiofsMountPath(pvc1), pvc1, virtiofsMountPath(pvc1), virtiofsTestFile(virtiofsMountPath(pvc1)),
virtiofsMountPath(pvc2), pvc2, virtiofsMountPath(pvc2), virtiofsTestFile(virtiofsMountPath(pvc2)))
vmi = libvmi.NewFedora(
libvmi.WithCloudInitNoCloudUserData(mountVirtiofsCommands, true),
libvmi.WithFilesystemPVC(pvc1),
libvmi.WithFilesystemPVC(pvc2),
option1, option2,
)
vmi = tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 300)
// Wait for cloud init to finish and start the agent inside the vmi.
tests.WaitAgentConnected(virtClient, vmi)
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToFedora(vmi)).To(Succeed(), "Should be able to login to the Fedora VM")
virtioFsFileTestCmd := fmt.Sprintf("test -f /run/kubevirt-private/vmi-disks/%s/virtiofs_test && echo exist", pvc1)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
podVirtioFsFileExist, err := tests.ExecuteCommandOnPod(
virtClient,
pod,
"compute",
[]string{tests.BinBash, "-c", virtioFsFileTestCmd},
)
Expect(err).ToNot(HaveOccurred())
Expect(strings.Trim(podVirtioFsFileExist, "\n")).To(Equal("exist"))
virtioFsFileTestCmd = fmt.Sprintf("test -f /run/kubevirt-private/vmi-disks/%s/virtiofs_test && echo exist", pvc2)
pod = tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
podVirtioFsFileExist, err = tests.ExecuteCommandOnPod(
virtClient,
pod,
"compute",
[]string{tests.BinBash, "-c", virtioFsFileTestCmd},
)
Expect(err).ToNot(HaveOccurred())
Expect(strings.Trim(podVirtioFsFileExist, "\n")).To(Equal("exist"))
},
Entry("", func(instance *virtv1.VirtualMachineInstance) {}, func(instance *virtv1.VirtualMachineInstance) {}),
Entry("with passt enabled", libvmi.WithPasstInterfaceWithPort(), libvmi.WithNetwork(v1.DefaultPodNetwork())),
)
})
Context("VirtIO-FS with an empty PVC", func() {
var pvc = "empty-pvc1"
BeforeEach(func() {
checks.SkipTestIfNoFeatureGate(virtconfig.VirtIOFSGate)
libstorage.CreateHostPathPv(pvc, filepath.Join(testsuite.HostPathBase, pvc))
libstorage.CreateHostPathPVC(pvc, "1G")
})
AfterEach(func() {
libstorage.DeletePVC(pvc)
libstorage.DeletePV(pvc)
})
It("should be successfully started and virtiofs could be accessed", func() {
pvcName := fmt.Sprintf("disk-%s", pvc)
virtiofsMountPath := fmt.Sprintf("/mnt/virtiofs_%s", pvcName)
virtiofsTestFile := fmt.Sprintf("%s/virtiofs_test", virtiofsMountPath)
mountVirtiofsCommands := fmt.Sprintf(`#!/bin/bash
mkdir %s
mount -t virtiofs %s %s
touch %s
`, virtiofsMountPath, pvcName, virtiofsMountPath, virtiofsTestFile)
vmi = libvmi.NewFedora(
libvmi.WithCloudInitNoCloudUserData(mountVirtiofsCommands, true),
libvmi.WithFilesystemPVC(pvcName),
)
vmi = tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 300)
// Wait for cloud init to finish and start the agent inside the vmi.
tests.WaitAgentConnected(virtClient, vmi)
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToFedora(vmi)).To(Succeed(), "Should be able to login to the Fedora VM")
virtioFsFileTestCmd := fmt.Sprintf("test -f /run/kubevirt-private/vmi-disks/%s/virtiofs_test && echo exist", pvcName)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
podVirtioFsFileExist, err := tests.ExecuteCommandOnPod(
virtClient,
pod,
"compute",
[]string{tests.BinBash, "-c", virtioFsFileTestCmd},
)
Expect(err).ToNot(HaveOccurred())
Expect(strings.Trim(podVirtioFsFileExist, "\n")).To(Equal("exist"))
})
})
Context("Run a VMI with VirtIO-FS and a datavolume", func() {
var dataVolume *cdiv1.DataVolume
BeforeEach(func() {
checks.SkipTestIfNoFeatureGate(virtconfig.VirtIOFSGate)
if !libstorage.HasCDI() {
Skip("Skip DataVolume tests when CDI is not present")
}
sc, exists := libstorage.GetRWOFileSystemStorageClass()
if !exists {
Skip("Skip test when Filesystem storage is not present")
}
dataVolume = libdv.NewDataVolume(
libdv.WithRegistryURLSource(cd.DataVolumeImportUrlForContainerDisk(cd.ContainerDiskAlpine)),
libdv.WithPVC(sc, cd.CirrosVolumeSize, k8sv1.ReadWriteOnce, k8sv1.PersistentVolumeFilesystem),
)
})
AfterEach(func() {
libstorage.DeleteDataVolume(&dataVolume)
})
It("should be successfully started and virtiofs could be accessed", func() {
dataVolume, err = virtClient.CdiClient().CdiV1beta1().DataVolumes(util.NamespaceTestDefault).Create(context.Background(), dataVolume, metav1.CreateOptions{})
Expect(err).ToNot(HaveOccurred())
By("Waiting until the DataVolume is ready")
if libstorage.IsStorageClassBindingModeWaitForFirstConsumer(libstorage.Config.StorageRWOFileSystem) {
Eventually(ThisDV(dataVolume), 30).Should(BeInPhase(cdiv1.WaitForFirstConsumer))
}
virtiofsMountPath := fmt.Sprintf("/mnt/virtiofs_%s", dataVolume.Name)
virtiofsTestFile := fmt.Sprintf("%s/virtiofs_test", virtiofsMountPath)
mountVirtiofsCommands := fmt.Sprintf(`#!/bin/bash
mkdir %s
mount -t virtiofs %s %s
touch %s
`, virtiofsMountPath, dataVolume.Name, virtiofsMountPath, virtiofsTestFile)
vmi = libvmi.NewFedora(
libvmi.WithCloudInitNoCloudUserData(mountVirtiofsCommands, true),
libvmi.WithFilesystemDV(dataVolume.Name),
)
// with WFFC the run actually starts the import and then runs VM, so the timeout has to include both
// import and start
vmi = tests.RunVMIAndExpectLaunchWithDataVolume(vmi, dataVolume, 500)
// Wait for cloud init to finish and start the agent inside the vmi.
tests.WaitAgentConnected(virtClient, vmi)
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToFedora(vmi)).To(Succeed(), "Should be able to login to the Fedora VM")
By("Checking that virtio-fs is mounted")
listVirtioFSDisk := fmt.Sprintf("ls -l %s/*disk* | wc -l\n", virtiofsMountPath)
Expect(console.ExpectBatch(vmi, []expect.Batcher{
&expect.BSnd{S: listVirtioFSDisk},
&expect.BExp{R: console.RetValue("1")},
}, 30*time.Second)).To(Succeed(), "Should be able to access the mounted virtiofs file")
virtioFsFileTestCmd := fmt.Sprintf("test -f /run/kubevirt-private/vmi-disks/%s/virtiofs_test && echo exist", dataVolume.Name)
pod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
podVirtioFsFileExist, err := tests.ExecuteCommandOnPod(
virtClient,
pod,
"compute",
[]string{tests.BinBash, "-c", virtioFsFileTestCmd},
)
Expect(err).ToNot(HaveOccurred())
Expect(strings.Trim(podVirtioFsFileExist, "\n")).To(Equal("exist"))
err = virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
tests.WaitForVirtualMachineToDisappearWithTimeout(vmi, 120)
})
})
Context("[rfe_id:3106][crit:medium][vendor:[email protected]][level:component]With ephemeral alpine PVC", func() {
var isRunOnKindInfra bool
BeforeEach(func() {
isRunOnKindInfra = tests.IsRunningOnKindInfra()
})
Context("should be successfully", func() {
var pvName string
var nfsPod *k8sv1.Pod
BeforeEach(func() {
nfsPod = nil
pvName = ""
})
AfterEach(func() {
if vmi != nil {
By("Deleting the VMI")
Expect(virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})).To(Succeed())
By("Waiting for VMI to disappear")
tests.WaitForVirtualMachineToDisappearWithTimeout(vmi, 120)
}
})
AfterEach(func() {
if pvName != "" && pvName != tests.DiskAlpineHostPath {
// PVs can't be reused
By("Deleting PV and PVC")
tests.DeletePvAndPvc(pvName)
}
})
// The following case is mostly similar to the alpine PVC test above, except using different VirtualMachineInstance.
DescribeTable("started", func(newVMI VMICreationFunc, storageEngine string, family k8sv1.IPFamily) {
libnet.SkipWhenClusterNotSupportIPFamily(virtClient, family)
// Start the VirtualMachineInstance with the PVC attached
if storageEngine == "nfs" {
nfsPod = storageframework.InitNFS(testsuite.HostPathAlpine, "")
pvName = createNFSPvAndPvc(family, nfsPod)
} else {
pvName = tests.DiskAlpineHostPath
}
vmi = newVMI(pvName)
if storageEngine == "nfs" {
vmi = tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 120)
} else {
vmi = tests.RunVMIAndExpectLaunch(vmi, 120)
}
By(checkingVMInstanceConsoleOut)
Expect(console.LoginToAlpine(vmi)).To(Succeed())
},
Entry("[test_id:3136]with Ephemeral PVC", tests.NewRandomVMIWithEphemeralPVC, "", nil),
Entry("[test_id:4619]with Ephemeral PVC from NFS using ipv4 address of the NFS pod", tests.NewRandomVMIWithEphemeralPVC, "nfs", k8sv1.IPv4Protocol),
Entry("with Ephemeral PVC from NFS using ipv6 address of the NFS pod", tests.NewRandomVMIWithEphemeralPVC, "nfs", k8sv1.IPv6Protocol),
)
})
// Not a candidate for testing on NFS because the VMI is restarted and NFS PVC can't be re-used
It("[test_id:3137]should not persist data", func() {
vmi = tests.NewRandomVMIWithEphemeralPVC(tests.DiskAlpineHostPath)
By("Starting the VirtualMachineInstance")
var createdVMI *virtv1.VirtualMachineInstance
if isRunOnKindInfra {
createdVMI = tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 90)
} else {
createdVMI = tests.RunVMIAndExpectLaunch(vmi, 90)
}
By("Writing an arbitrary file to it's EFI partition")
Expect(console.LoginToAlpine(vmi)).To(Succeed())
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
// Because "/" is mounted on tmpfs, we need something that normally persists writes - /dev/sda2 is the EFI partition formatted as vFAT.
&expect.BSnd{S: "mount /dev/sda2 /mnt\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: tests.EchoLastReturnValue},
&expect.BExp{R: console.RetValue("0")},
&expect.BSnd{S: "echo content > /mnt/checkpoint\n"},
&expect.BExp{R: console.PromptExpression},
// The QEMU process will be killed, therefore the write must be flushed to the disk.
&expect.BSnd{S: "sync\n"},
&expect.BExp{R: console.PromptExpression},
}, 200)).To(Succeed())
By("Killing a VirtualMachineInstance")
err = virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
tests.WaitForVirtualMachineToDisappearWithTimeout(createdVMI, 120)
By("Starting the VirtualMachineInstance again")
if isRunOnKindInfra {
tests.RunVMIAndExpectLaunchIgnoreWarnings(vmi, 90)
} else {
tests.RunVMIAndExpectLaunch(vmi, 90)
}
By("Making sure that the previously written file is not present")
Expect(console.LoginToAlpine(vmi)).To(Succeed())
Expect(console.SafeExpectBatch(vmi, []expect.Batcher{
// Same story as when first starting the VirtualMachineInstance - the checkpoint, if persisted, is located at /dev/sda2.
&expect.BSnd{S: "mount /dev/sda2 /mnt\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: tests.EchoLastReturnValue},
&expect.BExp{R: console.RetValue("0")},
&expect.BSnd{S: "cat /mnt/checkpoint &> /dev/null\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: tests.EchoLastReturnValue},
&expect.BExp{R: console.RetValue("1")},
}, 200)).To(Succeed())
})
})
Context("[rfe_id:3106][crit:medium][vendor:[email protected]][level:component]With VirtualMachineInstance with two PVCs", func() {
BeforeEach(func() {
// Setup second PVC to use in this context
libstorage.CreateHostPathPv(tests.CustomHostPath, testsuite.HostPathCustom)
libstorage.CreateHostPathPVC(tests.CustomHostPath, "1Gi")
})
// Not a candidate for testing on NFS because the VMI is restarted and NFS PVC can't be re-used
It("[test_id:3138]should start vmi multiple times", func() {
vmi = libvmi.New(
libvmi.WithPersistentVolumeClaim("disk0", tests.DiskAlpineHostPath),
libvmi.WithPersistentVolumeClaim("disk1", tests.DiskCustomHostPath),
libvmi.WithResourceMemory("256Mi"),
libvmi.WithRng())
num := 3
By("Starting and stopping the VirtualMachineInstance number of times")
for i := 1; i <= num; i++ {
obj := tests.RunVMIAndExpectLaunch(vmi, 240)
// Verify console on last iteration to verify the VirtualMachineInstance is still booting properly
// after being restarted multiple times
if i == num {
By("Checking that the second disk is present")
Expect(console.LoginToAlpine(obj)).To(Succeed())
Expect(console.SafeExpectBatch(obj, []expect.Batcher{
&expect.BSnd{S: "blockdev --getsize64 /dev/vdb\n"},
&expect.BExp{R: "1013972992"},
}, 200)).To(Succeed())
}
err = virtClient.VirtualMachineInstance(obj.Namespace).Delete(obj.Name, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
Eventually(ThisVMI(obj), 120).Should(BeGone())
}
})
})
Context("[Serial]With feature gates disabled for", func() {
It("[test_id:4620]HostDisk, it should fail to start a VMI", func() {
tests.DisableFeatureGate(virtconfig.HostDiskGate)
vmi = tests.NewRandomVMIWithHostDisk("somepath", virtv1.HostDiskExistsOrCreate, "")
virtClient, err := kubecli.GetKubevirtClient()
Expect(err).ToNot(HaveOccurred())
_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("HostDisk feature gate is not enabled"))
})
It("VirtioFS, it should fail to start a VMI", func() {
tests.DisableFeatureGate(virtconfig.VirtIOFSGate)
vmi := libvmi.NewFedora(libvmi.WithFilesystemDV("something"))
virtClient, err := kubecli.GetKubevirtClient()
Expect(err).ToNot(HaveOccurred())
_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("virtiofs feature gate is not enabled"))
})
})
Context("[rfe_id:2298][crit:medium][vendor:[email protected]][level:component] With HostDisk and PVC initialization", func() {
BeforeEach(func() {
if !checks.HasFeature(virtconfig.HostDiskGate) {
Skip("Cluster has the HostDisk featuregate disabled, skipping the tests")
}
})
Context("With a HostDisk defined", func() {
var hostDiskDir string
var nodeName string
BeforeEach(func() {
hostDiskDir = tests.RandTmpDir()
nodeName = ""
})
AfterEach(func() {
if vmi != nil {
err = virtClient.VirtualMachineInstance(vmi.Namespace).Delete(vmi.Name, &metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
Expect(err).ToNot(HaveOccurred())
}
Eventually(ThisVMI(vmi), 30).Should(Or(BeGone(), BeInPhase(virtv1.Failed), BeInPhase(virtv1.Succeeded)))
}
if nodeName != "" {
tests.RemoveHostDiskImage(hostDiskDir, nodeName)
}
})
Context("With 'DiskExistsOrCreate' type", func() {
var diskName string
var diskPath string
BeforeEach(func() {
diskName = fmt.Sprintf("disk-%s.img", uuid.NewRandom().String())
diskPath = filepath.Join(hostDiskDir, diskName)
})
DescribeTable("Should create a disk image and start", func(driver v1.DiskBus) {
By(startingVMInstance)
// do not choose a specific node to run the test
vmi = tests.NewRandomVMIWithHostDisk(diskPath, virtv1.HostDiskExistsOrCreate, "")
vmi.Spec.Domain.Devices.Disks[0].DiskDevice.Disk.Bus = driver
tests.RunVMIAndExpectLaunch(vmi, 30)
By("Checking if disk.img has been created")
vmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
nodeName = vmiPod.Spec.NodeName
output, err := tests.ExecuteCommandOnPod(
virtClient,
vmiPod,
vmiPod.Spec.Containers[0].Name,
[]string{"find", hostdisk.GetMountedHostDiskDir(hostDiskName), "-name", diskName, "-size", "1G", "-o", "-size", "+1G"},
)
Expect(err).ToNot(HaveOccurred())
Expect(output).To(ContainSubstring(hostdisk.GetMountedHostDiskPath(hostDiskName, diskPath)))
},
Entry("[test_id:851]with virtio driver", v1.DiskBusVirtio),
Entry("[test_id:3057]with sata driver", v1.DiskBusSATA),
)
It("[test_id:3107]should start with multiple hostdisks in the same directory", func() {
By(startingVMInstance)
// do not choose a specific node to run the test
vmi = tests.NewRandomVMIWithHostDisk(diskPath, virtv1.HostDiskExistsOrCreate, "")
tests.AddHostDisk(vmi, filepath.Join(hostDiskDir, "another.img"), virtv1.HostDiskExistsOrCreate, "anotherdisk")
tests.RunVMIAndExpectLaunch(vmi, 30)
By("Checking if another.img has been created")
vmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
nodeName = vmiPod.Spec.NodeName
output, err := tests.ExecuteCommandOnPod(
virtClient,
vmiPod,
vmiPod.Spec.Containers[0].Name,
[]string{"find", hostdisk.GetMountedHostDiskDir("anotherdisk"), "-size", "1G", "-o", "-size", "+1G"},
)
Expect(err).ToNot(HaveOccurred())
Expect(output).To(ContainSubstring(hostdisk.GetMountedHostDiskPath("anotherdisk", filepath.Join(hostDiskDir, "another.img"))))
By("Checking if disk.img has been created")
output, err = tests.ExecuteCommandOnPod(
virtClient,
vmiPod,
vmiPod.Spec.Containers[0].Name,
[]string{"find", hostdisk.GetMountedHostDiskDir(hostDiskName), "-size", "1G", "-o", "-size", "+1G"},
)
Expect(err).ToNot(HaveOccurred())
Expect(output).To(ContainSubstring(hostdisk.GetMountedHostDiskPath(hostDiskName, diskPath)))
})
})
Context("With 'DiskExists' type", func() {
var diskPath string
var diskName string
BeforeEach(func() {
diskName = fmt.Sprintf("disk-%s.img", uuid.NewRandom().String())
diskPath = filepath.Join(hostDiskDir, diskName)
// create a disk image before test
job := tests.CreateHostDiskImage(diskPath)
job, err = virtClient.CoreV1().Pods(testsuite.NamespacePrivileged).Create(context.Background(), job, metav1.CreateOptions{})
Expect(err).ToNot(HaveOccurred())
Eventually(ThisPod(job), 30*time.Second, 1*time.Second).Should(BeInPhase(k8sv1.PodSucceeded))
pod, err := ThisPod(job)()
Expect(err).NotTo(HaveOccurred())
nodeName = pod.Spec.NodeName
})
It("[test_id:2306]Should use existing disk image and start", func() {
By(startingVMInstance)
vmi = tests.NewRandomVMIWithHostDisk(diskPath, virtv1.HostDiskExists, nodeName)
tests.RunVMIAndExpectLaunch(vmi, 30)
By("Checking if disk.img exists")
vmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
output, err := tests.ExecuteCommandOnPod(
virtClient,
vmiPod,
vmiPod.Spec.Containers[0].Name,
[]string{"find", hostdisk.GetMountedHostDiskDir(hostDiskName), "-name", diskName},
)
Expect(err).ToNot(HaveOccurred())
Expect(output).To(ContainSubstring(diskName))
})
It("[test_id:847]Should fail with a capacity option", func() {
By(startingVMInstance)
vmi = tests.NewRandomVMIWithHostDisk(diskPath, virtv1.HostDiskExists, nodeName)
for i, volume := range vmi.Spec.Volumes {
if volume.HostDisk != nil {
vmi.Spec.Volumes[i].HostDisk.Capacity = resource.MustParse("1Gi")
break
}
}
_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(HaveOccurred())
})
})
Context("With unknown hostDisk type", func() {
It("[test_id:852]Should fail to start VMI", func() {
By(startingVMInstance)
vmi = tests.NewRandomVMIWithHostDisk("/data/unknown.img", "unknown", "")
_, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
Expect(err).To(HaveOccurred())
})
})
})
Context("With multiple empty PVCs", func() {
var pvcs = []string{}
var node string
var nodeSelector map[string]string
BeforeEach(func() {
for i := 0; i < 3; i++ {
pvcs = append(pvcs, fmt.Sprintf("empty-pvc-%d-%s", i, rand.String(5)))
}
for _, pvc := range pvcs {
hostpath := filepath.Join(testsuite.HostPathBase, pvc)
node = libstorage.CreateHostPathPv(pvc, hostpath)
libstorage.CreateHostPathPVC(pvc, "1G")
if checks.HasFeature(virtconfig.NonRoot) {
nodeSelector = map[string]string{"kubernetes.io/hostname": node}
By("changing permissions to qemu")
args := []string{fmt.Sprintf(`chown 107 %s`, hostpath)}
pod := tests.RenderHostPathPod("tmp-change-owner-job", hostpath, k8sv1.HostPathDirectoryOrCreate, k8sv1.MountPropagationNone, []string{"/bin/bash", "-c"}, args)
pod.Spec.NodeSelector = nodeSelector
tests.RunPodAndExpectCompletion(pod)
}
}
})
AfterEach(func() {
for _, pvc := range pvcs {
libstorage.DeletePVC(pvc)
libstorage.DeletePV(pvc)
}
})
// Not a candidate for NFS testing because multiple VMIs are started
It("[test_id:868] Should initialize an empty PVC by creating a disk.img", func() {
for _, pvc := range pvcs {
By(startingVMInstance)
vmi = libvmi.New(
libvmi.WithPersistentVolumeClaim("disk0", fmt.Sprintf("disk-%s", pvc)),
libvmi.WithResourceMemory("256Mi"),
libvmi.WithNetwork(v1.DefaultPodNetwork()),
libvmi.WithInterface(libvmi.InterfaceDeviceWithMasqueradeBinding()),
libvmi.WithNodeSelectorFor(&k8sv1.Node{ObjectMeta: metav1.ObjectMeta{Name: node}}))
tests.RunVMIAndExpectLaunch(vmi, 90)
By("Checking if disk.img exists")
vmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)
output, err := tests.ExecuteCommandOnPod(
virtClient,
vmiPod,
vmiPod.Spec.Containers[0].Name,
[]string{"find", "/var/run/kubevirt-private/vmi-disks/disk0/", "-name", diskImgName, "-size", "1G", "-o", "-size", "+1G"},
)
Expect(err).ToNot(HaveOccurred())
By("Checking if a disk image for PVC has been created")
Expect(strings.Contains(output, diskImgName)).To(BeTrue())
}
})
})
Context("With smaller than requested PVCs", func() {