forked from kubevirt/kubevirt
-
Notifications
You must be signed in to change notification settings - Fork 3
/
operator_test.go
1488 lines (1220 loc) · 54.3 KB
/
operator_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 Red Hat, Inc.
*
*/
package tests_test
import (
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"time"
jsonpatch "github.com/evanphx/json-patch"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
v12 "k8s.io/api/apps/v1"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
extclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
aggregatorclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
v1 "kubevirt.io/client-go/api/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/client-go/log"
cdiv1 "kubevirt.io/containerized-data-importer/pkg/apis/core/v1alpha1"
"kubevirt.io/kubevirt/pkg/controller"
"kubevirt.io/kubevirt/pkg/virt-operator/creation/components"
"kubevirt.io/kubevirt/pkg/virt-operator/util"
"kubevirt.io/kubevirt/tests"
cd "kubevirt.io/kubevirt/tests/containerdisk"
"kubevirt.io/kubevirt/tests/flags"
)
type vmYamlDefinition struct {
apiVersion string
vmName string
generatedYaml string
yamlFile string
}
var _ = Describe("Operator", func() {
var originalKv *v1.KubeVirt
var originalCDI *cdiv1.CDI
var originalKubeVirtConfig *k8sv1.ConfigMap
var originalOperatorVersion string
var err error
var workDir string
var virtClient kubecli.KubevirtClient
var aggregatorClient *aggregatorclient.Clientset
var k8sClient string
var vmYamls []vmYamlDefinition
var (
copyOriginalCDI func() *cdiv1.CDI
copyOriginalKv func() *v1.KubeVirt
createKv func(*v1.KubeVirt)
createCdi func()
sanityCheckDeploymentsExistWithNS func(string)
sanityCheckDeploymentsExist func()
sanityCheckDeploymentsDeleted func()
allPodsAreReady func(*v1.KubeVirt)
waitForUpdateCondition func(*v1.KubeVirt)
waitForKvWithTimeout func(*v1.KubeVirt, int)
waitForKv func(*v1.KubeVirt)
patchKvVersionAndRegistry func(string, string, string)
patchKvVersion func(string, string)
parseDaemonset func(string) (*v12.DaemonSet, string, string, string, string)
parseImage func(string, string) (string, string, string)
parseDeployment func(string) (*v12.Deployment, string, string, string, string)
parseOperatorImage func() (*v12.Deployment, string, string, string, string)
patchOperator func(*string, *string) bool
deleteAllKvAndWait func(bool)
usesSha func(string) bool
ensureShasums func()
generatePreviousVersionVmYamls func(string, string)
)
tests.BeforeAll(func() {
virtClient, err = kubecli.GetKubevirtClient()
tests.PanicOnError(err)
config, err := kubecli.GetConfig()
tests.PanicOnError(err)
aggregatorClient = aggregatorclient.NewForConfigOrDie(config)
k8sClient = tests.GetK8sCmdClient()
copyOriginalCDI = func() *cdiv1.CDI {
newCDI := &cdiv1.CDI{
Spec: *originalCDI.Spec.DeepCopy(),
}
newCDI.Name = originalCDI.Name
newCDI.Namespace = originalCDI.Namespace
newCDI.ObjectMeta.Labels = originalCDI.ObjectMeta.Labels
newCDI.ObjectMeta.Annotations = originalCDI.ObjectMeta.Annotations
return newCDI
}
copyOriginalKv = func() *v1.KubeVirt {
newKv := &v1.KubeVirt{
Spec: *originalKv.Spec.DeepCopy(),
}
newKv.Name = originalKv.Name
newKv.Namespace = originalKv.Namespace
newKv.ObjectMeta.Labels = originalKv.ObjectMeta.Labels
newKv.ObjectMeta.Annotations = originalKv.ObjectMeta.Annotations
return newKv
}
createKv = func(newKv *v1.KubeVirt) {
Eventually(func() error {
_, err = virtClient.KubeVirt(newKv.Namespace).Create(newKv)
return err
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
createCdi = func() {
_, err = virtClient.CdiClient().CdiV1alpha1().CDIs().Create(copyOriginalCDI())
Expect(err).ToNot(HaveOccurred())
Eventually(func() bool {
cdi, err := virtClient.CdiClient().CdiV1alpha1().CDIs().Get(originalCDI.Name, metav1.GetOptions{})
if err != nil {
return false
} else if cdi.Status.Phase != cdiv1.CDIPhaseDeployed {
return false
}
return true
}, 240*time.Second, 1*time.Second).Should(BeTrue())
}
sanityCheckDeploymentsExistWithNS = func(namespace string) {
Eventually(func() error {
for _, deployment := range []string{"virt-api", "virt-controller"} {
_, err := virtClient.AppsV1().Deployments(namespace).Get(deployment, metav1.GetOptions{})
if err != nil {
return err
}
}
return nil
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
sanityCheckDeploymentsExist = func() {
sanityCheckDeploymentsExistWithNS(flags.KubeVirtInstallNamespace)
}
sanityCheckDeploymentsDeleted = func() {
Eventually(func() error {
for _, deployment := range []string{"virt-api", "virt-controller"} {
_, err := virtClient.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(deployment, metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
return err
}
}
return nil
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
allPodsAreReady = func(kv *v1.KubeVirt) {
Eventually(func() error {
curKv, err := virtClient.KubeVirt(kv.Namespace).Get(kv.Name, &metav1.GetOptions{})
if err != nil {
return err
}
if curKv.Status.TargetDeploymentID != curKv.Status.ObservedDeploymentID {
return fmt.Errorf("Target and obeserved id don't match")
}
podsReadyAndOwned := 0
pods, err := virtClient.CoreV1().Pods(curKv.Namespace).List(metav1.ListOptions{LabelSelector: "kubevirt.io"})
if err != nil {
return err
}
for _, pod := range pods.Items {
managed, ok := pod.Labels[v1.ManagedByLabel]
if !ok || managed != v1.ManagedByLabelOperatorValue {
continue
}
if pod.Status.Phase != k8sv1.PodRunning {
return fmt.Errorf("Waiting for pod %s with phase %s to reach Running phase", pod.Name, pod.Status.Phase)
}
for _, containerStatus := range pod.Status.ContainerStatuses {
if !containerStatus.Ready {
return fmt.Errorf("Waiting for pod %s to have all containers in Ready state", pod.Name)
}
}
id, ok := pod.Annotations[v1.InstallStrategyIdentifierAnnotation]
if !ok {
return fmt.Errorf("Pod %s is owned by operator but has no id annotation", pod.Name)
}
expectedID := curKv.Status.ObservedDeploymentID
if id != expectedID {
return fmt.Errorf("Pod %s is of version %s when we expected id %s", pod.Name, id, expectedID)
}
podsReadyAndOwned++
}
// this just sanity checks that at least one pod was found and verified.
// 0 would indicate our labeling was incorrect.
Expect(podsReadyAndOwned).ToNot(Equal(0))
return nil
}, 120*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
waitForUpdateCondition = func(kv *v1.KubeVirt) {
Eventually(func() error {
kv, err := virtClient.KubeVirt(kv.Namespace).Get(kv.Name, &metav1.GetOptions{})
if err != nil {
return err
}
available := false
progressing := false
degraded := false
for _, condition := range kv.Status.Conditions {
if condition.Type == v1.KubeVirtConditionAvailable && condition.Status == k8sv1.ConditionTrue {
available = true
} else if condition.Type == v1.KubeVirtConditionProgressing && condition.Status == k8sv1.ConditionTrue {
progressing = true
} else if condition.Type == v1.KubeVirtConditionDegraded && condition.Status == k8sv1.ConditionTrue {
degraded = true
}
}
if !available || !progressing || !degraded {
return fmt.Errorf("Waiting for conditions to indicate update (conditions: %+v)", kv.Status.Conditions)
}
return nil
}, 120*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
waitForKvWithTimeout = func(newKv *v1.KubeVirt, timeoutSeconds int) {
Eventually(func() error {
kv, err := virtClient.KubeVirt(newKv.Namespace).Get(newKv.Name, &metav1.GetOptions{})
if err != nil {
return err
}
if kv.Status.Phase != v1.KubeVirtPhaseDeployed {
return fmt.Errorf("Waiting for phase to be deployed (current phase: %+v)", kv.Status.Phase)
}
available := false
progressing := true
degraded := true
created := false
for _, condition := range kv.Status.Conditions {
if condition.Type == v1.KubeVirtConditionAvailable && condition.Status == k8sv1.ConditionTrue {
available = true
} else if condition.Type == v1.KubeVirtConditionProgressing && condition.Status == k8sv1.ConditionFalse {
progressing = false
} else if condition.Type == v1.KubeVirtConditionDegraded && condition.Status == k8sv1.ConditionFalse {
degraded = false
} else if condition.Type == v1.KubeVirtConditionCreated && condition.Status == k8sv1.ConditionTrue {
created = true
}
}
if !available || progressing || degraded || !created {
return fmt.Errorf("Waiting for conditions to indicate deployment (conditions: %+v)", kv.Status.Conditions)
}
return nil
}, time.Duration(timeoutSeconds)*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
waitForKv = func(newKv *v1.KubeVirt) {
waitForKvWithTimeout(newKv, 300)
}
patchKvVersionAndRegistry = func(name string, version string, registry string) {
data := []byte(fmt.Sprintf(`[{ "op": "replace", "path": "/spec/imageTag", "value": "%s"},{ "op": "replace", "path": "/spec/imageRegistry", "value": "%s"}]`, version, registry))
Eventually(func() error {
_, err := virtClient.KubeVirt(flags.KubeVirtInstallNamespace).Patch(name, types.JSONPatchType, data)
return err
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
patchKvVersion = func(name string, version string) {
data := []byte(fmt.Sprintf(`[{ "op": "add", "path": "/spec/imageTag", "value": "%s"}]`, version))
Eventually(func() error {
_, err := virtClient.KubeVirt(flags.KubeVirtInstallNamespace).Patch(name, types.JSONPatchType, data)
return err
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
parseDaemonset = func(name string) (daemonSet *v12.DaemonSet, image, registry, imagePrefix, version string) {
var err error
daemonSet, err = virtClient.AppsV1().DaemonSets(flags.KubeVirtInstallNamespace).Get(name, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
image = daemonSet.Spec.Template.Spec.Containers[0].Image
imageRegEx := regexp.MustCompile(fmt.Sprintf("%s%s%s", `^(.*)/(.*)`, name, `([@:].*)?$`))
matches := imageRegEx.FindAllStringSubmatch(image, 1)
Expect(len(matches)).To(Equal(1))
Expect(len(matches[0])).To(Equal(4))
registry = matches[0][1]
imagePrefix = matches[0][2]
version = matches[0][3]
return
}
parseImage = func(name, image string) (registry, imagePrefix, version string) {
imageRegEx := regexp.MustCompile(fmt.Sprintf("%s%s%s", `^(.*)/(.*)`, name, `([@:].*)?$`))
matches := imageRegEx.FindAllStringSubmatch(image, 1)
Expect(len(matches)).To(Equal(1))
Expect(len(matches[0])).To(Equal(4))
registry = matches[0][1]
imagePrefix = matches[0][2]
version = matches[0][3]
return
}
parseDeployment = func(name string) (deployment *v12.Deployment, image, registry, imagePrefix, version string) {
var err error
deployment, err = virtClient.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(name, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
image = deployment.Spec.Template.Spec.Containers[0].Image
registry, imagePrefix, version = parseImage(name, image)
return
}
parseOperatorImage = func() (operator *v12.Deployment, image, registry, imagePrefix, version string) {
return parseDeployment("virt-operator")
}
patchOperator = func(imagePrefix, version *string) bool {
modified := true
Eventually(func() error {
operator, oldImage, registry, oldPrefix, oldVersion := parseOperatorImage()
if imagePrefix == nil {
// keep old prefix
imagePrefix = &oldPrefix
}
if version == nil {
// keep old version
version = &oldVersion
} else {
newVersion := components.AddVersionSeparatorPrefix(*version)
version = &newVersion
}
newImage := fmt.Sprintf("%s/%svirt-operator%s", registry, *imagePrefix, *version)
if oldImage == newImage {
modified = false
return nil
}
operator.Spec.Template.Spec.Containers[0].Image = newImage
for idx, env := range operator.Spec.Template.Spec.Containers[0].Env {
if env.Name == util.OperatorImageEnvName {
env.Value = newImage
operator.Spec.Template.Spec.Containers[0].Env[idx] = env
break
}
}
newTemplate, _ := json.Marshal(operator.Spec.Template)
op := fmt.Sprintf(`[{ "op": "replace", "path": "/spec/template", "value": %s }]`, string(newTemplate))
_, err = virtClient.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Patch("virt-operator", types.JSONPatchType, []byte(op))
return err
}, 10*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
return modified
}
deleteAllKvAndWait = func(ignoreOriginal bool) {
Eventually(func() error {
kvs := tests.GetKvList(virtClient)
deleteCount := 0
for _, kv := range kvs {
if ignoreOriginal && kv.Name == originalKv.Name {
continue
}
deleteCount++
if kv.DeletionTimestamp == nil {
err := virtClient.KubeVirt(kv.Namespace).Delete(kv.Name, &metav1.DeleteOptions{})
if err != nil {
return err
}
}
}
if deleteCount != 0 {
return fmt.Errorf("still waiting on %d kvs to delete", deleteCount)
}
return nil
}, 240*time.Second, 1*time.Second).ShouldNot(HaveOccurred())
}
usesSha = func(image string) bool {
return strings.Contains(image, "@sha256:")
}
ensureShasums = func() {
if flags.SkipShasumCheck {
log.Log.Warning("Cannot use shasums, skipping")
return
}
for _, name := range []string{"virt-operator", "virt-api", "virt-controller"} {
deployment, err := virtClient.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(name, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(usesSha(deployment.Spec.Template.Spec.Containers[0].Image)).To(BeTrue(), fmt.Sprintf("%s should use sha", name))
}
handler, err := virtClient.AppsV1().DaemonSets(flags.KubeVirtInstallNamespace).Get("virt-handler", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(usesSha(handler.Spec.Template.Spec.Containers[0].Image)).To(BeTrue(), "virt-handler should use sha")
}
// make sure virt deployments use shasums before we start
ensureShasums()
originalKv = tests.GetCurrentKv(virtClient)
originalKubeVirtConfig, err = virtClient.CoreV1().ConfigMaps(flags.KubeVirtInstallNamespace).Get("kubevirt-config", metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
Expect(err).ToNot(HaveOccurred())
}
if errors.IsNotFound(err) {
// create an empty kubevirt-config configmap if none exists.
cfgMap := &k8sv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Name: "kubevirt-config"},
Data: map[string]string{
"feature-gates": "",
},
}
originalKubeVirtConfig, err = virtClient.CoreV1().ConfigMaps(flags.KubeVirtInstallNamespace).Create(cfgMap)
Expect(err).ToNot(HaveOccurred())
}
// save the operator sha
_, _, _, _, version := parseOperatorImage()
Expect(strings.HasPrefix(version, "@")).To(BeTrue())
originalOperatorVersion = strings.TrimPrefix(version, "@")
if tests.HasDataVolumeCRD() {
cdiList, err := virtClient.CdiClient().CdiV1alpha1().CDIs().List(metav1.ListOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(len(cdiList.Items)).To(Equal(1))
originalCDI = &cdiList.Items[0]
}
generatePreviousVersionVmYamls = func(previousImageRegistry string, previousImageTag string) {
ext, err := extclient.NewForConfig(virtClient.Config())
Expect(err).ToNot(HaveOccurred())
crd, err := ext.ApiextensionsV1beta1().CustomResourceDefinitions().Get("virtualmachines.kubevirt.io", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
// Generate a vm Yaml for every version supported in the currently deployed KubeVirt
supportedVersions := []string{}
if len(crd.Spec.Versions) > 0 {
for _, version := range crd.Spec.Versions {
supportedVersions = append(supportedVersions, version.Name)
}
} else {
supportedVersions = append(supportedVersions, crd.Spec.Version)
}
for _, version := range supportedVersions {
vmYaml := fmt.Sprintf(`apiVersion: kubevirt.io/%s
kind: VirtualMachine
metadata:
labels:
kubevirt.io/vm: vm-%s
name: vm-%s
spec:
runStrategy: Manual
template:
metadata:
labels:
kubevirt.io/vm: vm-%s
spec:
domain:
devices:
disks:
- disk:
bus: virtio
name: containerdisk
- disk:
bus: virtio
name: cloudinitdisk
machine:
type: ""
resources:
requests:
memory: 64M
terminationGracePeriodSeconds: 0
volumes:
- containerDisk:
image: %s/%s-container-disk-demo:%s
name: containerdisk
- cloudInitNoCloud:
userData: |
#!/bin/sh
echo 'printed from cloud-init userdata'
name: cloudinitdisk
`, version, version, version, version, previousImageRegistry, cd.ContainerDiskCirros, previousImageTag)
yamlFile := filepath.Join(workDir, fmt.Sprintf("vm-%s.yaml", version))
err = ioutil.WriteFile(yamlFile, []byte(vmYaml), 0644)
Expect(err).ToNot(HaveOccurred())
vmYamls = append(vmYamls, vmYamlDefinition{
apiVersion: version,
vmName: "vm-" + version,
generatedYaml: vmYaml,
yamlFile: yamlFile,
})
}
}
})
BeforeEach(func() {
tests.BeforeTestCleanup()
workDir, err = ioutil.TempDir("", tests.TempDirPrefix+"-")
Expect(err).ToNot(HaveOccurred())
vmYamls = []vmYamlDefinition{}
verifyOperatorWebhookCertificate()
})
AfterEach(func() {
ignoreDeleteOriginalKV := true
curKubeVirtConfig, err := virtClient.CoreV1().ConfigMaps(flags.KubeVirtInstallNamespace).Get("kubevirt-config", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
// if revision changed, patch data and reload everything
if curKubeVirtConfig.ResourceVersion != originalKubeVirtConfig.ResourceVersion {
ignoreDeleteOriginalKV = false
// Add Spec Patch
newData, err := json.Marshal(originalKubeVirtConfig.Data)
Expect(err).ToNot(HaveOccurred())
data := fmt.Sprintf(`[{ "op": "replace", "path": "/data", "value": %s }]`, string(newData))
originalKubeVirtConfig, err = virtClient.CoreV1().ConfigMaps(flags.KubeVirtInstallNamespace).Patch("kubevirt-config", types.JSONPatchType, []byte(data))
Expect(err).ToNot(HaveOccurred())
}
deleteAllKvAndWait(ignoreDeleteOriginalKV)
kvs := tests.GetKvList(virtClient)
if len(kvs) == 0 {
createKv(copyOriginalKv())
}
modified := patchOperator(nil, &originalOperatorVersion)
if modified {
// make sure we wait until redeploymemt started
waitForUpdateCondition(originalKv)
}
waitForKv(originalKv)
allPodsAreReady(originalKv)
if workDir != "" {
err = os.RemoveAll(workDir)
workDir = ""
Expect(err).ToNot(HaveOccurred())
}
// repost original CDI object if it doesn't still exist
// in order to restore original environment
if originalCDI != nil {
cdiExists := false
// ensure we wait for cdi to finish deleting before restoring it
// in the event that cdi has the deletionTimestamp set.
Eventually(func() bool {
cdi, err := virtClient.CdiClient().CdiV1alpha1().CDIs().Get(originalCDI.Name, metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
// cdi isn't deleting and doesn't exist.
return true
} else {
Expect(err).ToNot(HaveOccurred())
}
// wait for cdi to delete if deletionTimestamp is set
if cdi.DeletionTimestamp != nil {
return false
}
cdiExists = true
return true
}, 240*time.Second, 1*time.Second).Should(BeTrue())
if !cdiExists {
createCdi()
}
}
// make sure virt deployments use shasums again after each test
ensureShasums()
// ensure that the state is fully restored after destructive tests
verifyOperatorWebhookCertificate()
})
It("[test_id:1746]should have created and available condition", func() {
kv := tests.GetCurrentKv(virtClient)
By("vyrifying that created and available condition is present")
waitForKv(kv)
})
Describe("[rfe_id:2291][crit:high][vendor:[email protected]][level:component]should start a VM", func() {
It("[test_id:3144]using virt-launcher with a shasum", func() {
if flags.SkipShasumCheck {
Skip("Cannot currently test shasums, skipping")
}
By("starting a VM")
vmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskCirros))
vmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)
Expect(err).To(BeNil())
tests.WaitForSuccessfulVMIStart(vmi)
By("getting virt-launcher")
uid := vmi.GetObjectMeta().GetUID()
labelSelector := fmt.Sprintf(v1.CreatedByLabel + "=" + string(uid))
pods, err := virtClient.CoreV1().Pods(tests.NamespaceTestDefault).List(metav1.ListOptions{LabelSelector: labelSelector})
Expect(err).ToNot(HaveOccurred(), "Should list pods")
Expect(len(pods.Items)).To(Equal(1))
Expect(usesSha(pods.Items[0].Spec.Containers[0].Image)).To(BeTrue(), "launcher pod should use shasum")
})
})
Describe("[rfe_id:2291][crit:high][vendor:[email protected]][level:component]should update kubevirt", func() {
// This test is installing a previous release of KubeVirt
// running a VM/VMI using that previous release
// Updating KubeVirt to the target tested code
// Ensuring VM/VMI is still operational after the update from previous release.
It("[test_id:3145]from previous release to target tested release", func() {
previousImageTag := flags.PreviousReleaseTag
previousImageRegistry := flags.PreviousReleaseRegistry
if previousImageTag == "" {
previousImageTag, err = tests.DetectLatestUpstreamOfficialTag()
Expect(err).ToNot(HaveOccurred())
By(fmt.Sprintf("By Using detected tag %s", previousImageTag))
} else {
By(fmt.Sprintf("By Using user defined tag %s", previousImageTag))
}
curVersion := originalKv.Status.ObservedKubeVirtVersion
curRegistry := originalKv.Status.ObservedKubeVirtRegistry
allPodsAreReady(originalKv)
sanityCheckDeploymentsExist()
// Delete current KubeVirt install so we can install previous release.
By("Deleting KubeVirt object")
deleteAllKvAndWait(false)
By("Sanity Checking Deployments infrastructure is deleted")
sanityCheckDeploymentsDeleted()
// Install Previous Release of KubeVirt
By(fmt.Sprintf("Creating KubeVirt Object with Previous Release: %s using registry %s", previousImageTag, previousImageRegistry))
kv := copyOriginalKv()
kv.Name = "kubevirt-release-install"
kv.Spec.ImageTag = previousImageTag
kv.Spec.ImageRegistry = previousImageRegistry
createKv(kv)
// Wait for Previous Release to come online
// wait 7 minutes because this test involves pulling containers
// over the internet related to the latest kubevirt release
By("Waiting for KV to stabilize")
waitForKvWithTimeout(kv, 420)
By("Verifying infrastructure is Ready")
allPodsAreReady(kv)
sanityCheckDeploymentsExist()
// kubectl API discovery cache only refreshes every 10 minutes
// Since we're likely dealing with api additions/removals here, we
// need to ensure we're using a different cache directory after
// the update from the previous release occurs.
oldClientCacheDir := workDir + "/oldclient"
err = os.MkdirAll(oldClientCacheDir, 0755)
Expect(err).ToNot(HaveOccurred())
newClientCacheDir := workDir + "/newclient"
err = os.MkdirAll(newClientCacheDir, 0755)
Expect(err).ToNot(HaveOccurred())
// Create VM on previous release using a specific API.
// NOTE: we are testing with yaml here and explicilty _NOT_ generating
// this vm using the latest api code. We want to guarrantee there are no
// surprises when it comes to backwards compatiblity with previous
// virt apis. As we progress our api from v1alpha3 -> v1 there
// needs to be a VM created for every api. This is how we will ensure
// our api remains upgradable and supportable from previous release.
generatePreviousVersionVmYamls(previousImageRegistry, previousImageTag)
for _, vmYaml := range vmYamls {
By(fmt.Sprintf("Creating VM with %s api", vmYaml.vmName))
// NOTE: using kubectl to post yaml directly
_, _, err = tests.RunCommand(k8sClient, "create", "-f", vmYaml.yamlFile, "--cache-dir", oldClientCacheDir)
Expect(err).ToNot(HaveOccurred())
// Use Current virtctl to start VM
// NOTE: we are using virtctl explicitly here because we want to start the VM
// using the subresource endpoint in the same way virtctl performs this.
By("Starting VM with virtctl")
startCommand := tests.NewRepeatableVirtctlCommand("start", "--namespace", tests.NamespaceTestDefault, vmYaml.vmName)
Expect(startCommand()).To(Succeed())
By(fmt.Sprintf("Waiting for VM with %s api to become ready", vmYaml.apiVersion))
Eventually(func() bool {
virtualMachine, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmYaml.vmName, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
if virtualMachine.Status.Ready {
return true
}
return false
}, 180*time.Second, 1*time.Second).Should(BeTrue())
}
// Update KubeVirt from the previous release to the testing target release.
By("Updating KubeVirtObject With Current Tag")
patchKvVersionAndRegistry(kv.Name, curVersion, curRegistry)
By("Wait for Updating Condition")
waitForUpdateCondition(kv)
By("Waiting for KV to stabilize")
waitForKv(kv)
By("Verifying infrastructure Is Updated")
allPodsAreReady(kv)
// Verify console connectivity to VMI still works and stop VM
for _, vmYaml := range vmYamls {
By(fmt.Sprintf("Ensuring vm %s is ready and latest API annotation is set", vmYaml.apiVersion))
Eventually(func() bool {
// We are using our internal client here on purpose to ensure we can interact
// with previously created objects that may have been created using a different
// api version from the latest one our client uses.
virtualMachine, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmYaml.vmName, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
if !virtualMachine.Status.Ready {
return false
}
if !controller.ObservedLatestApiVersionAnnotation(virtualMachine) {
return false
}
return true
}, 180*time.Second, 1*time.Second).Should(BeTrue())
By(fmt.Sprintf("Connecting to %s's console", vmYaml.vmName))
// This is in an eventually loop because it's possible for the
// subresource endpoint routing to fail temporarily right after a deployment
// completes while we wait for the kubernetes apiserver to detect our
// subresource api server is online and ready to serve requests.
Eventually(func() error {
vmi, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmYaml.vmName, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
expecter, err := tests.LoggedInCirrosExpecter(vmi)
if err != nil {
return err
}
expecter.Close()
return nil
}, 60*time.Second, 1*time.Second).Should(BeNil())
By("Stopping VM with virtctl")
stopFn := tests.NewRepeatableVirtctlCommand("stop", "--namespace", tests.NamespaceTestDefault, vmYaml.vmName)
Eventually(func() error {
return stopFn()
}, 30*time.Second, 1*time.Second).Should(BeNil())
By("Waiting for VMI to stop")
Eventually(func() bool {
_, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmYaml.vmName, &metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
return true
} else if err != nil {
Expect(err).ToNot(HaveOccurred())
}
return false
// #3610 - this timeout needs to be reduced back to 60 seconds.
// there's an issue occuring after update where sometimes virt-launcher
// can't dial the event notify socket. This impacts the timing for when
// the vmi is shutdown. Once that is resolved, reduce the timeout
}, 160*time.Second, 1*time.Second).Should(BeTrue())
By(fmt.Sprintf("Deleting VM with %s api", vmYaml.apiVersion))
_, _, err = tests.RunCommand(k8sClient, "delete", "-f", vmYaml.yamlFile, "--cache-dir", newClientCacheDir)
Expect(err).ToNot(HaveOccurred())
By("Waiting for VM to be removed")
Eventually(func() bool {
_, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmYaml.vmName, &metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
return true
}
return false
}, 90*time.Second, 1*time.Second).Should(BeTrue())
}
By("Deleting KubeVirt object")
deleteAllKvAndWait(false)
})
})
Describe("[rfe_id:2291][crit:high][vendor:[email protected]][level:component]infrastructure management", func() {
It("[test_id:3146]should be able to delete and re-create kubevirt install", func() {
allPodsAreReady(originalKv)
sanityCheckDeploymentsExist()
By("Deleting KubeVirt object")
deleteAllKvAndWait(false)
// this is just verifying some common known components do in fact get deleted.
By("Sanity Checking Deployments infrastructure is deleted")
sanityCheckDeploymentsDeleted()
By("ensuring that namespaces can be successfully created and deleted")
_, err := virtClient.CoreV1().Namespaces().Create(&k8sv1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: tests.NamespaceTestOperator}})
if err != nil && !errors.IsAlreadyExists(err) {
Expect(err).ToNot(HaveOccurred())
}
err = virtClient.CoreV1().Namespaces().Delete(tests.NamespaceTestOperator, &metav1.DeleteOptions{})
Expect(err).ToNot(HaveOccurred())
Eventually(func() bool {
_, err := virtClient.CoreV1().Namespaces().Get(tests.NamespaceTestOperator, metav1.GetOptions{})
return errors.IsNotFound(err)
}, 60*time.Second, 1*time.Second).Should(BeTrue())
By("Creating KubeVirt Object")
createKv(copyOriginalKv())
By("Creating KubeVirt Object Created and Ready Condition")
waitForKv(originalKv)
By("Verifying infrastructure is Ready")
allPodsAreReady(originalKv)
// We're just verifying that a few common components that
// should always exist get re-deployed.
sanityCheckDeploymentsExist()
})
Describe("[rfe_id:3578][crit:high][vendor:[email protected]][level:component] deleting with BlockUninstallIfWorkloadsExist", func() {
It("[test_id:3683]should be blocked if a workload exists", func() {
allPodsAreReady(originalKv)
sanityCheckDeploymentsExist()
By("setting the right uninstall strategy")
kv, err := virtClient.KubeVirt(originalKv.Namespace).Get(originalKv.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
kv.Spec.UninstallStrategy = v1.KubeVirtUninstallStrategyBlockUninstallIfWorkloadsExist
_, err = virtClient.KubeVirt(kv.Namespace).Update(kv)
Expect(err).ToNot(HaveOccurred())
By("creating a simple VMI")
_, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskCirros)))
Expect(err).ToNot(HaveOccurred())
By("Deleting KubeVirt object")
err = virtClient.KubeVirt(kv.Namespace).Delete(kv.Name, &metav1.DeleteOptions{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("there are still Virtual Machine Instances present"))
})
})
It("[test_id:3148]should be able to create kubevirt install with custom image tag", func() {
if flags.KubeVirtVersionTagAlt == "" {
Skip("Skip operator custom image tag test because alt tag is not present")
}
allPodsAreReady(originalKv)
sanityCheckDeploymentsExist()
By("Deleting KubeVirt object")
deleteAllKvAndWait(false)
// this is just verifying some common known components do in fact get deleted.
By("Sanity Checking Deployments infrastructure is deleted")
sanityCheckDeploymentsDeleted()
By("Creating KubeVirt Object")
kv := copyOriginalKv()
kv.Name = "kubevirt-alt-install"
kv.Spec = v1.KubeVirtSpec{
ImageTag: flags.KubeVirtVersionTagAlt,
ImageRegistry: flags.KubeVirtRepoPrefix,
}
createKv(kv)
By("Creating KubeVirt Object Created and Ready Condition")
waitForKv(kv)
By("Verifying infrastructure is Ready")
allPodsAreReady(kv)
// We're just verifying that a few common components that
// should always exist get re-deployed.
sanityCheckDeploymentsExist()
By("Deleting KubeVirt object")
deleteAllKvAndWait(false)
})
// this test ensures that we can deal with image prefixes in case they are not used for tests already
It("[test_id:3149]should be able to create kubevirt install with image prefix", func() {
if flags.ImagePrefixAlt == "" {
Skip("Skip operator imagePrefix test because imagePrefixAlt is not present")
}
kv := copyOriginalKv()
allPodsAreReady(originalKv)
sanityCheckDeploymentsExist()
_, _, _, oldPrefix, _ := parseOperatorImage()
By("Update Operator using imagePrefixAlt")
patchOperator(&flags.ImagePrefixAlt, nil)
// should result in kubevirt cr entering updating state
By("Wait for Updating Condition")
waitForUpdateCondition(kv)
By("Waiting for KV to stabilize")
waitForKv(kv)
By("Verifying infrastructure Is Updated")
allPodsAreReady(kv)