-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
vm.go
3626 lines (3106 loc) · 122 KB
/
vm.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 virthandler
import (
"context"
"encoding/json"
goerror "errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
cmdv1 "kubevirt.io/kubevirt/pkg/handler-launcher-com/cmd/v1"
"golang.org/x/sys/unix"
"k8s.io/apimachinery/pkg/util/errors"
"kubevirt.io/kubevirt/pkg/network/domainspec"
"kubevirt.io/kubevirt/pkg/pointer"
"kubevirt.io/kubevirt/pkg/virt-controller/services"
"kubevirt.io/kubevirt/pkg/virt-controller/watch/topology"
"kubevirt.io/kubevirt/pkg/virt-handler/selinux"
"kubevirt.io/kubevirt/pkg/virtiofs"
"kubevirt.io/kubevirt/pkg/config"
hotplugdisk "kubevirt.io/kubevirt/pkg/hotplug-disk"
"kubevirt.io/kubevirt/pkg/safepath"
"kubevirt.io/kubevirt/pkg/virt-handler/cgroup"
"github.com/opencontainers/runc/libcontainer/cgroups"
nodelabellerapi "kubevirt.io/kubevirt/pkg/virt-handler/node-labeller/api"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
netcache "kubevirt.io/kubevirt/pkg/network/cache"
netsetup "kubevirt.io/kubevirt/pkg/network/setup"
netvmispec "kubevirt.io/kubevirt/pkg/network/vmispec"
"kubevirt.io/kubevirt/pkg/util"
"kubevirt.io/kubevirt/pkg/virt-handler/heartbeat"
"kubevirt.io/kubevirt/pkg/util/hardware"
"kubevirt.io/kubevirt/pkg/util/migrations"
container_disk "kubevirt.io/kubevirt/pkg/virt-handler/container-disk"
device_manager "kubevirt.io/kubevirt/pkg/virt-handler/device-manager"
hotplug_volume "kubevirt.io/kubevirt/pkg/virt-handler/hotplug-disk"
ps "github.com/mitchellh/go-ps"
v1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/client-go/log"
containerdisk "kubevirt.io/kubevirt/pkg/container-disk"
"kubevirt.io/kubevirt/pkg/controller"
diskutils "kubevirt.io/kubevirt/pkg/ephemeral-disk-utils"
"kubevirt.io/kubevirt/pkg/executor"
hostdisk "kubevirt.io/kubevirt/pkg/host-disk"
neterrors "kubevirt.io/kubevirt/pkg/network/errors"
"kubevirt.io/kubevirt/pkg/storage/reservation"
pvctypes "kubevirt.io/kubevirt/pkg/storage/types"
virtutil "kubevirt.io/kubevirt/pkg/util"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
virtcache "kubevirt.io/kubevirt/pkg/virt-handler/cache"
cmdclient "kubevirt.io/kubevirt/pkg/virt-handler/cmd-client"
"kubevirt.io/kubevirt/pkg/virt-handler/isolation"
migrationproxy "kubevirt.io/kubevirt/pkg/virt-handler/migration-proxy"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
"kubevirt.io/kubevirt/pkg/watchdog"
)
type netconf interface {
Setup(vmi *v1.VirtualMachineInstance, networks []v1.Network, launcherPid int, preSetup func() error) error
Teardown(vmi *v1.VirtualMachineInstance) error
}
type netstat interface {
UpdateStatus(vmi *v1.VirtualMachineInstance, domain *api.Domain) error
Teardown(vmi *v1.VirtualMachineInstance)
PodInterfaceVolatileDataIsCached(vmi *v1.VirtualMachineInstance, ifaceName string) bool
CachePodInterfaceVolatileData(vmi *v1.VirtualMachineInstance, ifaceName string, data *netcache.PodIfaceCacheData)
}
type downwardMetricsManager interface {
Run(stopCh chan struct{})
StartServer(vmi *v1.VirtualMachineInstance, pid int) error
StopServer(vmi *v1.VirtualMachineInstance)
}
const (
failedDetectIsolationFmt = "failed to detect isolation for launcher pod: %v"
unableCreateVirtLauncherConnectionFmt = "unable to create virt-launcher client connection: %v"
)
const (
//VolumeReadyReason is the reason set when the volume is ready.
VolumeReadyReason = "VolumeReady"
//VolumeUnMountedFromPodReason is the reason set when the volume is unmounted from the virtlauncher pod
VolumeUnMountedFromPodReason = "VolumeUnMountedFromPod"
//VolumeMountedToPodReason is the reason set when the volume is mounted to the virtlauncher pod
VolumeMountedToPodReason = "VolumeMountedToPod"
//VolumeUnplugged is the reason set when the volume is completely unplugged from the VMI
VolumeUnplugged = "VolumeUnplugged"
//VMIDefined is the reason set when a VMI is defined
VMIDefined = "VirtualMachineInstance defined."
//VMIStarted is the reason set when a VMI is started
VMIStarted = "VirtualMachineInstance started."
//VMIShutdown is the reason set when a VMI is shutdown
VMIShutdown = "The VirtualMachineInstance was shut down."
//VMICrashed is the reason set when a VMI crashed
VMICrashed = "The VirtualMachineInstance crashed."
//VMIAbortingMigration is the reason set when migration is being aborted
VMIAbortingMigration = "VirtualMachineInstance is aborting migration."
//VMIMigrating in the reason set when the VMI is migrating
VMIMigrating = "VirtualMachineInstance is migrating."
//VMIMigrationTargetPrepared is the reason set when the migration target has been prepared
VMIMigrationTargetPrepared = "VirtualMachineInstance Migration Target Prepared."
//VMIStopping is the reason set when the VMI is stopping
VMIStopping = "VirtualMachineInstance stopping"
//VMIGracefulShutdown is the reason set when the VMI is gracefully shut down
VMIGracefulShutdown = "Signaled Graceful Shutdown"
//VMISignalDeletion is the reason set when the VMI has signal deletion
VMISignalDeletion = "Signaled Deletion"
)
var RequiredGuestAgentCommands = []string{
"guest-ping",
"guest-get-time",
"guest-info",
"guest-shutdown",
"guest-network-get-interfaces",
"guest-get-fsinfo",
"guest-get-host-name",
"guest-get-users",
"guest-get-timezone",
"guest-get-osinfo",
}
var SSHRelatedGuestAgentCommands = []string{
"guest-exec-status",
"guest-exec",
"guest-file-open",
"guest-file-close",
"guest-file-read",
"guest-file-write",
}
var PasswordRelatedGuestAgentCommands = []string{
"guest-set-user-password",
}
var getCgroupManager = func(vmi *v1.VirtualMachineInstance) (cgroup.Manager, error) {
return cgroup.NewManagerFromVM(vmi)
}
func NewController(
recorder record.EventRecorder,
clientset kubecli.KubevirtClient,
host string,
migrationIpAddress string,
virtShareDir string,
virtPrivateDir string,
kubeletPodsDir string,
vmiSourceInformer cache.SharedIndexInformer,
vmiTargetInformer cache.SharedIndexInformer,
domainInformer cache.SharedInformer,
watchdogTimeoutSeconds int,
maxDevices int,
clusterConfig *virtconfig.ClusterConfig,
podIsolationDetector isolation.PodIsolationDetector,
migrationProxy migrationproxy.ProxyManager,
downwardMetricsManager downwardMetricsManager,
capabilities *nodelabellerapi.Capabilities,
hostCpuModel string,
) (*VirtualMachineController, error) {
queue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "virt-handler-vm")
c := &VirtualMachineController{
Queue: queue,
recorder: recorder,
clientset: clientset,
host: host,
migrationIpAddress: migrationIpAddress,
virtShareDir: virtShareDir,
vmiSourceInformer: vmiSourceInformer,
vmiTargetInformer: vmiTargetInformer,
domainInformer: domainInformer,
heartBeatInterval: 1 * time.Minute,
watchdogTimeoutSeconds: watchdogTimeoutSeconds,
migrationProxy: migrationProxy,
podIsolationDetector: podIsolationDetector,
containerDiskMounter: container_disk.NewMounter(podIsolationDetector, filepath.Join(virtPrivateDir, "container-disk-mount-state"), clusterConfig),
hotplugVolumeMounter: hotplug_volume.NewVolumeMounter(filepath.Join(virtPrivateDir, "hotplug-volume-mount-state"), kubeletPodsDir),
clusterConfig: clusterConfig,
virtLauncherFSRunDirPattern: "/proc/%d/root/var/run",
capabilities: capabilities,
hostCpuModel: hostCpuModel,
vmiExpectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()),
sriovHotplugExecutorPool: executor.NewRateLimitedExecutorPool(executor.NewExponentialLimitedBackoffCreator()),
ioErrorRetryManager: NewFailRetryManager("io-error-retry", 10*time.Second, 3*time.Minute, 30*time.Second),
}
_, err := vmiSourceInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addFunc,
DeleteFunc: c.deleteFunc,
UpdateFunc: c.updateFunc,
})
if err != nil {
return nil, err
}
_, err = vmiTargetInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addFunc,
DeleteFunc: c.deleteFunc,
UpdateFunc: c.updateFunc,
})
if err != nil {
return nil, err
}
_, err = domainInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addDomainFunc,
DeleteFunc: c.deleteDomainFunc,
UpdateFunc: c.updateDomainFunc,
})
if err != nil {
return nil, err
}
c.launcherClients = virtcache.LauncherClientInfoByVMI{}
c.netConf = netsetup.NewNetConf()
c.netStat = netsetup.NewNetStat()
c.downwardMetricsManager = downwardMetricsManager
c.domainNotifyPipes = make(map[string]string)
permissions := "rw"
if cgroups.IsCgroup2UnifiedMode() {
// Need 'rwm' permissions otherwise ebpf filtering program attached by runc
// will deny probing the device file with 'access' syscall. That in turn
// will lead to virtqemud failure on VM startup.
// This has been fixed upstream:
// https://github.com/opencontainers/runc/pull/2796
// but the workaround is still needed to support previous versions without
// the patch.
permissions = "rwm"
}
c.deviceManagerController = device_manager.NewDeviceController(
c.host,
maxDevices,
permissions,
device_manager.PermanentHostDevicePlugins(maxDevices, permissions),
clusterConfig,
clientset.CoreV1())
c.heartBeat = heartbeat.NewHeartBeat(clientset.CoreV1(), c.deviceManagerController, clusterConfig, host)
return c, nil
}
type VirtualMachineController struct {
recorder record.EventRecorder
clientset kubecli.KubevirtClient
host string
migrationIpAddress string
virtShareDir string
virtPrivateDir string
Queue workqueue.RateLimitingInterface
vmiSourceInformer cache.SharedIndexInformer
vmiTargetInformer cache.SharedIndexInformer
domainInformer cache.SharedInformer
launcherClients virtcache.LauncherClientInfoByVMI
heartBeatInterval time.Duration
watchdogTimeoutSeconds int
deviceManagerController *device_manager.DeviceController
migrationProxy migrationproxy.ProxyManager
podIsolationDetector isolation.PodIsolationDetector
containerDiskMounter container_disk.Mounter
hotplugVolumeMounter hotplug_volume.VolumeMounter
clusterConfig *virtconfig.ClusterConfig
sriovHotplugExecutorPool *executor.RateLimitedExecutorPool
downwardMetricsManager downwardMetricsManager
netConf netconf
netStat netstat
domainNotifyPipes map[string]string
virtLauncherFSRunDirPattern string
heartBeat *heartbeat.HeartBeat
capabilities *nodelabellerapi.Capabilities
hostCpuModel string
vmiExpectations *controller.UIDTrackingControllerExpectations
ioErrorRetryManager *FailRetryManager
}
type virtLauncherCriticalSecurebootError struct {
msg string
}
func (e *virtLauncherCriticalSecurebootError) Error() string { return e.msg }
func handleDomainNotifyPipe(domainPipeStopChan chan struct{}, ln net.Listener, virtShareDir string, vmi *v1.VirtualMachineInstance) {
fdChan := make(chan net.Conn, 100)
// Close listener and exit when stop encountered
go func() {
<-domainPipeStopChan
log.Log.Object(vmi).Infof("closing notify pipe listener for vmi")
if err := ln.Close(); err != nil {
log.Log.Object(vmi).Infof("failed closing notify pipe listener for vmi: %v", err)
}
}()
// Listen for new connections,
go func(vmi *v1.VirtualMachineInstance, ln net.Listener, domainPipeStopChan chan struct{}) {
for {
fd, err := ln.Accept()
if err != nil {
if goerror.Is(err, net.ErrClosed) {
// As Accept blocks, closing it is our mechanism to exit this loop
return
}
log.Log.Reason(err).Error("Domain pipe accept error encountered.")
// keep listening until stop invoked
time.Sleep(1 * time.Second)
} else {
fdChan <- fd
}
}
}(vmi, ln, domainPipeStopChan)
// Process new connections
// exit when stop encountered
go func(vmi *v1.VirtualMachineInstance, fdChan chan net.Conn, domainPipeStopChan chan struct{}) {
for {
select {
case <-domainPipeStopChan:
return
case fd := <-fdChan:
go func(vmi *v1.VirtualMachineInstance) {
defer fd.Close()
// pipe the VMI domain-notify.sock to the virt-handler domain-notify.sock
// so virt-handler receives notifications from the VMI
conn, err := net.Dial("unix", filepath.Join(virtShareDir, "domain-notify.sock"))
if err != nil {
log.Log.Reason(err).Error("error connecting to domain-notify.sock for proxy connection")
return
}
defer conn.Close()
log.Log.Object(vmi).Infof("Accepted new notify pipe connection for vmi")
copyErr := make(chan error, 2)
go func() {
_, err := io.Copy(fd, conn)
copyErr <- err
}()
go func() {
_, err := io.Copy(conn, fd)
copyErr <- err
}()
// wait until one of the copy routines exit then
// let the fd close
err = <-copyErr
if err != nil {
log.Log.Object(vmi).Infof("closing notify pipe connection for vmi with error: %v", err)
} else {
log.Log.Object(vmi).Infof("gracefully closed notify pipe connection for vmi")
}
}(vmi)
}
}
}(vmi, fdChan, domainPipeStopChan)
}
func (d *VirtualMachineController) startDomainNotifyPipe(domainPipeStopChan chan struct{}, vmi *v1.VirtualMachineInstance) error {
res, err := d.podIsolationDetector.Detect(vmi)
if err != nil {
return fmt.Errorf("failed to detect isolation for launcher pod when setting up notify pipe: %v", err)
}
// inject the domain-notify.sock into the VMI pod.
root, err := res.MountRoot()
if err != nil {
return err
}
socketDir, err := root.AppendAndResolveWithRelativeRoot(d.virtShareDir)
if err != nil {
return err
}
listener, err := safepath.ListenUnixNoFollow(socketDir, "domain-notify-pipe.sock")
if err != nil {
log.Log.Reason(err).Error("failed to create unix socket for proxy service")
return err
}
socketPath, err := safepath.JoinNoFollow(socketDir, "domain-notify-pipe.sock")
if err != nil {
return err
}
if util.IsNonRootVMI(vmi) {
err := diskutils.DefaultOwnershipManager.SetFileOwnership(socketPath)
if err != nil {
log.Log.Reason(err).Error("unable to change ownership for domain notify")
return err
}
}
handleDomainNotifyPipe(domainPipeStopChan, listener, d.virtShareDir, vmi)
return nil
}
// Determines if a domain's grace period has expired during shutdown.
// If the grace period has started but not expired, timeLeft represents
// the time in seconds left until the period expires.
// If the grace period has not started, timeLeft will be set to -1.
func (d *VirtualMachineController) hasGracePeriodExpired(dom *api.Domain) (hasExpired bool, timeLeft int64) {
hasExpired = false
timeLeft = 0
if dom == nil {
hasExpired = true
return
}
startTime := int64(0)
if dom.Spec.Metadata.KubeVirt.GracePeriod.DeletionTimestamp != nil {
startTime = dom.Spec.Metadata.KubeVirt.GracePeriod.DeletionTimestamp.UTC().Unix()
}
gracePeriod := dom.Spec.Metadata.KubeVirt.GracePeriod.DeletionGracePeriodSeconds
// If gracePeriod == 0, then there will be no startTime set, deletion
// should occur immediately during shutdown.
if gracePeriod == 0 {
hasExpired = true
return
} else if startTime == 0 {
// If gracePeriod > 0, then the shutdown signal needs to be sent
// and the gracePeriod start time needs to be set.
timeLeft = -1
return
}
now := time.Now().UTC().Unix()
diff := now - startTime
if diff >= gracePeriod {
hasExpired = true
return
}
timeLeft = int64(gracePeriod - diff)
if timeLeft < 1 {
timeLeft = 1
}
return
}
func (d *VirtualMachineController) hasTargetDetectedReadyDomain(vmi *v1.VirtualMachineInstance) (bool, int64) {
// give the target node 60 seconds to discover the libvirt domain via the domain informer
// before allowing the VMI to be processed. This closes the gap between the
// VMI's status getting updated to reflect the new source node, and the domain
// informer firing the event to alert the source node of the new domain.
migrationTargetDelayTimeout := 60
if vmi.Status.MigrationState != nil &&
vmi.Status.MigrationState.TargetNodeDomainDetected &&
vmi.Status.MigrationState.TargetNodeDomainReadyTimestamp != nil {
return true, 0
}
nowUnix := time.Now().UTC().Unix()
migrationEndUnix := vmi.Status.MigrationState.EndTimestamp.Time.UTC().Unix()
diff := nowUnix - migrationEndUnix
if diff > int64(migrationTargetDelayTimeout) {
return false, 0
}
timeLeft := int64(migrationTargetDelayTimeout) - diff
enqueueTime := timeLeft
if enqueueTime < 5 {
enqueueTime = 5
}
// re-enqueue the key to ensure it gets processed again within the right time.
d.Queue.AddAfter(controller.VirtualMachineInstanceKey(vmi), time.Duration(enqueueTime)*time.Second)
return false, timeLeft
}
// teardownNetwork performs network cache cleanup for a specific VMI.
func (d *VirtualMachineController) teardownNetwork(vmi *v1.VirtualMachineInstance) {
if string(vmi.UID) == "" {
return
}
if err := d.netConf.Teardown(vmi); err != nil {
log.Log.Reason(err).Errorf("failed to delete VMI Network cache files: %s", err.Error())
}
d.netStat.Teardown(vmi)
}
func (d *VirtualMachineController) setupNetwork(vmi *v1.VirtualMachineInstance, networks []v1.Network) error {
if len(networks) == 0 {
return nil
}
isolationRes, err := d.podIsolationDetector.Detect(vmi)
if err != nil {
return fmt.Errorf(failedDetectIsolationFmt, err)
}
rootMount, err := isolationRes.MountRoot()
if err != nil {
return err
}
return d.netConf.Setup(vmi, networks, isolationRes.Pid(), func() error {
if virtutil.WantVirtioNetDevice(vmi) {
if err := d.claimDeviceOwnership(rootMount, "vhost-net"); err != nil {
return neterrors.CreateCriticalNetworkError(fmt.Errorf("failed to set up vhost-net device, %s", err))
}
}
if virtutil.NeedTunDevice(vmi) {
if err := d.claimDeviceOwnership(rootMount, "/net/tun"); err != nil {
return neterrors.CreateCriticalNetworkError(fmt.Errorf("failed to set up tun device, %s", err))
}
}
return nil
})
}
func domainMigrated(domain *api.Domain) bool {
if domain != nil && domain.Status.Status == api.Shutoff && domain.Status.Reason == api.ReasonMigrated {
return true
}
return false
}
func canUpdateToMounted(currentPhase v1.VolumePhase) bool {
return currentPhase == v1.VolumeBound || currentPhase == v1.VolumePending || currentPhase == v1.HotplugVolumeAttachedToNode
}
func canUpdateToUnmounted(currentPhase v1.VolumePhase) bool {
return currentPhase == v1.VolumeReady || currentPhase == v1.HotplugVolumeMounted || currentPhase == v1.HotplugVolumeAttachedToNode
}
func (d *VirtualMachineController) setMigrationProgressStatus(vmi *v1.VirtualMachineInstance, domain *api.Domain) {
if domain == nil ||
domain.Spec.Metadata.KubeVirt.Migration == nil ||
vmi.Status.MigrationState == nil ||
!d.isMigrationSource(vmi) {
return
}
migrationMetadata := domain.Spec.Metadata.KubeVirt.Migration
if migrationMetadata.UID != vmi.Status.MigrationState.MigrationUID {
return
}
if vmi.Status.MigrationState.EndTimestamp == nil && migrationMetadata.EndTimestamp != nil {
if migrationMetadata.Failed {
d.recorder.Event(vmi, k8sv1.EventTypeWarning, v1.Migrated.String(), fmt.Sprintf("VirtualMachineInstance migration uid %s failed. reason:%s", string(migrationMetadata.UID), migrationMetadata.FailureReason))
}
}
if vmi.Status.MigrationState.StartTimestamp == nil {
vmi.Status.MigrationState.StartTimestamp = migrationMetadata.StartTimestamp
}
if vmi.Status.MigrationState.EndTimestamp == nil {
vmi.Status.MigrationState.EndTimestamp = migrationMetadata.EndTimestamp
}
vmi.Status.MigrationState.AbortStatus = v1.MigrationAbortStatus(migrationMetadata.AbortStatus)
vmi.Status.MigrationState.Completed = migrationMetadata.Completed
vmi.Status.MigrationState.Failed = migrationMetadata.Failed
vmi.Status.MigrationState.Mode = migrationMetadata.Mode
}
func (d *VirtualMachineController) migrationSourceUpdateVMIStatus(origVMI *v1.VirtualMachineInstance, domain *api.Domain) error {
vmi := origVMI.DeepCopy()
oldStatus := vmi.DeepCopy().Status
// if a migration happens very quickly, it's possible parts of the in
// progress status wasn't set. We need to make sure we set this even
// if the migration has completed
d.setMigrationProgressStatus(vmi, domain)
// handle migrations differently than normal status updates.
//
// When a successful migration is detected, we must transfer ownership of the VMI
// from the source node (this node) to the target node (node the domain was migrated to).
//
// Transfer ownership by...
// 1. Marking vmi.Status.MigrationState as completed
// 2. Update the vmi.Status.NodeName to reflect the target node's name
// 3. Update the VMI's NodeNameLabel annotation to reflect the target node's name
// 4. Clear the LauncherContainerImageVersion which virt-controller will detect
// and accurately based on the version used on the target pod
//
// After a migration, the VMI's phase is no longer owned by this node. Only the
// MigrationState status field is eligible to be mutated.
migrationHost := ""
if vmi.Status.MigrationState != nil {
migrationHost = vmi.Status.MigrationState.TargetNode
}
if vmi.Status.MigrationState != nil && vmi.Status.MigrationState.EndTimestamp == nil {
now := metav1.NewTime(time.Now())
vmi.Status.MigrationState.EndTimestamp = &now
}
targetNodeDetectedDomain, timeLeft := d.hasTargetDetectedReadyDomain(vmi)
// If we can't detect where the migration went to, then we have no
// way of transferring ownership. The only option here is to move the
// vmi to failed. The cluster vmi controller will then tear down the
// resulting pods.
if migrationHost == "" {
// migrated to unknown host.
vmi.Status.Phase = v1.Failed
vmi.Status.MigrationState.Completed = true
vmi.Status.MigrationState.Failed = true
d.recorder.Event(vmi, k8sv1.EventTypeWarning, v1.Migrated.String(), fmt.Sprintf("The VirtualMachineInstance migrated to unknown host."))
} else if !targetNodeDetectedDomain {
if timeLeft <= 0 {
vmi.Status.Phase = v1.Failed
vmi.Status.MigrationState.Completed = true
vmi.Status.MigrationState.Failed = true
d.recorder.Event(vmi, k8sv1.EventTypeWarning, v1.Migrated.String(), fmt.Sprintf("The VirtualMachineInstance's domain was never observed on the target after the migration completed within the timeout period."))
} else {
log.Log.Object(vmi).Info("Waiting on the target node to observe the migrated domain before performing the handoff")
}
} else if vmi.Status.MigrationState != nil && targetNodeDetectedDomain {
// this is the migration ACK.
// At this point we know that the migration has completed and that
// the target node has seen the domain event.
vmi.Labels[v1.NodeNameLabel] = migrationHost
delete(vmi.Labels, v1.OutdatedLauncherImageLabel)
vmi.Status.LauncherContainerImageVersion = ""
vmi.Status.NodeName = migrationHost
// clean the evacuation node name since have already migrated to a new node
vmi.Status.EvacuationNodeName = ""
vmi.Status.MigrationState.Completed = true
// update the vmi migrationTransport to indicate that next migration should use unix URI
// new workloads will set the migrationTransport on their creation, however, legacy workloads
// can make the switch only after the first migration
vmi.Status.MigrationTransport = v1.MigrationTransportUnix
d.recorder.Event(vmi, k8sv1.EventTypeNormal, v1.Migrated.String(), fmt.Sprintf("The VirtualMachineInstance migrated to node %s.", migrationHost))
log.Log.Object(vmi).Infof("migration completed to node %s", migrationHost)
}
if !equality.Semantic.DeepEqual(oldStatus, vmi.Status) {
key := controller.VirtualMachineInstanceKey(vmi)
d.vmiExpectations.SetExpectations(key, 1, 0)
_, err := d.clientset.VirtualMachineInstance(vmi.ObjectMeta.Namespace).Update(context.Background(), vmi)
if err != nil {
d.vmiExpectations.LowerExpectations(key, 1, 0)
return err
}
}
return nil
}
func domainIsActiveOnTarget(domain *api.Domain) bool {
if domain == nil {
return false
}
// It's possible for the domain to be active on the target node if the domain is
// 1. Running
// 2. User initiated Paused
if domain.Status.Status == api.Running {
return true
} else if domain.Status.Status == api.Paused && domain.Status.Reason == api.ReasonPausedUser {
return true
}
return false
}
func (d *VirtualMachineController) migrationTargetUpdateVMIStatus(vmi *v1.VirtualMachineInstance, domain *api.Domain) error {
vmiCopy := vmi.DeepCopy()
if migrations.MigrationFailed(vmi) {
// nothing left to report on the target node if the migration failed
return nil
}
domainExists := domain != nil
// Handle post migration
if domainExists && vmi.Status.MigrationState != nil && !vmi.Status.MigrationState.TargetNodeDomainDetected {
// record that we've see the domain populated on the target's node
log.Log.Object(vmi).Info("The target node received the migrated domain")
vmiCopy.Status.MigrationState.TargetNodeDomainDetected = true
// adjust QEMU process memlock limits in order to enable old virt-launcher pod's to
// perform hotplug host-devices on post migration.
if err := isolation.AdjustQemuProcessMemoryLimits(d.podIsolationDetector, vmi, d.clusterConfig.GetConfig().AdditionalGuestMemoryOverheadRatio); err != nil {
d.recorder.Event(vmi, k8sv1.EventTypeWarning, err.Error(), "Failed to update target node qemu memory limits during live migration")
}
}
if domainExists &&
domainIsActiveOnTarget(domain) &&
vmi.Status.MigrationState != nil &&
vmi.Status.MigrationState.TargetNodeDomainReadyTimestamp == nil {
// record the moment we detected the domain is running.
// This is used as a trigger to help coordinate when CNI drivers
// fail over the IP to the new pod.
log.Log.Object(vmi).Info("The target node received the running migrated domain")
now := metav1.Now()
vmiCopy.Status.MigrationState.TargetNodeDomainReadyTimestamp = &now
d.finalizeMigration(vmiCopy)
}
if !migrations.IsMigrating(vmi) {
destSrcPortsMap := d.migrationProxy.GetTargetListenerPorts(string(vmi.UID))
if len(destSrcPortsMap) == 0 {
msg := "target migration listener is not up for this vmi"
log.Log.Object(vmi).Error(msg)
return fmt.Errorf(msg)
}
hostAddress := ""
// advertise the listener address to the source node
if vmi.Status.MigrationState != nil {
hostAddress = vmi.Status.MigrationState.TargetNodeAddress
}
if hostAddress != d.migrationIpAddress {
portsList := make([]string, 0, len(destSrcPortsMap))
for k := range destSrcPortsMap {
portsList = append(portsList, k)
}
portsStrList := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(portsList)), ","), "[]")
d.recorder.Event(vmi, k8sv1.EventTypeNormal, v1.PreparingTarget.String(), fmt.Sprintf("Migration Target is listening at %s, on ports: %s", d.migrationIpAddress, portsStrList))
vmiCopy.Status.MigrationState.TargetNodeAddress = d.migrationIpAddress
vmiCopy.Status.MigrationState.TargetDirectMigrationNodePorts = destSrcPortsMap
}
// If the migrated VMI requires dedicated CPUs, report the new pod CPU set to the source node
// via the VMI migration status in order to patch the domain pre migration
if vmi.IsCPUDedicated() {
err := d.reportDedicatedCPUSetForMigratingVMI(vmiCopy)
if err != nil {
return err
}
err = d.reportTargetTopologyForMigratingVMI(vmiCopy)
if err != nil {
return err
}
}
}
// update the VMI if necessary
if !equality.Semantic.DeepEqual(vmi.Status, vmiCopy.Status) {
key := controller.VirtualMachineInstanceKey(vmi)
d.vmiExpectations.SetExpectations(key, 1, 0)
_, err := d.clientset.VirtualMachineInstance(vmi.ObjectMeta.Namespace).Update(context.Background(), vmiCopy)
if err != nil {
d.vmiExpectations.LowerExpectations(key, 1, 0)
return err
}
}
return nil
}
func (d *VirtualMachineController) generateEventsForVolumeStatusChange(vmi *v1.VirtualMachineInstance, newStatusMap map[string]v1.VolumeStatus) {
newStatusMapCopy := make(map[string]v1.VolumeStatus)
for k, v := range newStatusMap {
newStatusMapCopy[k] = v
}
for _, oldStatus := range vmi.Status.VolumeStatus {
newStatus, ok := newStatusMap[oldStatus.Name]
if !ok {
// status got removed
d.recorder.Event(vmi, k8sv1.EventTypeNormal, VolumeUnplugged, fmt.Sprintf("Volume %s has been unplugged", oldStatus.Name))
continue
}
if newStatus.Phase != oldStatus.Phase {
d.recorder.Event(vmi, k8sv1.EventTypeNormal, newStatus.Reason, newStatus.Message)
}
delete(newStatusMapCopy, newStatus.Name)
}
// Send events for any new statuses.
for _, v := range newStatusMapCopy {
d.recorder.Event(vmi, k8sv1.EventTypeNormal, v.Reason, v.Message)
}
}
func (d *VirtualMachineController) updateHotplugVolumeStatus(vmi *v1.VirtualMachineInstance, volumeStatus v1.VolumeStatus, specVolumeMap map[string]v1.Volume) (v1.VolumeStatus, bool) {
needsRefresh := false
if volumeStatus.Target == "" {
needsRefresh = true
mounted, err := d.hotplugVolumeMounter.IsMounted(vmi, volumeStatus.Name, volumeStatus.HotplugVolume.AttachPodUID)
if err != nil {
log.Log.Object(vmi).Errorf("error occurred while checking if volume is mounted: %v", err)
}
if mounted {
if _, ok := specVolumeMap[volumeStatus.Name]; ok && canUpdateToMounted(volumeStatus.Phase) {
log.DefaultLogger().Infof("Marking volume %s as mounted in pod, it can now be attached", volumeStatus.Name)
// mounted, and still in spec, and in phase we can change, update status to mounted.
volumeStatus.Phase = v1.HotplugVolumeMounted
volumeStatus.Message = fmt.Sprintf("Volume %s has been mounted in virt-launcher pod", volumeStatus.Name)
volumeStatus.Reason = VolumeMountedToPodReason
}
} else {
// Not mounted, check if the volume is in the spec, if not update status
if _, ok := specVolumeMap[volumeStatus.Name]; !ok && canUpdateToUnmounted(volumeStatus.Phase) {
log.DefaultLogger().Infof("Marking volume %s as unmounted from pod, it can now be detached", volumeStatus.Name)
// Not mounted.
volumeStatus.Phase = v1.HotplugVolumeUnMounted
volumeStatus.Message = fmt.Sprintf("Volume %s has been unmounted from virt-launcher pod", volumeStatus.Name)
volumeStatus.Reason = VolumeUnMountedFromPodReason
}
}
} else {
// Successfully attached to VM.
volumeStatus.Phase = v1.VolumeReady
volumeStatus.Message = fmt.Sprintf("Successfully attach hotplugged volume %s to VM", volumeStatus.Name)
volumeStatus.Reason = VolumeReadyReason
}
return volumeStatus, needsRefresh
}
func needToComputeChecksums(vmi *v1.VirtualMachineInstance) bool {
containerDisks := map[string]*v1.Volume{}
for _, volume := range vmi.Spec.Volumes {
if volume.VolumeSource.ContainerDisk != nil {
containerDisks[volume.Name] = &volume
}
}
for i := range vmi.Status.VolumeStatus {
_, isContainerDisk := containerDisks[vmi.Status.VolumeStatus[i].Name]
if !isContainerDisk {
continue
}
if vmi.Status.VolumeStatus[i].ContainerDiskVolume == nil ||
vmi.Status.VolumeStatus[i].ContainerDiskVolume.Checksum == 0 {
return true
}
}
if util.HasKernelBootContainerImage(vmi) {
if vmi.Status.KernelBootStatus == nil {
return true
}
kernelBootContainer := vmi.Spec.Domain.Firmware.KernelBoot.Container
if kernelBootContainer.KernelPath != "" &&
(vmi.Status.KernelBootStatus.KernelInfo == nil ||
vmi.Status.KernelBootStatus.KernelInfo.Checksum == 0) {
return true
}
if kernelBootContainer.InitrdPath != "" &&
(vmi.Status.KernelBootStatus.InitrdInfo == nil ||
vmi.Status.KernelBootStatus.InitrdInfo.Checksum == 0) {
return true
}
}
return false
}
func (d *VirtualMachineController) updateChecksumInfo(vmi *v1.VirtualMachineInstance, syncError error) error {
if syncError != nil || vmi.DeletionTimestamp != nil || !needToComputeChecksums(vmi) {
return nil
}
diskChecksums, err := d.containerDiskMounter.ComputeChecksums(vmi)
if goerror.Is(err, container_disk.ErrDiskContainerGone) {
log.Log.Errorf("cannot compute checksums as containerdisk/kernelboot containers seem to have been terminated")
return nil
}
if err != nil {
return err
}
// containerdisks
for i := range vmi.Status.VolumeStatus {
checksum, exists := diskChecksums.ContainerDiskChecksums[vmi.Status.VolumeStatus[i].Name]
if !exists {
// not a containerdisk
continue
}
vmi.Status.VolumeStatus[i].ContainerDiskVolume = &v1.ContainerDiskInfo{
Checksum: checksum,
}
}
// kernelboot
if util.HasKernelBootContainerImage(vmi) {
vmi.Status.KernelBootStatus = &v1.KernelBootStatus{}
if diskChecksums.KernelBootChecksum.Kernel != nil {
vmi.Status.KernelBootStatus.KernelInfo = &v1.KernelInfo{
Checksum: *diskChecksums.KernelBootChecksum.Kernel,
}
}
if diskChecksums.KernelBootChecksum.Initrd != nil {
vmi.Status.KernelBootStatus.InitrdInfo = &v1.InitrdInfo{
Checksum: *diskChecksums.KernelBootChecksum.Initrd,
}
}
}
return nil
}
func (d *VirtualMachineController) updateVolumeStatusesFromDomain(vmi *v1.VirtualMachineInstance, domain *api.Domain) bool {
// used by unit test
hasHotplug := false
if domain == nil {
return hasHotplug
}
if len(vmi.Status.VolumeStatus) > 0 {
diskDeviceMap := make(map[string]string)
for _, disk := range domain.Spec.Devices.Disks {
diskDeviceMap[disk.Alias.GetName()] = disk.Target.Device
}
specVolumeMap := make(map[string]v1.Volume)
for _, volume := range vmi.Spec.Volumes {
specVolumeMap[volume.Name] = volume
}
newStatusMap := make(map[string]v1.VolumeStatus)
newStatuses := make([]v1.VolumeStatus, 0)
needsRefresh := false
for _, volumeStatus := range vmi.Status.VolumeStatus {
tmpNeedsRefresh := false
if _, ok := diskDeviceMap[volumeStatus.Name]; ok {
volumeStatus.Target = diskDeviceMap[volumeStatus.Name]
}