-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
utils.go
5003 lines (4289 loc) · 157 KB
/
utils.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
import (
"bytes"
"context"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"encoding/xml"
goerrors "errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
expect "github.com/google/goexpect"
. "github.com/onsi/ginkgo"
"github.com/onsi/ginkgo/config"
. "github.com/onsi/gomega"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
autoscalingv1 "k8s.io/api/autoscaling/v1"
k8sv1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
storagev1 "k8s.io/api/storage/v1"
extclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport/spdy"
netutils "k8s.io/utils/net"
"kubevirt.io/kubevirt/tests/framework/cleanup"
"kubevirt.io/kubevirt/pkg/certificates/triple/cert"
"kubevirt.io/kubevirt/pkg/virt-operator/resource/generate/components"
"kubevirt.io/kubevirt/pkg/certificates/bootstrap"
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/util/cluster"
"kubevirt.io/kubevirt/pkg/util/net/ip"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-controller/services"
launcherApi "kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
"kubevirt.io/kubevirt/pkg/virt-operator/util"
"kubevirt.io/kubevirt/pkg/virtctl"
vmsgen "kubevirt.io/kubevirt/tools/vms-generator/utils"
"kubevirt.io/kubevirt/tests/console"
cd "kubevirt.io/kubevirt/tests/containerdisk"
"kubevirt.io/kubevirt/tests/flags"
"kubevirt.io/kubevirt/tests/libnet"
"kubevirt.io/kubevirt/tests/libvmi"
"github.com/Masterminds/semver"
"github.com/google/go-github/v32/github"
)
var Config *KubeVirtTestsConfiguration
var KubeVirtDefaultConfig v1.KubeVirtConfiguration
var CDIInsecureRegistryConfig *k8sv1.ConfigMap
type EventType string
const TempDirPrefix = "kubevirt-test"
const (
defaultEventuallyTimeout = 5 * time.Second
defaultEventuallyPollingInterval = 1 * time.Second
)
const (
AlpineHttpUrl = iota
DummyFileHttpUrl
CirrosHttpUrl
VirtWhatCpuidHelperHttpUrl
)
const (
NormalEvent EventType = "Normal"
WarningEvent EventType = "Warning"
)
const defaultTestGracePeriod int64 = 0
const (
SubresourceServiceAccountName = "kubevirt-subresource-test-sa"
AdminServiceAccountName = "kubevirt-admin-test-sa"
EditServiceAccountName = "kubevirt-edit-test-sa"
ViewServiceAccountName = "kubevirt-view-test-sa"
)
const SubresourceTestLabel = "subresource-access-test-pod"
const insecureRegistryConfigName = "cdi-insecure-registries"
// tests.NamespaceTestDefault is the default namespace, to test non-infrastructure related KubeVirt objects.
var NamespaceTestDefault = "kubevirt-test-default"
// NamespaceTestAlternative is used to test controller-namespace independency.
var NamespaceTestAlternative = "kubevirt-test-alternative"
// NamespaceTestOperator is used to test if namespaces can still be deleted when kubevirt is uninstalled
var NamespaceTestOperator = "kubevirt-test-operator"
const (
ISCSITargetName = "test-isci-target"
)
var testNamespaces = []string{NamespaceTestDefault, NamespaceTestAlternative, NamespaceTestOperator}
var schedulableNode = ""
type startType string
const (
invalidWatch startType = "invalidWatch"
// Watch since the moment a long poll connection is established
watchSinceNow startType = "watchSinceNow"
// Watch since the resourceVersion of the passed in runtime object
watchSinceObjectUpdate startType = "watchSinceObjectUpdate"
// Watch since the resourceVersion of the watched object
watchSinceWatchedObjectUpdate startType = "watchSinceWatchedObjectUpdate"
// Watch since the resourceVersion passed in to the builder
watchSinceResourceVersion startType = "watchSinceResourceVersion"
)
const (
osAlpineHostPath = "alpine-host-path"
OSWindows = "windows"
OSRhel = "rhel"
CustomHostPath = "custom-host-path"
HostPathBase = "/tmp/hostImages"
)
var (
HostPathAlpine string
HostPathCustom string
HostPathFedora string
)
const (
DiskAlpineHostPath = "disk-alpine-host-path"
DiskWindows = "disk-windows"
DiskRhel = "disk-rhel"
DiskCustomHostPath = "disk-custom-host-path"
)
const (
defaultDiskSize = "1Gi"
)
const VMIResource = "virtualmachineinstances"
const (
SecretLabel = "kubevirt.io/secret"
)
const (
// BlockDiskForTest contains name of the block PV and PVC
BlockDiskForTest = "block-disk-for-tests"
)
const (
tmpPath = "/var/provision/kubevirt.io/tests"
)
const (
capNetAdmin k8sv1.Capability = "NET_ADMIN"
capNetRaw k8sv1.Capability = "NET_RAW"
capSysNice k8sv1.Capability = "SYS_NICE"
)
const MigrationWaitTime = 240
type ProcessFunc func(event *k8sv1.Event) (done bool)
type ObjectEventWatcher struct {
object runtime.Object
timeout *time.Duration
resourceVersion string
startType startType
warningPolicy WarningsPolicy
dontFailOnMissingEvent bool
}
type WarningsPolicy struct {
FailOnWarnings bool
WarningsIgnoreList []string
}
func (wp *WarningsPolicy) shouldIgnoreWarning(event *k8sv1.Event) bool {
if event.Type == string(WarningEvent) {
for _, message := range wp.WarningsIgnoreList {
if message == event.Message {
return true
}
}
}
return false
}
func NewObjectEventWatcher(object runtime.Object) *ObjectEventWatcher {
return &ObjectEventWatcher{object: object, startType: invalidWatch}
}
func (w *ObjectEventWatcher) Timeout(duration time.Duration) *ObjectEventWatcher {
w.timeout = &duration
return w
}
func (w *ObjectEventWatcher) SetWarningsPolicy(wp WarningsPolicy) *ObjectEventWatcher {
w.warningPolicy = wp
return w
}
/*
SinceNow sets a watch starting point for events, from the moment on the connection to the apiserver
was established.
*/
func (w *ObjectEventWatcher) SinceNow() *ObjectEventWatcher {
w.startType = watchSinceNow
return w
}
/*
SinceWatchedObjectResourceVersion takes the resource version of the runtime object which is watched,
and takes it as the starting point for all events to watch for.
*/
func (w *ObjectEventWatcher) SinceWatchedObjectResourceVersion() *ObjectEventWatcher {
w.startType = watchSinceWatchedObjectUpdate
return w
}
/*
SinceObjectResourceVersion takes the resource version of the passed in runtime object and takes it
as the starting point for all events to watch for.
*/
func (w *ObjectEventWatcher) SinceObjectResourceVersion(object runtime.Object) *ObjectEventWatcher {
var err error
w.startType = watchSinceObjectUpdate
w.resourceVersion, err = meta.NewAccessor().ResourceVersion(object)
Expect(err).ToNot(HaveOccurred())
return w
}
/*
SinceResourceVersion sets the passed in resourceVersion as the starting point for all events to watch for.
*/
func (w *ObjectEventWatcher) SinceResourceVersion(rv string) *ObjectEventWatcher {
w.resourceVersion = rv
w.startType = watchSinceResourceVersion
return w
}
func (w *ObjectEventWatcher) Watch(ctx context.Context, processFunc ProcessFunc, watchedDescription string) {
Expect(w.startType).ToNot(Equal(invalidWatch))
resourceVersion := ""
switch w.startType {
case watchSinceNow:
resourceVersion = ""
case watchSinceObjectUpdate, watchSinceResourceVersion:
resourceVersion = w.resourceVersion
case watchSinceWatchedObjectUpdate:
var err error
resourceVersion, err = meta.NewAccessor().ResourceVersion(w.object)
Expect(err).ToNot(HaveOccurred())
}
cli, err := kubecli.GetKubevirtClient()
if err != nil {
panic(err)
}
f := processFunc
if w.warningPolicy.FailOnWarnings {
f = func(event *k8sv1.Event) bool {
msg := fmt.Sprintf("Event(%#v): type: '%v' reason: '%v' %v", event.InvolvedObject, event.Type, event.Reason, event.Message)
if w.warningPolicy.shouldIgnoreWarning(event) == false {
ExpectWithOffset(1, event.Type).NotTo(Equal(string(WarningEvent)), "Unexpected Warning event received: %s,%s: %s", event.InvolvedObject.Name, event.InvolvedObject.UID, event.Message)
}
log.Log.ObjectRef(&event.InvolvedObject).Info(msg)
return processFunc(event)
}
} else {
f = func(event *k8sv1.Event) bool {
if event.Type == string(WarningEvent) {
log.Log.ObjectRef(&event.InvolvedObject).Reason(fmt.Errorf("Warning event received")).Error(event.Message)
} else {
log.Log.ObjectRef(&event.InvolvedObject).Infof(event.Message)
}
return processFunc(event)
}
}
var selector []string
objectMeta := w.object.(metav1.ObjectMetaAccessor)
name := objectMeta.GetObjectMeta().GetName()
namespace := objectMeta.GetObjectMeta().GetNamespace()
uid := objectMeta.GetObjectMeta().GetUID()
selector = append(selector, fmt.Sprintf("involvedObject.name=%v", name))
if namespace != "" {
selector = append(selector, fmt.Sprintf("involvedObject.namespace=%v", namespace))
}
if uid != "" {
selector = append(selector, fmt.Sprintf("involvedObject.uid=%v", uid))
}
eventWatcher, err := cli.CoreV1().Events(k8sv1.NamespaceAll).
Watch(context.Background(), metav1.ListOptions{
FieldSelector: fields.ParseSelectorOrDie(strings.Join(selector, ",")).String(),
ResourceVersion: resourceVersion,
})
if err != nil {
panic(err)
}
defer eventWatcher.Stop()
done := make(chan struct{})
go func() {
defer GinkgoRecover()
for watchEvent := range eventWatcher.ResultChan() {
if watchEvent.Type != watch.Error {
event := watchEvent.Object.(*k8sv1.Event)
if f(event) {
close(done)
break
}
} else {
Fail(fmt.Sprintf("unexpected error event: %v", apierrors.FromObject(watchEvent.Object)))
}
}
}()
if w.timeout != nil {
select {
case <-done:
case <-ctx.Done():
case <-time.After(*w.timeout):
if !w.dontFailOnMissingEvent {
Fail(fmt.Sprintf("Waited for %v seconds on the event stream to match a specific event: %s", w.timeout.Seconds(), watchedDescription), 1)
}
}
} else {
select {
case <-ctx.Done():
case <-done:
}
}
}
func (w *ObjectEventWatcher) WaitFor(ctx context.Context, eventType EventType, reason interface{}) (e *k8sv1.Event) {
w.Watch(ctx, func(event *k8sv1.Event) bool {
if event.Type == string(eventType) && event.Reason == reflect.ValueOf(reason).String() {
e = event
return true
}
return false
}, fmt.Sprintf("event type %s, reason = %s", string(eventType), reflect.ValueOf(reason).String()))
return
}
func (w *ObjectEventWatcher) WaitNotFor(ctx context.Context, eventType EventType, reason interface{}) (e *k8sv1.Event) {
w.dontFailOnMissingEvent = true
w.Watch(ctx, func(event *k8sv1.Event) bool {
if event.Type == string(eventType) && event.Reason == reflect.ValueOf(reason).String() {
e = event
Fail(fmt.Sprintf("Did not expect %s with reason %s", string(eventType), reflect.ValueOf(reason).String()), 1)
return true
}
return false
}, fmt.Sprintf("not happen event type %s, reason = %s", string(eventType), reflect.ValueOf(reason).String()))
return
}
// Do scale and returns error, replicas-before.
func DoScaleDeployment(namespace string, name string, desired int32) (error, int32) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
deployment, err := virtCli.AppsV1().Deployments(namespace).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
return err, -1
}
scale := &autoscalingv1.Scale{Spec: autoscalingv1.ScaleSpec{Replicas: desired}, ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}}
_, err = virtCli.AppsV1().Deployments(namespace).UpdateScale(context.Background(), name, scale, metav1.UpdateOptions{})
if err != nil {
return err, -1
}
return nil, *deployment.Spec.Replicas
}
func DoScaleVirtHandler(namespace string, name string, selector map[string]string) (int32, map[string]string, int64, error) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
d, err := virtCli.AppsV1().DaemonSets(namespace).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
return 0, nil, 0, err
}
sel := d.Spec.Template.Spec.NodeSelector
ready := d.Status.DesiredNumberScheduled
d.Spec.Template.Spec.NodeSelector = selector
d, err = virtCli.AppsV1().DaemonSets(namespace).Update(context.Background(), d, metav1.UpdateOptions{})
if err != nil {
return 0, nil, 0, err
}
return ready, sel, d.ObjectMeta.Generation, nil
}
func WaitForAllPodsReady(timeout time.Duration, listOptions metav1.ListOptions) {
checkForPodsToBeReady := func() []string {
podsNotReady := make([]string, 0)
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
podsList, err := virtClient.CoreV1().Pods(k8sv1.NamespaceAll).List(context.Background(), listOptions)
PanicOnError(err)
for _, pod := range podsList.Items {
for _, status := range pod.Status.ContainerStatuses {
if status.State.Terminated != nil {
break // We don't care about terminated pods
} else if status.State.Running != nil {
if !status.Ready { // We need to wait for this one
podsNotReady = append(podsNotReady, pod.Name)
break
}
} else {
// It is in Waiting state, We need to wait for this one
podsNotReady = append(podsNotReady, pod.Name)
break
}
}
}
return podsNotReady
}
Eventually(checkForPodsToBeReady, timeout, 2*time.Second).Should(BeEmpty(), "There are pods in system which are not ready.")
}
func SynchronizedAfterTestSuiteCleanup() {
RestoreKubeVirtResource()
if Config.ManageStorageClasses {
deleteStorageClass(Config.StorageClassHostPath)
deleteStorageClass(Config.StorageClassBlockVolume)
}
CleanNodes()
}
func AfterTestSuitCleanup() {
cleanupServiceAccounts()
cleanNamespaces()
if flags.DeployTestingInfrastructureFlag {
WipeTestingInfrastructure()
}
removeNamespaces()
}
func BeforeTestCleanup() {
deleteBlockPVAndPVC()
cleanNamespaces()
CleanNodes()
resetToDefaultConfig()
CreateHostPathPv(osAlpineHostPath, HostPathAlpine)
CreateHostPathPVC(osAlpineHostPath, defaultDiskSize)
}
func CleanNodes() {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
nodes := GetAllSchedulableNodes(virtCli).Items
clusterDrainKey := GetNodeDrainKey()
for _, node := range nodes {
old, err := json.Marshal(node)
Expect(err).ToNot(HaveOccurred())
new := node.DeepCopy()
k8sClient := GetK8sCmdClient()
if k8sClient == "oc" {
RunCommandWithNS("", k8sClient, "adm", "uncordon", node.Name)
} else {
RunCommandWithNS("", k8sClient, "uncordon", node.Name)
}
found := false
taints := []k8sv1.Taint{}
for _, taint := range node.Spec.Taints {
if taint.Key == clusterDrainKey && taint.Effect == k8sv1.TaintEffectNoSchedule {
found = true
} else if taint.Key == "kubevirt.io/drain" && taint.Effect == k8sv1.TaintEffectNoSchedule {
// this key is used as a fallback if the original drain key is built-in
found = true
} else if taint.Key == "kubevirt.io/alt-drain" && taint.Effect == k8sv1.TaintEffectNoSchedule {
// this key is used in testing as a custom alternate drain key
found = true
} else {
taints = append(taints, taint)
}
}
new.Spec.Taints = taints
for k := range node.Labels {
if strings.HasPrefix(k, "tests.kubevirt.io") {
found = true
delete(new.Labels, k)
}
}
if node.Spec.Unschedulable {
new.Spec.Unschedulable = false
}
if !found {
continue
}
newJson, err := json.Marshal(new)
Expect(err).ToNot(HaveOccurred())
patch, err := strategicpatch.CreateTwoWayMergePatch(old, newJson, node)
Expect(err).ToNot(HaveOccurred())
_, err = virtCli.CoreV1().Nodes().Patch(context.Background(), node.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred())
}
}
func AddLabelToNode(nodeName string, key string, value string) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
node, err := virtCli.CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
old, err := json.Marshal(node)
Expect(err).ToNot(HaveOccurred())
new := node.DeepCopy()
new.Labels[key] = value
newJson, err := json.Marshal(new)
Expect(err).ToNot(HaveOccurred())
patch, err := strategicpatch.CreateTwoWayMergePatch(old, newJson, node)
Expect(err).ToNot(HaveOccurred())
_, err = virtCli.CoreV1().Nodes().Patch(context.Background(), node.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred())
}
func RemoveLabelFromNode(nodeName string, key string) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
node, err := virtCli.CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
if _, exists := node.Labels[key]; !exists {
return
}
old, err := json.Marshal(node)
Expect(err).ToNot(HaveOccurred())
new := node.DeepCopy()
delete(new.Labels, key)
newJson, err := json.Marshal(new)
Expect(err).ToNot(HaveOccurred())
patch, err := strategicpatch.CreateTwoWayMergePatch(old, newJson, node)
Expect(err).ToNot(HaveOccurred())
_, err = virtCli.CoreV1().Nodes().Patch(context.Background(), node.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred())
}
func Taint(nodeName string, key string, effect k8sv1.TaintEffect) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
node, err := virtCli.CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
old, err := json.Marshal(node)
Expect(err).ToNot(HaveOccurred())
new := node.DeepCopy()
new.Spec.Taints = append(new.Spec.Taints, k8sv1.Taint{
Key: key,
Effect: effect,
})
newJson, err := json.Marshal(new)
Expect(err).ToNot(HaveOccurred())
patch, err := strategicpatch.CreateTwoWayMergePatch(old, newJson, node)
Expect(err).ToNot(HaveOccurred())
_, err = virtCli.CoreV1().Nodes().Patch(context.Background(), node.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
Expect(err).ToNot(HaveOccurred())
}
// CalculateNamespaces checks on which ginkgo gest node the tests are run and sets the namespaces accordingly
func CalculateNamespaces() {
worker := config.GinkgoConfig.ParallelNode
NamespaceTestDefault = fmt.Sprintf("%s%d", NamespaceTestDefault, worker)
NamespaceTestAlternative = fmt.Sprintf("%s%d", NamespaceTestAlternative, worker)
// TODO, that is not needed, just a shortcut to not have to treat this namespace
// differently when running in parallel
NamespaceTestOperator = fmt.Sprintf("%s%d", NamespaceTestOperator, worker)
testNamespaces = []string{NamespaceTestDefault, NamespaceTestAlternative, NamespaceTestOperator}
}
func SynchronizedBeforeTestSetup() []byte {
var err error
Config, err = loadConfig()
Expect(err).ToNot(HaveOccurred())
if flags.KubeVirtInstallNamespace == "" {
detectInstallNamespace()
}
if flags.DeployTestingInfrastructureFlag {
WipeTestingInfrastructure()
DeployTestingInfrastructure()
}
if Config.ManageStorageClasses {
createStorageClass(Config.StorageClassHostPath)
createStorageClass(Config.StorageClassBlockVolume)
}
EnsureKVMPresent()
AdjustKubeVirtResource()
return nil
}
func BeforeTestSuitSetup(_ []byte) {
rand.Seed(int64(config.GinkgoConfig.ParallelNode))
log.InitializeLogging("tests")
log.Log.SetIOWriter(GinkgoWriter)
var err error
Config, err = loadConfig()
Expect(err).ToNot(HaveOccurred())
// Customize host disk paths
// Right now we support three nodes. More image copying needs to happen
// TODO link this somehow with the image provider which we run upfront
worker := config.GinkgoConfig.ParallelNode
HostPathAlpine = filepath.Join(HostPathBase, fmt.Sprintf("%s%v", "alpine", worker))
HostPathCustom = filepath.Join(HostPathBase, fmt.Sprintf("%s%v", "custom", worker))
HostPathFedora = filepath.Join(HostPathBase, "fedora-cloud")
// Wait for schedulable nodes
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
Eventually(func() int {
nodes := GetAllSchedulableNodes(virtClient)
if len(nodes.Items) > 0 {
idx := rand.Intn(len(nodes.Items))
schedulableNode = nodes.Items[idx].Name
}
return len(nodes.Items)
}, 5*time.Minute, 10*time.Second).ShouldNot(BeZero(), "no schedulable nodes found")
createNamespaces()
createServiceAccounts()
SetDefaultEventuallyTimeout(defaultEventuallyTimeout)
SetDefaultEventuallyPollingInterval(defaultEventuallyPollingInterval)
}
var originalKV *v1.KubeVirt
func AdjustKubeVirtResource() {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
kv := GetCurrentKv(virtClient)
originalKV = kv.DeepCopy()
KubeVirtDefaultConfig = originalKV.Spec.Configuration
if !flags.ApplyDefaulte2eConfiguration {
return
}
// Rotate very often during the tests to ensure that things are working
kv.Spec.CertificateRotationStrategy = v1.KubeVirtCertificateRotateStrategy{SelfSigned: &v1.KubeVirtSelfSignConfiguration{
CARotateInterval: &metav1.Duration{Duration: 20 * time.Minute},
CertRotateInterval: &metav1.Duration{Duration: 14 * time.Minute},
CAOverlapInterval: &metav1.Duration{Duration: 8 * time.Minute},
}}
// match default kubevirt-config testing resource
if kv.Spec.Configuration.DeveloperConfiguration == nil {
kv.Spec.Configuration.DeveloperConfiguration = &v1.DeveloperConfiguration{}
}
kv.Spec.Configuration.DeveloperConfiguration.FeatureGates = []string{
virtconfig.CPUManager,
virtconfig.LiveMigrationGate,
virtconfig.IgnitionGate,
virtconfig.SidecarGate,
virtconfig.SnapshotGate,
virtconfig.HostDiskGate,
virtconfig.VirtIOFSGate,
virtconfig.HotplugVolumesGate,
}
kv.Spec.Configuration.SELinuxLauncherType = "virt_launcher.process"
data, err := json.Marshal(kv.Spec)
Expect(err).ToNot(HaveOccurred())
patchData := fmt.Sprintf(`[{ "op": "replace", "path": "/spec", "value": %s }]`, string(data))
adjustedKV, err := virtClient.KubeVirt(kv.Namespace).Patch(kv.Name, types.JSONPatchType, []byte(patchData))
PanicOnError(err)
KubeVirtDefaultConfig = adjustedKV.Spec.Configuration
CDIInsecureRegistryConfig, err = virtClient.CoreV1().ConfigMaps(flags.ContainerizedDataImporterNamespace).Get(context.Background(), insecureRegistryConfigName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
// force it to nil, independent of what the client returned
CDIInsecureRegistryConfig = nil
} else {
PanicOnError(err)
}
}
}
func RestoreKubeVirtResource() {
if originalKV != nil {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
data, err := json.Marshal(originalKV.Spec)
Expect(err).ToNot(HaveOccurred())
patchData := fmt.Sprintf(`[{ "op": "replace", "path": "/spec", "value": %s }]`, string(data))
_, err = virtClient.KubeVirt(originalKV.Namespace).Patch(originalKV.Name, types.JSONPatchType, []byte(patchData))
PanicOnError(err)
}
}
func createStorageClass(name string) {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
sc := &storagev1.StorageClass{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"kubevirt.io/test": name,
},
},
Provisioner: name,
}
_, err = virtClient.StorageV1().StorageClasses().Create(context.Background(), sc, metav1.CreateOptions{})
if !errors.IsAlreadyExists(err) {
PanicOnError(err)
}
}
func deleteStorageClass(name string) {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
_, err = virtClient.StorageV1().StorageClasses().Get(context.Background(), name, metav1.GetOptions{})
if errors.IsNotFound(err) {
return
}
PanicOnError(err)
err = virtClient.StorageV1().StorageClasses().Delete(context.Background(), name, metav1.DeleteOptions{})
PanicOnError(err)
}
func ShouldUseEmulation(virtClient kubecli.KubevirtClient) bool {
useEmulation := false
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
kv := GetCurrentKv(virtClient)
if kv.Spec.Configuration.DeveloperConfiguration != nil {
useEmulation = kv.Spec.Configuration.DeveloperConfiguration.UseEmulation
}
return useEmulation
}
func EnsureKVMPresent() {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
if !ShouldUseEmulation(virtClient) {
listOptions := metav1.ListOptions{LabelSelector: v1.AppLabel + "=virt-handler"}
virtHandlerPods, err := virtClient.CoreV1().Pods(flags.KubeVirtInstallNamespace).List(context.Background(), listOptions)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
EventuallyWithOffset(1, func() bool {
ready := true
// cluster is not ready until all nodes are ready.
for _, pod := range virtHandlerPods.Items {
virtHandlerNode, err := virtClient.CoreV1().Nodes().Get(context.Background(), pod.Spec.NodeName, metav1.GetOptions{})
ExpectWithOffset(1, err).ToNot(HaveOccurred())
kvmAllocatable, ok1 := virtHandlerNode.Status.Allocatable[services.KvmDevice]
vhostNetAllocatable, ok2 := virtHandlerNode.Status.Allocatable[services.VhostNetDevice]
ready = ready && ok1 && ok2
ready = ready && (kvmAllocatable.Value() > 0) && (vhostNetAllocatable.Value() > 0)
}
return ready
}, 120*time.Second, 1*time.Second).Should(BeTrue(),
"Both KVM devices and vhost-net devices are required for testing, but are not present on cluster nodes")
}
}
func GetNodesWithKVM() []*k8sv1.Node {
virtClient, err := kubecli.GetKubevirtClient()
PanicOnError(err)
listOptions := metav1.ListOptions{LabelSelector: v1.AppLabel + "=virt-handler"}
virtHandlerPods, err := virtClient.CoreV1().Pods(flags.KubeVirtInstallNamespace).List(context.Background(), listOptions)
Expect(err).ToNot(HaveOccurred())
nodes := make([]*k8sv1.Node, 0)
// cluster is not ready until all nodes are ready.
for _, pod := range virtHandlerPods.Items {
virtHandlerNode, err := virtClient.CoreV1().Nodes().Get(context.Background(), pod.Spec.NodeName, metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
_, ok := virtHandlerNode.Status.Allocatable[services.KvmDevice]
if ok {
nodes = append(nodes, virtHandlerNode)
}
}
return nodes
}
func GetSupportedCPUFeatures(nodes k8sv1.NodeList) []string {
var featureDenyList = map[string]bool{
"svm": true,
}
featuresMap := make(map[string]bool)
for _, node := range nodes.Items {
for key := range node.Labels {
if strings.Contains(key, services.NFD_CPU_FEATURE_PREFIX) {
feature := strings.TrimPrefix(key, services.NFD_CPU_FEATURE_PREFIX)
if _, ok := featureDenyList[feature]; !ok {
featuresMap[feature] = true
}
}
}
}
features := make([]string, 0)
for feature := range featuresMap {
features = append(features, feature)
}
return features
}
func GetSupportedCPUModels(nodes k8sv1.NodeList) []string {
var cpuDenyList = map[string]bool{
"qemu64": true,
"Opteron_G2": true,
}
cpuMap := make(map[string]bool)
for _, node := range nodes.Items {
for key := range node.Labels {
if strings.Contains(key, services.NFD_CPU_MODEL_PREFIX) {
cpu := strings.TrimPrefix(key, services.NFD_CPU_MODEL_PREFIX)
if _, ok := cpuDenyList[cpu]; !ok {
cpuMap[cpu] = true
}
}
}
}
cpus := make([]string, 0)
for model := range cpuMap {
cpus = append(cpus, model)
}
return cpus
}
func CreateConfigMap(name string, data map[string]string) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
_, err = virtCli.CoreV1().ConfigMaps(NamespaceTestDefault).Create(context.Background(), &k8sv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Name: name},
Data: data,
}, metav1.CreateOptions{})
if !errors.IsAlreadyExists(err) {
PanicOnError(err)
}
}
func CreateSecret(name string, data map[string]string) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
_, err = virtCli.CoreV1().Secrets(NamespaceTestDefault).Create(context.Background(), &k8sv1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: name},
StringData: data,
}, metav1.CreateOptions{})
if !errors.IsAlreadyExists(err) {
PanicOnError(err)
}
}
func CreateHostPathPVC(os, size string) {
CreatePVC(os, size, Config.StorageClassHostPath, false)
}
func CreatePVC(os, size, storageClass string, recycledPV bool) {
virtCli, err := kubecli.GetKubevirtClient()
PanicOnError(err)
_, err = virtCli.CoreV1().PersistentVolumeClaims((NamespaceTestDefault)).Create(context.Background(), newPVC(os, size, storageClass, recycledPV), metav1.CreateOptions{})
if !errors.IsAlreadyExists(err) {
PanicOnError(err)
}
}
func newPVC(os, size, storageClass string, recycledPV bool) *k8sv1.PersistentVolumeClaim {
quantity, err := resource.ParseQuantity(size)
PanicOnError(err)
name := fmt.Sprintf("disk-%s", os)
selector := map[string]string{
"kubevirt.io/test": os,
}
// If the PV is not recycled, it will have a namespace related test label which we should match
if !recycledPV {
selector[cleanup.TestLabelForNamespace(NamespaceTestDefault)] = ""
}
return &k8sv1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{Name: name},
Spec: k8sv1.PersistentVolumeClaimSpec{
AccessModes: []k8sv1.PersistentVolumeAccessMode{k8sv1.ReadWriteOnce},
Resources: k8sv1.ResourceRequirements{