-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
manager.go
1727 lines (1526 loc) · 53.4 KB
/
manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the KubeVirt project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2017, 2018 Red Hat, Inc.
*
*/
package virtwrap
//go:generate mockgen -source $GOFILE -package=$GOPACKAGE -destination=generated_mock_$GOFILE
/*
ATTENTION: Rerun code generators when interface signatures are modified.
*/
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
cmdclient "kubevirt.io/kubevirt/pkg/virt-handler/cmd-client"
eventsclient "kubevirt.io/kubevirt/pkg/virt-launcher/notify-client"
libvirt "github.com/libvirt/libvirt-go"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
utilwait "k8s.io/apimachinery/pkg/util/wait"
v1 "kubevirt.io/client-go/api/v1"
"kubevirt.io/client-go/log"
cloudinit "kubevirt.io/kubevirt/pkg/cloud-init"
"kubevirt.io/kubevirt/pkg/config"
containerdisk "kubevirt.io/kubevirt/pkg/container-disk"
"kubevirt.io/kubevirt/pkg/emptydisk"
ephemeraldisk "kubevirt.io/kubevirt/pkg/ephemeral-disk"
cmdv1 "kubevirt.io/kubevirt/pkg/handler-launcher-com/cmd/v1"
"kubevirt.io/kubevirt/pkg/hooks"
hostdisk "kubevirt.io/kubevirt/pkg/host-disk"
"kubevirt.io/kubevirt/pkg/ignition"
migrationproxy "kubevirt.io/kubevirt/pkg/virt-handler/migration-proxy"
agentpoller "kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/agent-poller"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/cli"
domainerrors "kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/errors"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/network"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/stats"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/util"
)
const LibvirtLocalConnectionPort = 22222
const gpuEnvPrefix = "GPU_PASSTHROUGH_DEVICES"
const vgpuEnvPrefix = "VGPU_PASSTHROUGH_DEVICES"
type contextStore struct {
ctx context.Context
cancel context.CancelFunc
}
type DomainManager interface {
SyncVMI(*v1.VirtualMachineInstance, bool, *cmdv1.VirtualMachineOptions) (*api.DomainSpec, error)
PauseVMI(*v1.VirtualMachineInstance) error
UnpauseVMI(*v1.VirtualMachineInstance) error
KillVMI(*v1.VirtualMachineInstance) error
DeleteVMI(*v1.VirtualMachineInstance) error
SignalShutdownVMI(*v1.VirtualMachineInstance) error
MarkGracefulShutdownVMI(*v1.VirtualMachineInstance) error
ListAllDomains() ([]*api.Domain, error)
MigrateVMI(*v1.VirtualMachineInstance, *cmdclient.MigrationOptions) error
PrepareMigrationTarget(*v1.VirtualMachineInstance, bool) error
GetDomainStats() ([]*stats.DomainStats, error)
CancelVMIMigration(*v1.VirtualMachineInstance) error
GetGuestInfo() (v1.VirtualMachineInstanceGuestAgentInfo, error)
GetUsers() ([]v1.VirtualMachineInstanceGuestOSUser, error)
GetFilesystems() ([]v1.VirtualMachineInstanceFileSystem, error)
SetGuestTime(*v1.VirtualMachineInstance) error
}
type LibvirtDomainManager struct {
virConn cli.Connection
// Anytime a get and a set is done on the domain, this lock must be held.
domainModifyLock sync.Mutex
// mutex to control access to the guest time context
setGuestTimeLock sync.Mutex
virtShareDir string
notifier *eventsclient.Notifier
lessPVCSpaceToleration int
paused pausedVMIs
agentData *agentpoller.AsyncAgentStore
cloudInitDataStore *cloudinit.CloudInitData
setGuestTimeContextPtr *contextStore
ovmfPath string
}
type migrationDisks struct {
shared map[string]bool
generated map[string]bool
}
type pausedVMIs struct {
paused map[types.UID]bool
}
func (s pausedVMIs) add(uid types.UID) {
// implicitly locked by domainModifyLock
if _, ok := s.paused[uid]; !ok {
s.paused[uid] = true
}
}
func (s pausedVMIs) remove(uid types.UID) {
// implicitly locked by domainModifyLock
if _, ok := s.paused[uid]; ok {
delete(s.paused, uid)
}
}
func (s pausedVMIs) contains(uid types.UID) bool {
_, ok := s.paused[uid]
return ok
}
func NewLibvirtDomainManager(connection cli.Connection, virtShareDir string, notifier *eventsclient.Notifier, lessPVCSpaceToleration int, agentStore *agentpoller.AsyncAgentStore, ovmfPath string) (DomainManager, error) {
manager := LibvirtDomainManager{
virConn: connection,
virtShareDir: virtShareDir,
notifier: notifier,
lessPVCSpaceToleration: lessPVCSpaceToleration,
paused: pausedVMIs{
paused: make(map[types.UID]bool, 0),
},
agentData: agentStore,
ovmfPath: ovmfPath,
}
return &manager, nil
}
func (l *LibvirtDomainManager) initializeMigrationMetadata(vmi *v1.VirtualMachineInstance) (bool, error) {
l.domainModifyLock.Lock()
defer l.domainModifyLock.Unlock()
domName := api.VMINamespaceKeyFunc(vmi)
dom, err := l.virConn.LookupDomainByName(domName)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Getting the domain for migration failed.")
return false, err
}
defer dom.Free()
domainSpec, err := l.getDomainSpec(dom)
if err != nil {
return false, err
}
migrationMetadata := domainSpec.Metadata.KubeVirt.Migration
if migrationMetadata != nil && migrationMetadata.UID == vmi.Status.MigrationState.MigrationUID {
if migrationMetadata.EndTimestamp == nil {
// don't stomp on currently executing migrations
return true, nil
} else {
// Don't allow the same migration UID to be executed twice.
// Migration attempts are like pods. One shot.
return false, fmt.Errorf("migration job already executed")
}
}
now := metav1.Now()
domainSpec.Metadata.KubeVirt.Migration = &api.MigrationMetadata{
UID: vmi.Status.MigrationState.MigrationUID,
StartTimestamp: &now,
}
_, err = l.setDomainSpecWithHooks(vmi, domainSpec)
if err != nil {
return false, err
}
return false, nil
}
func (l *LibvirtDomainManager) setMigrationResult(vmi *v1.VirtualMachineInstance, failed bool, reason string, abortStatus v1.MigrationAbortStatus) error {
connectionInterval := 10 * time.Second
connectionTimeout := 60 * time.Second
err := utilwait.PollImmediate(connectionInterval, connectionTimeout, func() (done bool, err error) {
err = l.setMigrationResultHelper(vmi, failed, true, reason, abortStatus)
if err != nil {
return false, nil
}
return true, nil
})
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Unable to post migration results to libvirt after multiple tries")
return err
}
return nil
}
func (l *LibvirtDomainManager) setMigrationAbortStatus(vmi *v1.VirtualMachineInstance, abortStatus v1.MigrationAbortStatus) error {
connectionInterval := 10 * time.Second
connectionTimeout := 60 * time.Second
err := utilwait.PollImmediate(connectionInterval, connectionTimeout, func() (done bool, err error) {
err = l.setMigrationResultHelper(vmi, false, false, "", abortStatus)
if err != nil {
if err == domainerrors.MigrationAbortInProgressError {
return false, err
}
return false, nil
}
return true, nil
})
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Unable to post migration results to libvirt after multiple tries")
return err
}
return nil
}
func (l *LibvirtDomainManager) setMigrationResultHelper(vmi *v1.VirtualMachineInstance, failed bool, completed bool, reason string, abortStatus v1.MigrationAbortStatus) error {
l.domainModifyLock.Lock()
defer l.domainModifyLock.Unlock()
domName := api.VMINamespaceKeyFunc(vmi)
dom, err := l.virConn.LookupDomainByName(domName)
if err != nil {
if domainerrors.IsNotFound(err) {
return nil
} else {
log.Log.Object(vmi).Reason(err).Error("Getting the domain for completed migration failed.")
}
return err
}
defer dom.Free()
domainSpec, err := l.getDomainSpec(dom)
if err != nil {
return err
}
migrationMetadata := domainSpec.Metadata.KubeVirt.Migration
if migrationMetadata == nil {
// nothing to report if migration metadata is empty
return nil
}
now := metav1.Now()
if abortStatus != "" {
metaAbortStatus := domainSpec.Metadata.KubeVirt.Migration.AbortStatus
if metaAbortStatus == string(abortStatus) && metaAbortStatus == string(v1.MigrationAbortInProgress) {
return domainerrors.MigrationAbortInProgressError
}
domainSpec.Metadata.KubeVirt.Migration.AbortStatus = string(abortStatus)
}
if failed {
domainSpec.Metadata.KubeVirt.Migration.Failed = true
domainSpec.Metadata.KubeVirt.Migration.FailureReason = reason
}
if completed {
domainSpec.Metadata.KubeVirt.Migration.Completed = true
domainSpec.Metadata.KubeVirt.Migration.EndTimestamp = &now
}
_, err = l.setDomainSpecWithHooks(vmi, domainSpec)
if err != nil {
return err
}
return nil
}
func prepareMigrationFlags(isBlockMigration bool, isUnsafeMigration bool, allowAutoConverge bool) libvirt.DomainMigrateFlags {
migrateFlags := libvirt.MIGRATE_LIVE | libvirt.MIGRATE_PEER2PEER
if isBlockMigration {
migrateFlags |= libvirt.MIGRATE_NON_SHARED_INC
}
if isUnsafeMigration {
migrateFlags |= libvirt.MIGRATE_UNSAFE
}
if allowAutoConverge {
migrateFlags |= libvirt.MIGRATE_AUTO_CONVERGE
}
return migrateFlags
}
func (d *migrationDisks) isSharedVolume(name string) bool {
_, shared := d.shared[name]
return shared
}
func (d *migrationDisks) isGeneratedVolume(name string) bool {
_, generated := d.generated[name]
return generated
}
func classifyVolumesForMigration(vmi *v1.VirtualMachineInstance) *migrationDisks {
// This method collects all VMI volumes that should not be copied during
// live migration. It also collects all generated disks suck as cloudinit, secrets, ServiceAccount and ConfigMaps
// to make sure that these are being copied during migration.
// Persistent volume claims without ReadWriteMany access mode
// should be filtered out earlier in the process
disks := &migrationDisks{
shared: make(map[string]bool),
generated: make(map[string]bool),
}
for _, volume := range vmi.Spec.Volumes {
volSrc := volume.VolumeSource
if volSrc.PersistentVolumeClaim != nil || volSrc.DataVolume != nil ||
(volSrc.HostDisk != nil && *volSrc.HostDisk.Shared) {
disks.shared[volume.Name] = true
}
if volSrc.ConfigMap != nil || volSrc.Secret != nil ||
volSrc.ServiceAccount != nil || volSrc.CloudInitNoCloud != nil ||
volSrc.CloudInitConfigDrive != nil || volSrc.ContainerDisk != nil {
disks.generated[volume.Name] = true
}
}
return disks
}
func getAllDomainDevices(dom cli.VirDomain) (api.Devices, error) {
xmlstr, err := dom.GetXMLDesc(0)
if err != nil {
return api.Devices{}, err
}
var newSpec api.DomainSpec
err = xml.Unmarshal([]byte(xmlstr), &newSpec)
if err != nil {
return api.Devices{}, err
}
return newSpec.Devices, nil
}
func getAllDomainDisks(dom cli.VirDomain) ([]api.Disk, error) {
devices, err := getAllDomainDevices(dom)
if err != nil {
return nil, err
}
return devices.Disks, nil
}
func getDiskTargetsForMigration(dom cli.VirDomain, vmi *v1.VirtualMachineInstance) []string {
// This method collects all VMI disks that needs to be copied during live migration
// and returns a list of its target device names.
// Shared volues are being excluded.
copyDisks := []string{}
migrationVols := classifyVolumesForMigration(vmi)
disks, err := getAllDomainDisks(dom)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("failed to parse domain XML to get disks.")
}
// the name of the volume should match the alias
for _, disk := range disks {
if disk.ReadOnly != nil && !migrationVols.isGeneratedVolume(disk.Alias.Name) {
continue
}
if (disk.Type != "file" && disk.Type != "block") || migrationVols.isSharedVolume(disk.Alias.Name) {
continue
}
copyDisks = append(copyDisks, disk.Target.Device)
}
return copyDisks
}
func (l *LibvirtDomainManager) asyncMigrate(vmi *v1.VirtualMachineInstance, options *cmdclient.MigrationOptions) {
go func(l *LibvirtDomainManager, vmi *v1.VirtualMachineInstance) {
// Start local migration proxy.
//
// Right now Libvirt won't let us perform a migration using a unix socket, so
// we have to create a local host tcp server (on port 22222) that forwards the traffic
// to libvirt in order to trick libvirt into doing what we want.
// This also creates a tcp server for each additional direct migration connections
// that will be proxied to the destination pod
isBlockMigration := (vmi.Status.MigrationMethod == v1.BlockMigration)
migrationPortsRange := migrationproxy.GetMigrationPortsList(isBlockMigration)
// Create a tcp server for each direct connection proxy
for _, port := range migrationPortsRange {
key := migrationproxy.ConstructProxyKey(string(vmi.UID), port)
migrationProxy := migrationproxy.NewTargetProxy("127.0.0.1", port, nil, nil, migrationproxy.SourceUnixFile(l.virtShareDir, key))
defer migrationProxy.StopListening()
err := migrationProxy.StartListening()
if err != nil {
l.setMigrationResult(vmi, true, fmt.Sprintf("%v", err), "")
return
}
}
// proxy incoming migration requests on port 22222 to the vmi's existing libvirt connection
libvirtConnectionProxy := migrationproxy.NewTargetProxy("127.0.0.1", LibvirtLocalConnectionPort, nil, nil, migrationproxy.SourceUnixFile(l.virtShareDir, string(vmi.UID)))
defer libvirtConnectionProxy.StopListening()
err := libvirtConnectionProxy.StartListening()
if err != nil {
l.setMigrationResult(vmi, true, fmt.Sprintf("%v", err), "")
return
}
// For a tunnelled migration, this is always the uri
dstUri := fmt.Sprintf("qemu+tcp://127.0.0.1:%d/system", LibvirtLocalConnectionPort)
migrUri := "tcp://127.0.0.1"
domName := api.VMINamespaceKeyFunc(vmi)
dom, err := l.virConn.LookupDomainByName(domName)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Live migration failed.")
l.setMigrationResult(vmi, true, fmt.Sprintf("%v", err), "")
return
}
migrateFlags := prepareMigrationFlags(isBlockMigration, options.UnsafeMigration, options.AllowAutoConverge)
if options.UnsafeMigration {
log.Log.Object(vmi).Info("UNSAFE_MIGRATION flag is set, libvirt's migration checks will be disabled!")
}
bandwidth, err := api.QuantityToMebiByte(options.Bandwidth)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Live migration failed. Invalid bandwidth supplied.")
return
}
params := &libvirt.DomainMigrateParameters{
Bandwidth: bandwidth, // MiB/s
URI: migrUri,
URISet: true,
}
copyDisks := getDiskTargetsForMigration(dom, vmi)
if len(copyDisks) != 0 {
params.MigrateDisks = copyDisks
params.MigrateDisksSet = true
}
// start live migration tracking
migrationErrorChan := make(chan error, 1)
defer close(migrationErrorChan)
go liveMigrationMonitor(vmi, dom, l, options, migrationErrorChan)
err = dom.MigrateToURI3(dstUri, params, migrateFlags)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("Live migration failed.")
migrationErrorChan <- err
return
}
log.Log.Object(vmi).Infof("Live migration succeeded.")
}(l, vmi)
}
func (l *LibvirtDomainManager) SetGuestTime(vmi *v1.VirtualMachineInstance) error {
// Try to set VM time to the current value. This is typically useful
// when clock wasn't running on the VM for some time (e.g. during
// suspension or migration), especially if the time delay exceeds NTP
// tolerance.
// It is not guaranteed that the time is actually set (it depends on guest
// environment, especially QEMU agent presence) or that the set time is
// very precise (NTP in the guest should take care of it if needed).
domName := api.VMINamespaceKeyFunc(vmi)
dom, err := l.virConn.LookupDomainByName(domName)
if err != nil {
log.Log.Object(vmi).Reason(err).Error("failed to sync guest time")
return err
}
// try setting the guest time. Fail early if agent is not configured.
l.setGuestTime(vmi, dom)
return nil
}
func (l *LibvirtDomainManager) getGuestTimeContext() context.Context {
l.setGuestTimeLock.Lock()
defer l.setGuestTimeLock.Unlock()
// cancel the already running setGuestTime go-routine if such exist
if l.setGuestTimeContextPtr != nil {
l.setGuestTimeContextPtr.cancel()
}
// create a new context and store it
ctx, cancel := context.WithCancel(context.Background())
l.setGuestTimeContextPtr = &contextStore{ctx: ctx, cancel: cancel}
return ctx
}
func (l *LibvirtDomainManager) setGuestTime(vmi *v1.VirtualMachineInstance, dom cli.VirDomain) {
// get new context
ctx := l.getGuestTimeContext()
go func(ctx context.Context, vmi *v1.VirtualMachineInstance, dom cli.VirDomain) {
timeout := time.After(60 * time.Second)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-timeout:
log.Log.Object(vmi).Error("failed to sync guest time")
return
case <-ctx.Done():
return
case <-ticker.C:
currTime := time.Now()
secs := currTime.Unix()
nsecs := uint(currTime.Nanosecond())
err := dom.SetTime(secs, nsecs, 0)
if err != nil {
libvirtError, ok := err.(libvirt.Error)
if !ok {
log.Log.Object(vmi).Reason(err).Warning("failed to sync guest time")
return
}
switch libvirtError.Code {
case libvirt.ERR_AGENT_UNRESPONSIVE:
log.Log.Object(vmi).Reason(err).Warning("failed to set time: QEMU agent unresponsive")
case libvirt.ERR_OPERATION_UNSUPPORTED:
// no need to retry as this opertaion is not supported
log.Log.Object(vmi).Reason(err).Warning("failed to set time: not supported")
return
case libvirt.ERR_ARGUMENT_UNSUPPORTED:
// no need to retry as the agent is not configured
log.Log.Object(vmi).Reason(err).Warning("failed to set time: agent not configured")
return
default:
log.Log.Object(vmi).Reason(err).Warning("failed to sync guest time")
}
} else {
return
}
}
}
}(ctx, vmi, dom)
}
func getVMIEphemeralDisksTotalSize() *resource.Quantity {
var baseDir = "/var/run/kubevirt-ephemeral-disks/"
totalSize := int64(0)
err := filepath.Walk(baseDir, func(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
totalSize += f.Size()
}
return err
})
if err != nil {
log.Log.Reason(err).Warning("failed to get VMI ephemeral disks size")
return &resource.Quantity{Format: resource.BinarySI}
}
return resource.NewScaledQuantity(totalSize, 0)
}
func getVMIMigrationDataSize(vmi *v1.VirtualMachineInstance) int64 {
var memory resource.Quantity
// Take memory from the requested memory
if v, ok := vmi.Spec.Domain.Resources.Requests[k8sv1.ResourceMemory]; ok {
memory = v
}
// In case that guest memory is explicitly set, override it
if vmi.Spec.Domain.Memory != nil && vmi.Spec.Domain.Memory.Guest != nil {
memory = *vmi.Spec.Domain.Memory.Guest
}
//get total data Size
if vmi.Status.MigrationMethod == v1.BlockMigration {
disksSize := getVMIEphemeralDisksTotalSize()
memory.Add(*disksSize)
}
return memory.ScaledValue(resource.Giga)
}
func liveMigrationMonitor(vmi *v1.VirtualMachineInstance, dom cli.VirDomain, l *LibvirtDomainManager, options *cmdclient.MigrationOptions, migrationErr chan error) {
logger := log.Log.Object(vmi)
start := time.Now().UTC().Unix()
lastProgressUpdate := start
progressWatermark := int64(0)
// update timeouts from migration config
progressTimeout := options.ProgressTimeout
completionTimeoutPerGiB := options.CompletionTimeoutPerGiB
acceptableCompletionTime := completionTimeoutPerGiB * getVMIMigrationDataSize(vmi)
monitorLoop:
for {
select {
case passedErr := <-migrationErr:
if passedErr != nil {
logger.Reason(passedErr).Error("Live migration failed")
var abortStatus v1.MigrationAbortStatus
if strings.Contains(passedErr.Error(), "canceled by client") {
abortStatus = v1.MigrationAbortSucceeded
}
l.setMigrationResult(vmi, true, fmt.Sprintf("Live migration failed %v", passedErr), abortStatus)
break monitorLoop
}
default:
}
stats, err := dom.GetJobInfo()
if err != nil {
logger.Reason(err).Error("failed to get domain job info")
break
}
remainingData := int64(stats.DataRemaining)
switch stats.Type {
case libvirt.DOMAIN_JOB_UNBOUNDED:
// Migration is running
now := time.Now().UTC().Unix()
elapsed := now - start
if (progressWatermark == 0) ||
(progressWatermark > remainingData) {
progressWatermark = remainingData
lastProgressUpdate = now
}
// check if the migration is progressing
progressDelay := now - lastProgressUpdate
if progressTimeout != 0 &&
progressDelay > progressTimeout {
logger.Warningf("Live migration stuck for %d sec", progressDelay)
err := dom.AbortJob()
if err != nil {
logger.Reason(err).Error("failed to abort migration")
}
l.setMigrationResult(vmi, true, fmt.Sprintf("Live migration stuck for %d sec and has been aborted", progressDelay), v1.MigrationAbortSucceeded)
break monitorLoop
}
// check the overall migration time
if acceptableCompletionTime != 0 &&
elapsed > acceptableCompletionTime {
logger.Warningf("Live migration is not completed after %d sec",
acceptableCompletionTime)
err := dom.AbortJob()
if err != nil {
logger.Reason(err).Error("failed to abort migration")
}
l.setMigrationResult(vmi, true, fmt.Sprintf("Live migration is not completed after %d sec and has been aborted", acceptableCompletionTime), v1.MigrationAbortSucceeded)
break monitorLoop
}
case libvirt.DOMAIN_JOB_NONE:
logger.Info("Migration job didn't start yet")
case libvirt.DOMAIN_JOB_COMPLETED:
logger.Info("Migration has been completed")
l.setMigrationResult(vmi, false, "", "")
break monitorLoop
case libvirt.DOMAIN_JOB_FAILED:
logger.Info("Migration job failed")
l.setMigrationResult(vmi, true, fmt.Sprintf("%v", err), "")
break monitorLoop
case libvirt.DOMAIN_JOB_CANCELLED:
logger.Info("Migration was canceled")
l.setMigrationResult(vmi, true, "Live migration aborted ", v1.MigrationAbortSucceeded)
break monitorLoop
}
time.Sleep(400 * time.Millisecond)
}
}
func (l *LibvirtDomainManager) CancelVMIMigration(vmi *v1.VirtualMachineInstance) error {
if vmi.Status.MigrationState == nil || vmi.Status.MigrationState.Completed ||
vmi.Status.MigrationState.Failed || vmi.Status.MigrationState.StartTimestamp == nil {
return fmt.Errorf("failed to cancel migration - vmi is not migrating")
}
err := l.setMigrationAbortStatus(vmi, v1.MigrationAbortInProgress)
if err != nil {
if err == domainerrors.MigrationAbortInProgressError {
return nil
}
return err
}
l.asyncMigrationAbort(vmi)
return nil
}
func (l *LibvirtDomainManager) asyncMigrationAbort(vmi *v1.VirtualMachineInstance) {
go func(l *LibvirtDomainManager, vmi *v1.VirtualMachineInstance) {
domName := api.VMINamespaceKeyFunc(vmi)
dom, err := l.virConn.LookupDomainByName(domName)
if err != nil {
log.Log.Object(vmi).Reason(err).Warning("failed to cancel migration, domain not found ")
return
}
stats, err := dom.GetJobInfo()
if err != nil {
log.Log.Object(vmi).Reason(err).Error("failed to get domain job info")
return
}
if stats.Type == libvirt.DOMAIN_JOB_UNBOUNDED {
err := dom.AbortJob()
if err != nil {
log.Log.Object(vmi).Reason(err).Error("failed to cancel migration")
l.setMigrationAbortStatus(vmi, v1.MigrationAbortFailed)
return
}
log.Log.Object(vmi).Info("Live migration abort succeeded")
}
return
}(l, vmi)
}
func (l *LibvirtDomainManager) MigrateVMI(vmi *v1.VirtualMachineInstance, options *cmdclient.MigrationOptions) error {
if vmi.Status.MigrationState == nil {
return fmt.Errorf("cannot migration VMI until migrationState is ready")
}
inProgress, err := l.initializeMigrationMetadata(vmi)
if err != nil {
return err
}
if inProgress {
return nil
}
if err := updateHostsFile(fmt.Sprintf("%s %s\n", "127.0.0.1", vmi.Status.MigrationState.TargetPod)); err != nil {
return fmt.Errorf("failed to update the hosts file: %v", err)
}
l.asyncMigrate(vmi, options)
return nil
}
var updateHostsFile = func(entry string) error {
file, err := os.OpenFile("/etc/hosts", os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return fmt.Errorf("failed opening file: %s", err)
}
defer file.Close()
_, err = file.WriteString(entry)
if err != nil {
return fmt.Errorf("failed writing to file: %s", err)
}
return nil
}
// Prepares the target pod environment by executing the preStartHook
func (l *LibvirtDomainManager) PrepareMigrationTarget(vmi *v1.VirtualMachineInstance, useEmulation bool) error {
logger := log.Log.Object(vmi)
var emulatorThreadCpu *int
domain := &api.Domain{}
podCPUSet, err := util.GetPodCPUSet()
if err != nil {
logger.Reason(err).Error("failed to read pod cpuset.")
return fmt.Errorf("failed to read pod cpuset: %v", err)
}
// reserve the last cpu for the emulator thread
if vmi.IsCPUDedicated() && vmi.Spec.Domain.CPU.IsolateEmulatorThread {
if len(podCPUSet) > 0 {
emulatorThreadCpu = &podCPUSet[len(podCPUSet)]
podCPUSet = podCPUSet[:len(podCPUSet)-1]
}
}
// Check if PVC volumes are block volumes
isBlockPVCMap := make(map[string]bool)
isBlockDVMap := make(map[string]bool)
diskInfo := make(map[string]*containerdisk.DiskInfo)
for i, volume := range vmi.Spec.Volumes {
if volume.VolumeSource.PersistentVolumeClaim != nil {
isBlockPVC, err := isBlockDeviceVolume(volume.Name)
if err != nil {
logger.Reason(err).Errorf("failed to detect volume mode for Volume %v and PVC %v.",
volume.Name, volume.VolumeSource.PersistentVolumeClaim.ClaimName)
return err
}
isBlockPVCMap[volume.Name] = isBlockPVC
} else if volume.VolumeSource.ContainerDisk != nil {
image, err := containerdisk.GetDiskTargetPartFromLauncherView(i)
if err != nil {
return err
}
info, err := GetImageInfo(image)
if err != nil {
return err
}
diskInfo[volume.Name] = info
} else if volume.VolumeSource.DataVolume != nil {
isBlockDV, err := isBlockDeviceVolume(volume.Name)
if err != nil {
logger.Reason(err).Errorf("failed to detect volume mode for Volume %v and DataVolume %v.",
volume.Name, volume.VolumeSource.DataVolume.Name)
return err
}
isBlockDVMap[volume.Name] = isBlockDV
}
}
// Map the VirtualMachineInstance to the Domain
c := &api.ConverterContext{
Architecture: runtime.GOARCH,
VirtualMachine: vmi,
UseEmulation: useEmulation,
CPUSet: podCPUSet,
IsBlockPVC: isBlockPVCMap,
IsBlockDV: isBlockDVMap,
DiskType: diskInfo,
EmulatorThreadCpu: emulatorThreadCpu,
OVMFPath: l.ovmfPath,
}
if err := api.Convert_v1_VirtualMachine_To_api_Domain(vmi, domain, c); err != nil {
return fmt.Errorf("conversion failed: %v", err)
}
dom, err := l.preStartHook(vmi, domain)
if err != nil {
return fmt.Errorf("pre-start pod-setup failed: %v", err)
}
err = l.generateCloudInitISO(vmi, nil)
if err != nil {
return err
}
// TODO this should probably a OnPrepareMigration hook or something.
// Right now we need to call OnDefineDomain, so that additional setup, which might be done
// by the hook can also be done for the new target pod
hooksManager := hooks.GetManager()
_, err = hooksManager.OnDefineDomain(&dom.Spec, vmi)
if err != nil {
return fmt.Errorf("executing custom preStart hooks failed: %v", err)
}
if err := updateHostsFile(fmt.Sprintf("%s %s\n", "127.0.0.1", vmi.Status.MigrationState.TargetPod)); err != nil {
return fmt.Errorf("failed to update the hosts file: %v", err)
}
isBlockMigration := (vmi.Status.MigrationMethod == v1.BlockMigration)
migrationPortsRange := migrationproxy.GetMigrationPortsList(isBlockMigration)
for _, port := range migrationPortsRange {
// Prepare the direct migration proxy
key := migrationproxy.ConstructProxyKey(string(vmi.UID), port)
curDirectAddress := fmt.Sprintf("%s:%d", "127.0.0.1", port)
unixSocketPath := migrationproxy.SourceUnixFile(l.virtShareDir, key)
migrationProxy := migrationproxy.NewSourceProxy(unixSocketPath, curDirectAddress, nil, nil)
err := migrationProxy.StartListening()
if err != nil {
logger.Reason(err).Errorf("proxy listening failed, socket %s", unixSocketPath)
return err
}
}
return nil
}
func (l *LibvirtDomainManager) generateCloudInitISO(vmi *v1.VirtualMachineInstance, domPtr *cli.VirDomain) error {
var devicesMetadata []cloudinit.DeviceData
// this is the point where we need to build the devices metadata if it was requested.
// This metadata maps the user provided tag to the hypervisor assigned device address.
if domPtr != nil {
data, err := l.buildDevicesMetadata(vmi, *domPtr)
if err != nil {
return err
}
devicesMetadata = data
}
// build condif drive iso file, that includes devices metadata if available
// get stored cloud init data
var cloudInitDataStore *cloudinit.CloudInitData
cloudInitDataStore = l.cloudInitDataStore
if cloudInitDataStore != nil {
// add devices metedata
if devicesMetadata != nil {
cloudInitDataStore.DevicesData = &devicesMetadata
}
err := cloudinit.GenerateLocalData(vmi.Name, vmi.Namespace, cloudInitDataStore)
if err != nil {
return fmt.Errorf("generating local cloud-init data failed: %v", err)
}
}
return nil
}
// All local environment setup that needs to occur before VirtualMachineInstance starts
// can be done in this function. This includes things like...
//
// - storage prep
// - network prep
// - cloud-init
//
// The Domain.Spec can be alterned in this function and any changes
// made to the domain will get set in libvirt after this function exits.
func (l *LibvirtDomainManager) preStartHook(vmi *v1.VirtualMachineInstance, domain *api.Domain) (*api.Domain, error) {
logger := log.Log.Object(vmi)
logger.Info("Executing PreStartHook on VMI pod environment")
err := cloudinit.ResolveNoCloudSecrets(vmi, config.SecretSourceDir)
if err != nil {
return nil, err
}
err = cloudinit.ResolveConfigDriveSecrets(vmi, config.SecretSourceDir)
if err != nil {
return nil, err
}
// generate cloud-init data
cloudInitData, err := cloudinit.ReadCloudInitVolumeDataSource(vmi)
if err != nil {
return domain, fmt.Errorf("PreCloudInitIso hook failed: %v", err)
}
// Pass cloud-init data to PreCloudInitIso hook
logger.Info("Starting PreCloudInitIso hook")
hooksManager := hooks.GetManager()
cloudInitData, err = hooksManager.PreCloudInitIso(vmi, cloudInitData)
if err != nil {
return domain, fmt.Errorf("PreCloudInitIso hook failed: %v", err)
}
if cloudInitData != nil {
// store the generated cloud init metadata.
// cloud init ISO will be generated after the domain definition
l.cloudInitDataStore = cloudInitData
}
// generate ignition data
ignitionData := ignition.GetIgnitionSource(vmi)
if ignitionData != "" {
err := ignition.GenerateIgnitionLocalData(vmi, vmi.Namespace)
if err != nil {
return domain, err
}
}
err = network.SetupNetworkInterfacesPhase2(vmi, domain)
if err != nil {
return domain, fmt.Errorf("preparing the pod network failed: %v", err)
}
// create disks images on the cluster lever
// or initalize disks images for empty PVC
hostDiskCreator := hostdisk.NewHostDiskCreator(l.notifier, l.lessPVCSpaceToleration)
err = hostDiskCreator.Create(vmi)
if err != nil {
return domain, fmt.Errorf("preparing host-disks failed: %v", err)
}
// Create ephemeral disk for container disks
err = containerdisk.CreateEphemeralImages(vmi)
if err != nil {
return domain, fmt.Errorf("preparing ephemeral container disk images failed: %v", err)
}
// Create images for volumes that are marked ephemeral.
err = ephemeraldisk.CreateEphemeralImages(vmi)
if err != nil {
return domain, fmt.Errorf("preparing ephemeral images failed: %v", err)
}
// create empty disks if they exist
if err := emptydisk.CreateTemporaryDisks(vmi); err != nil {
return domain, fmt.Errorf("creating empty disks failed: %v", err)
}
// create ConfigMap disks if they exists
if err := config.CreateConfigMapDisks(vmi); err != nil {
return domain, fmt.Errorf("creating config map disks failed: %v", err)
}
// create Secret disks if they exists
if err := config.CreateSecretDisks(vmi); err != nil {
return domain, fmt.Errorf("creating secret disks failed: %v", err)