-
Notifications
You must be signed in to change notification settings - Fork 909
/
driver_qemu.go
9064 lines (7476 loc) · 258 KB
/
driver_qemu.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
package drivers
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unsafe"
"github.com/flosch/pongo2"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/kballard/go-shellquote"
"github.com/mdlayher/vsock"
"github.com/pkg/sftp"
"golang.org/x/sync/errgroup"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/client"
agentAPI "github.com/canonical/lxd/lxd-agent/api"
"github.com/canonical/lxd/lxd/apparmor"
"github.com/canonical/lxd/lxd/cgroup"
"github.com/canonical/lxd/lxd/db"
dbCluster "github.com/canonical/lxd/lxd/db/cluster"
"github.com/canonical/lxd/lxd/db/warningtype"
"github.com/canonical/lxd/lxd/device"
deviceConfig "github.com/canonical/lxd/lxd/device/config"
"github.com/canonical/lxd/lxd/device/nictype"
"github.com/canonical/lxd/lxd/instance"
"github.com/canonical/lxd/lxd/instance/drivers/qmp"
"github.com/canonical/lxd/lxd/instance/drivers/uefi"
"github.com/canonical/lxd/lxd/instance/instancetype"
"github.com/canonical/lxd/lxd/instance/operationlock"
"github.com/canonical/lxd/lxd/instancewriter"
"github.com/canonical/lxd/lxd/lifecycle"
"github.com/canonical/lxd/lxd/metrics"
"github.com/canonical/lxd/lxd/migration"
"github.com/canonical/lxd/lxd/network"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/resources"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/lxd/state"
storagePools "github.com/canonical/lxd/lxd/storage"
storageDrivers "github.com/canonical/lxd/lxd/storage/drivers"
"github.com/canonical/lxd/lxd/storage/filesystem"
"github.com/canonical/lxd/lxd/subprocess"
pongoTemplate "github.com/canonical/lxd/lxd/template"
"github.com/canonical/lxd/lxd/util"
lxdvsock "github.com/canonical/lxd/lxd/vsock"
"github.com/canonical/lxd/lxd/warnings"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/entity"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/osarch"
"github.com/canonical/lxd/shared/revert"
"github.com/canonical/lxd/shared/units"
"github.com/canonical/lxd/shared/version"
)
// QEMUDefaultCPUCores defines the default number of cores a VM will get if no limit specified.
const QEMUDefaultCPUCores = 1
// QEMUDefaultMemSize is the default memory size for VMs if no limit specified.
const QEMUDefaultMemSize = "1GiB"
// qemuSerialChardevName is used to communicate state via qmp between Qemu and LXD.
const qemuSerialChardevName = "qemu_serial-chardev"
// qemuPCIDeviceIDStart is the first PCI slot used for user configurable devices.
const qemuPCIDeviceIDStart = 4
// qemuDeviceIDPrefix used as part of the name given QEMU devices generated from user added devices.
const qemuDeviceIDPrefix = "dev-lxd_"
// qemuNetDevIDPrefix used as part of the name given QEMU netdevs generated from user added devices.
const qemuNetDevIDPrefix = "lxd_"
// qemuBlockDevIDPrefix used as part of the name given QEMU blockdevs generated from user added devices.
const qemuBlockDevIDPrefix = "lxd_"
// qemuMigrationNBDExportName is the name of the disk device export by the migration NBD server.
const qemuMigrationNBDExportName = "lxd_root"
// VM firmwares.
type vmFirmware struct {
code string
vars string
}
// Debug version of the "default" firmware.
var vmDebugFirmware = "OVMF_CODE.4MB.debug.fd"
var vmGenericFirmwares = []vmFirmware{
{code: "OVMF_CODE.4MB.fd", vars: "OVMF_VARS.4MB.fd"},
{code: "OVMF_CODE.2MB.fd", vars: "OVMF_VARS.2MB.fd"},
{code: "OVMF_CODE.fd", vars: "OVMF_VARS.fd"},
{code: "OVMF_CODE.fd", vars: "qemu.nvram"},
}
var vmSecurebootFirmwares = []vmFirmware{
{code: "OVMF_CODE.4MB.fd", vars: "OVMF_VARS.4MB.ms.fd"},
{code: "OVMF_CODE.2MB.fd", vars: "OVMF_VARS.2MB.ms.fd"},
{code: "OVMF_CODE.fd", vars: "OVMF_VARS.ms.fd"},
{code: "OVMF_CODE.fd", vars: "qemu.nvram"},
}
// Only valid for x86_64.
var vmLegacyFirmwares = []vmFirmware{
{code: "bios-256k.bin", vars: "bios-256k.bin"},
{code: "OVMF_CODE.4MB.CSM.fd", vars: "OVMF_VARS.4MB.CSM.fd"},
{code: "OVMF_CODE.2MB.CSM.fd", vars: "OVMF_VARS.2MB.CSM.fd"},
{code: "OVMF_CODE.CSM.fd", vars: "OVMF_VARS.CSM.fd"},
}
// qemuSparseUSBPorts is the amount of sparse USB ports for VMs.
// 4 are reserved, and the other 4 can be used for any USB device.
const qemuSparseUSBPorts = 8
var errQemuAgentOffline = fmt.Errorf("LXD VM agent isn't currently running")
type monitorHook func(m *qmp.Monitor) error
// qemuLoad creates a Qemu instance from the supplied InstanceArgs.
func qemuLoad(s *state.State, args db.InstanceArgs, p api.Project) (instance.Instance, error) {
// Create the instance struct.
d := qemuInstantiate(s, args, nil, p)
// Expand config and devices.
err := d.expandConfig()
if err != nil {
return nil, err
}
return d, nil
}
// qemuInstantiate creates a Qemu struct without expanding config. The expandedDevices argument is
// used during device config validation when the devices have already been expanded and we do not
// have access to the profiles used to do it. This can be safely passed as nil if not required.
func qemuInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices, p api.Project) *qemu {
d := &qemu{
common: common{
state: s,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logger.AddContext(logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: p,
isSnapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(d.architecture)
if err == nil {
d.architectureName = archName
}
// Cleanup the zero values.
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
d.expandedDevices = expandedDevices
}
return d
}
// qemuCreate creates a new storage volume record and returns an initialised Instance.
// Returns a revert fail function that can be used to undo this function if a subsequent step fails.
func qemuCreate(s *state.State, args db.InstanceArgs, p api.Project) (instance.Instance, revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
// Create the instance struct.
d := &qemu{
common: common{
state: s,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logger.AddContext(logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: p,
isSnapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(d.architecture)
if err == nil {
d.architectureName = archName
}
// Cleanup the zero values.
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
if args.Snapshot {
d.logger.Info("Creating instance snapshot", logger.Ctx{"ephemeral": d.ephemeral})
} else {
d.logger.Info("Creating instance", logger.Ctx{"ephemeral": d.ephemeral})
}
// Load the config.
err = d.init()
if err != nil {
return nil, nil, fmt.Errorf("Failed to expand config: %w", err)
}
// Validate expanded config (allows mixed instance types for profiles).
err = instance.ValidConfig(s.OS, d.expandedConfig, true, instancetype.Any)
if err != nil {
return nil, nil, fmt.Errorf("Invalid config: %w", err)
}
err = instance.ValidDevices(s, d.project, d.Type(), d.localDevices, d.expandedDevices)
if err != nil {
return nil, nil, fmt.Errorf("Invalid devices: %w", err)
}
// Retrieve the instance's storage pool.
_, rootDiskDevice, err := d.getRootDiskDevice()
if err != nil {
return nil, nil, fmt.Errorf("Failed getting root disk: %w", err)
}
if rootDiskDevice["pool"] == "" {
return nil, nil, fmt.Errorf("The instance's root device is missing the pool property")
}
// Initialize the storage pool.
d.storagePool, err = storagePools.LoadByName(d.state, rootDiskDevice["pool"])
if err != nil {
return nil, nil, fmt.Errorf("Failed loading storage pool: %w", err)
}
volType, err := storagePools.InstanceTypeToVolumeType(d.Type())
if err != nil {
return nil, nil, err
}
storagePoolSupported := false
for _, supportedType := range d.storagePool.Driver().Info().VolumeTypes {
if supportedType == volType {
storagePoolSupported = true
break
}
}
if !storagePoolSupported {
return nil, nil, fmt.Errorf("Storage pool does not support instance type")
}
if !d.IsSnapshot() {
// Add devices to instance.
cleanup, err := d.devicesAdd(d, false)
if err != nil {
return nil, nil, err
}
revert.Add(cleanup)
}
if d.isSnapshot {
d.logger.Info("Created instance snapshot", logger.Ctx{"ephemeral": d.ephemeral})
} else {
d.logger.Info("Created instance", logger.Ctx{"ephemeral": d.ephemeral})
}
if d.isSnapshot {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceSnapshotCreated.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceCreated.Event(d, map[string]any{
"type": api.InstanceTypeVM,
"storage-pool": d.storagePool.Name(),
"location": d.Location(),
}))
}
cleanup := revert.Clone().Fail
revert.Success()
return d, cleanup, err
}
// qemu is the QEMU virtual machine driver.
type qemu struct {
common
// Cached handles.
// Do not use these variables directly, instead use their associated get functions so they
// will be initialised on demand.
architectureName string
// Stateful migration streams.
migrationReceiveStateful map[string]io.ReadWriteCloser
}
// getAgentClient returns the current agent client handle.
// Callers should check that the instance is running (and therefore mounted) before caling this function,
// otherwise the qmp.Connect call will fail to use the monitor socket file.
func (d *qemu) getAgentClient() (*http.Client, error) {
// Check if the agent is running.
monitor, err := qmp.Connect(d.monitorPath(), qemuSerialChardevName, d.getMonitorEventHandler())
if err != nil {
return nil, err
}
if !monitor.AgenStarted() {
return nil, errQemuAgentOffline
}
// The connection uses mutual authentication, so use the LXD server's key & cert for client.
agentCert, _, clientCert, clientKey, err := d.generateAgentCert()
if err != nil {
return nil, err
}
// Existing vsock ID from volatile.
vsockID, err := d.getVsockID()
if err != nil {
return nil, err
}
agent, err := lxdvsock.HTTPClient(vsockID, shared.HTTPSDefaultPort, clientCert, clientKey, agentCert)
if err != nil {
return nil, err
}
return agent, nil
}
func (d *qemu) getMonitorEventHandler() func(event string, data map[string]any) {
// Create local variables from instance properties we need so as not to keep references to instance around
// after we have returned the callback function.
instProject := d.Project()
instanceName := d.Name()
state := d.state
return func(event string, data map[string]any) {
if !shared.ValueInSlice(event, []string{qmp.EventVMShutdown, qmp.EventAgentStarted}) {
return // Don't bother loading the instance from DB if we aren't going to handle the event.
}
var err error
var d *qemu // Redefine d as local variable inside callback to avoid keeping references around.
inst := instanceRefGet(instProject.Name, instanceName)
if inst == nil {
inst, err = instance.LoadByProjectAndName(state, instProject.Name, instanceName)
if err != nil {
l := logger.AddContext(logger.Ctx{"project": instProject.Name, "instance": instanceName})
// If DB not available, try loading from backup file.
l.Warn("Failed loading instance from database to handle monitor event, trying backup file", logger.Ctx{"err": err})
instancePath := filepath.Join(shared.VarPath("virtual-machines"), project.Instance(instProject.Name, instanceName))
inst, err = instance.LoadFromBackup(state, instProject.Name, instancePath, false)
if err != nil {
l.Error("Failed loading instance to handle monitor event", logger.Ctx{"err": err})
return
}
}
}
d, ok := inst.(*qemu)
if !ok {
d.logger.Error("Failed to cast instance to *qemu")
return
}
if event == qmp.EventAgentStarted {
d.logger.Debug("Instance agent started")
err := d.advertiseVsockAddress()
if err != nil {
d.logger.Warn("Failed to advertise vsock address to instance agent", logger.Ctx{"err": err})
return
}
} else if event == qmp.EventVMShutdown {
target := "stop"
entry, ok := data["reason"]
if ok && entry == "guest-reset" {
target = "reboot"
}
if entry == qmp.EventVMShutdownReasonDisconnect {
d.logger.Warn("Instance stopped", logger.Ctx{"target": target, "reason": data["reason"]})
} else {
d.logger.Debug("Instance stopped", logger.Ctx{"target": target, "reason": data["reason"]})
}
err = d.onStop(target)
if err != nil {
d.logger.Error("Failed to cleanly stop instance", logger.Ctx{"err": err})
return
}
}
}
}
// mount the instance's config volume if needed.
func (d *qemu) mount() (*storagePools.MountInfo, error) {
var pool storagePools.Pool
pool, err := d.getStoragePool()
if err != nil {
return nil, err
}
if d.IsSnapshot() {
mountInfo, err := pool.MountInstanceSnapshot(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
mountInfo, err := pool.MountInstance(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
// unmount the instance's config volume if needed.
func (d *qemu) unmount() error {
pool, err := d.getStoragePool()
if err != nil {
return err
}
err = pool.UnmountInstance(d, nil)
if err != nil {
return err
}
return nil
}
// generateAgentCert creates the necessary server key and certificate if needed.
func (d *qemu) generateAgentCert() (agentCert string, agentKey string, clientCert string, clientKey string, err error) {
agentCertFile := filepath.Join(d.Path(), "agent.crt")
agentKeyFile := filepath.Join(d.Path(), "agent.key")
clientCertFile := filepath.Join(d.Path(), "agent-client.crt")
clientKeyFile := filepath.Join(d.Path(), "agent-client.key")
// Create server certificate.
err = shared.FindOrGenCert(agentCertFile, agentKeyFile, false, false)
if err != nil {
return "", "", "", "", err
}
// Create client certificate.
err = shared.FindOrGenCert(clientCertFile, clientKeyFile, true, false)
if err != nil {
return "", "", "", "", err
}
// Read all the files
agentCertBytes, err := os.ReadFile(agentCertFile)
if err != nil {
return "", "", "", "", err
}
agentKeyBytes, err := os.ReadFile(agentKeyFile)
if err != nil {
return "", "", "", "", err
}
clientCertBytes, err := os.ReadFile(clientCertFile)
if err != nil {
return "", "", "", "", err
}
clientKeyBytes, err := os.ReadFile(clientKeyFile)
if err != nil {
return "", "", "", "", err
}
return string(agentCertBytes), string(agentKeyBytes), string(clientCertBytes), string(clientKeyBytes), nil
}
// Freeze freezes the instance.
func (d *qemu) Freeze() error {
// Connect to the monitor.
monitor, err := qmp.Connect(d.monitorPath(), qemuSerialChardevName, d.getMonitorEventHandler())
if err != nil {
return err
}
// Send the stop command.
err = monitor.Pause()
if err != nil {
return err
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstancePaused.Event(d, nil))
return nil
}
// configDriveMountPath returns the path for the config drive bind mount.
func (d *qemu) configDriveMountPath() string {
return filepath.Join(d.DevicesPath(), "config.mount")
}
// configDriveMountPathClear attempts to unmount the config drive bind mount and remove the directory.
func (d *qemu) configDriveMountPathClear() error {
return device.DiskMountClear(d.configDriveMountPath())
}
// configVirtiofsdPaths returns the path for the socket and PID file to use with config drive virtiofsd process.
func (d *qemu) configVirtiofsdPaths() (sockPath string, pidPath string) {
sockPath = filepath.Join(d.LogPath(), "virtio-fs.config.sock")
pidPath = filepath.Join(d.LogPath(), "virtiofsd.pid")
return sockPath, pidPath
}
// pidWait waits for the QEMU process to exit. Does this in a way that doesn't require the LXD process to be a
// parent of the QEMU process (in order to allow for LXD to be restarted after the VM was started).
// Returns true if process stopped, false if timeout was exceeded.
func (d *qemu) pidWait(timeout time.Duration) bool {
waitUntil := time.Now().Add(timeout)
for {
pid, _ := d.pid()
if pid <= 0 {
break
}
if time.Now().After(waitUntil) {
return false
}
time.Sleep(time.Millisecond * time.Duration(250))
}
return true
}
// onStop is run when the instance stops.
func (d *qemu) onStop(target string) error {
d.logger.Debug("onStop hook started", logger.Ctx{"target": target})
defer d.logger.Debug("onStop hook finished", logger.Ctx{"target": target})
// Create/pick up operation.
op, err := d.onStopOperationSetup(target)
if err != nil {
return err
}
// Unlock on return
defer op.Done(nil)
// Wait for QEMU process to end (to avoiding racing start when restarting).
// Wait up to 5 minutes to allow for flushing any pending data to disk.
d.logger.Debug("Waiting for VM process to finish")
waitTimeout := time.Minute * 5
if d.pidWait(waitTimeout) {
d.logger.Debug("VM process finished")
} else {
// Log a warning, but continue clean up as best we can.
d.logger.Error("VM process failed to stop", logger.Ctx{"timeout": waitTimeout})
}
// Record power state.
err = d.VolatileSet(map[string]string{
"volatile.last_state.power": instance.PowerStateStopped,
"volatile.last_state.ready": "false",
})
if err != nil {
// Don't return an error here as we still want to cleanup the instance even if DB not available.
d.logger.Error("Failed recording last power state", logger.Ctx{"err": err})
}
// Cleanup.
d.cleanupDevices() // Must be called before unmount.
_ = os.Remove(d.pidFilePath())
_ = os.Remove(d.monitorPath())
// Stop the storage for the instance.
err = d.unmount()
if err != nil && !errors.Is(err, storageDrivers.ErrInUse) {
err = fmt.Errorf("Failed unmounting instance: %w", err)
op.Done(err)
return err
}
// Unload the apparmor profile
err = apparmor.InstanceUnload(d.state.OS, d)
if err != nil {
op.Done(err)
return err
}
// Log and emit lifecycle if not user triggered.
if op.GetInstanceInitiated() {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceShutdown.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceStopped.Event(d, nil))
}
// Reboot the instance.
if target == "reboot" {
err = d.Start(false)
if err != nil {
op.Done(err)
return err
}
d.state.Events.SendLifecycle(d.project.Name, lifecycle.InstanceRestarted.Event(d, nil))
} else if d.ephemeral {
// Destroy ephemeral virtual machines.
err = d.delete(true)
if err != nil {
op.Done(err)
return err
}
}
return nil
}
// Shutdown shuts the instance down.
func (d *qemu) Shutdown(timeout time.Duration) error {
d.logger.Debug("Shutdown started", logger.Ctx{"timeout": timeout})
defer d.logger.Debug("Shutdown finished", logger.Ctx{"timeout": timeout})
// Must be run prior to creating the operation lock.
statusCode := d.statusCode()
if !d.isRunningStatusCode(statusCode) {
if statusCode == api.Error {
return fmt.Errorf("The instance cannot be cleanly shutdown as in %s status", statusCode)
}
return ErrInstanceIsStopped
}
// Setup a new operation.
// Allow inheriting of ongoing restart operation (we are called from restartCommon).
// Allow reuse when creating a new stop operation. This allows the Stop() function to inherit operation.
// Allow reuse of a reusable ongoing stop operation as Shutdown() may be called earlier, which allows reuse
// of its operations. This allow for multiple Shutdown() attempts.
op, err := operationlock.CreateWaitGet(d.Project().Name, d.Name(), operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart}, true, true)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return err
}
// If frozen, resume so the signal can be handled.
if d.IsFrozen() {
err := d.Unfreeze()
if err != nil {
return err
}
}
// Connect to the monitor.
monitor, err := qmp.Connect(d.monitorPath(), qemuSerialChardevName, d.getMonitorEventHandler())
if err != nil {
op.Done(err)
return err
}
// Indicate to the onStop hook that if the VM stops it was due to a clean shutdown because the VM responded
// to the powerdown request.
op.SetInstanceInitiated(true)
// Send the system_powerdown command.
err = monitor.Powerdown()
if err != nil {
if err == qmp.ErrMonitorDisconnect {
op.Done(nil)
return nil
}
op.Done(err)
return err
}
d.logger.Debug("Shutdown request sent to instance")
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Wait for operation lock to be Done or context to timeout. The operation lock is normally completed by
// onStop which picks up the same lock and then marks it as Done after the instance stops and the devices
// have been cleaned up. However if the operation has failed for another reason we collect the error here.
err = op.Wait(ctx)
status := d.statusCode()
if status != api.Stopped {
errPrefix := fmt.Errorf("Failed shutting down instance, status is %q", status)
if err != nil {
return fmt.Errorf("%s: %w", errPrefix.Error(), err)
}
return errPrefix
}
// Now handle errors from shutdown sequence and return to caller if wasn't completed cleanly.
if err != nil {
return err
}
return nil
}
// Restart restart the instance.
func (d *qemu) Restart(timeout time.Duration) error {
return d.restartCommon(d, timeout)
}
// Rebuild rebuilds the instance using the supplied image fingerprint as source.
func (d *qemu) Rebuild(img *api.Image, op *operations.Operation) error {
return d.rebuildCommon(d, img, op)
}
func (*qemu) fwPath(filename string) string {
qemuFwPathsArr, err := util.GetQemuFwPaths()
if err != nil {
return ""
}
// GetQemuFwPaths resolves symlinks for us, but we still need EvalSymlinks() in here,
// because filename itself can be a symlink.
for _, path := range qemuFwPathsArr {
filePath := filepath.Join(path, filename)
filePath, err := filepath.EvalSymlinks(filePath)
if err != nil {
continue
}
if shared.PathExists(filePath) {
return filePath
}
}
return ""
}
// killQemuProcess kills specified process. Optimistically attempts to wait for the process to fully exit, but does
// not return an error if the Wait call fails. This is because this function is used in scenarios where LXD has
// been restarted after the VM has been started and is no longer the parent of the QEMU process.
// The caller should use another method to ensure that the QEMU process has fully exited instead.
// Returns an error if the Kill signal couldn't be sent to the process (for any other reason apart from the process
// not existing).
func (d *qemu) killQemuProcess(pid int) error {
proc, err := os.FindProcess(pid)
if err != nil {
if err == os.ErrProcessDone {
return nil
}
return err
}
err = proc.Kill()
if err != nil {
if err == os.ErrProcessDone {
return nil
}
return err
}
// Wait for process to exit, but don't return an error if this fails as it may be called when LXD isn't
// the parent of the process, and we have still sent the kill signal as per the function's description.
_, err = proc.Wait()
if err != nil {
if strings.Contains(err.Error(), "no child processes") {
return nil
}
d.logger.Warn("Failed to collect VM process exit status", logger.Ctx{"pid": pid, "err": err})
}
return nil
}
// restoreState restores the VM state from a file handle.
func (d *qemu) restoreStateHandle(ctx context.Context, monitor *qmp.Monitor, f *os.File) error {
err := monitor.SendFile("migration", f)
if err != nil {
return err
}
err = monitor.MigrateIncoming(ctx, "fd:migration")
if err != nil {
return err
}
return nil
}
// restoreState restores VM state from state file or from migration source if d.migrationReceiveStateful set.
func (d *qemu) restoreState(monitor *qmp.Monitor) error {
if d.migrationReceiveStateful != nil {
stateConn := d.migrationReceiveStateful[api.SecretNameState]
if stateConn == nil {
return fmt.Errorf("Migration state connection is not initialized")
}
// Perform non-shared storage transfer if requested.
filesystemConn := d.migrationReceiveStateful[api.SecretNameFilesystem]
if filesystemConn != nil {
nbdConn, err := monitor.NBDServerStart()
if err != nil {
return fmt.Errorf("Failed starting NBD server: %w", err)
}
d.logger.Debug("Migration NBD server started")
defer func() {
_ = nbdConn.Close()
_ = monitor.NBDServerStop()
}()
err = monitor.NBDBlockExportAdd(qemuMigrationNBDExportName)
if err != nil {
return fmt.Errorf("Failed adding root disk to NBD server: %w", err)
}
go func() {
d.logger.Debug("Migration storage NBD export starting")
go func() { _, _ = io.Copy(filesystemConn, nbdConn) }()
_, _ = io.Copy(nbdConn, filesystemConn)
_ = nbdConn.Close()
d.logger.Debug("Migration storage NBD export finished")
}()
defer func() { _ = filesystemConn.Close() }()
}
// Receive checkpoint from QEMU process on source.
d.logger.Debug("Stateful migration checkpoint receive starting")
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
go func() {
_, err := io.Copy(pipeWrite, stateConn)
if err != nil {
d.logger.Warn("Failed reading from state connection", logger.Ctx{"err": err})
}
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
err = d.restoreStateHandle(context.Background(), monitor, pipeRead)
if err != nil {
return fmt.Errorf("Failed restoring checkpoint from source: %w", err)
}
d.logger.Debug("Stateful migration checkpoint receive finished")
} else {
statePath := d.StatePath()
d.logger.Debug("Stateful checkpoint restore starting", logger.Ctx{"source": statePath})
defer d.logger.Debug("Stateful checkpoint restore finished", logger.Ctx{"source": statePath})
stateFile, err := os.Open(statePath)
if err != nil {
return fmt.Errorf("Failed opening state file %q: %w", statePath, err)
}
defer func() { _ = stateFile.Close() }()
uncompressedState, err := gzip.NewReader(stateFile)
if err != nil {
return fmt.Errorf("Failed opening state gzip reader: %w", err)
}
defer func() { _ = uncompressedState.Close() }()
pipeRead, pipeWrite, err := os.Pipe()
if err != nil {
return err
}
go func() {
_, err := io.Copy(pipeWrite, uncompressedState)
if err != nil {
d.logger.Warn("Failed reading from state file", logger.Ctx{"path": statePath, "err": err})
}
_ = pipeRead.Close()
_ = pipeWrite.Close()
}()
err = d.restoreStateHandle(context.Background(), monitor, pipeRead)
if err != nil {
return fmt.Errorf("Failed restoring state from %q: %w", stateFile.Name(), err)
}
}
return nil
}
// saveStateHandle dumps the current VM state to a file handle.
// Once started, the VM is in a paused state and it's up to the caller to wait for the transfer to complete and
// resume or kill the VM guest.
func (d *qemu) saveStateHandle(monitor *qmp.Monitor, f *os.File) error {
// Send the target file to qemu.
err := monitor.SendFile("migration", f)
if err != nil {
return err
}
// Issue the migration command.
err = monitor.Migrate("fd:migration")
if err != nil {
return err
}
return nil
}
// saveState dumps the current VM state to the state file.
// Once dumped, the VM is in a paused state and it's up to the caller to resume or kill it.
func (d *qemu) saveState(monitor *qmp.Monitor) error {
statePath := d.StatePath()
d.logger.Debug("Stateful checkpoint starting", logger.Ctx{"target": statePath})
defer d.logger.Debug("Stateful checkpoint finished", logger.Ctx{"target": statePath})
// Save the checkpoint to state file.