/
driver_qemu.go
4062 lines (3390 loc) · 104 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 (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/flosch/pongo2"
"github.com/gorilla/websocket"
"github.com/pborman/uuid"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
"gopkg.in/yaml.v2"
lxdClient "github.com/lxc/lxd/client"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/db/query"
"github.com/lxc/lxd/lxd/device"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/instance"
"github.com/lxc/lxd/lxd/instance/drivers/qmp"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/instance/operationlock"
"github.com/lxc/lxd/lxd/maas"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/resources"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
pongoTemplate "github.com/lxc/lxd/lxd/template"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/lxd/vsock"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/osarch"
"github.com/lxc/lxd/shared/termios"
"github.com/lxc/lxd/shared/units"
)
// qemuAsyncIO is used to indicate disk should use unsafe cache I/O.
const qemuUnsafeIO = "unsafeio"
var errQemuAgentOffline = fmt.Errorf("LXD VM agent isn't currently running")
var vmConsole = map[int]bool{}
var vmConsoleLock sync.Mutex
// qemuLoad creates a Qemu instance from the supplied InstanceArgs.
func qemuLoad(s *state.State, args db.InstanceArgs, profiles []api.Profile) (instance.Instance, error) {
// Create the instance struct.
vm := qemuInstantiate(s, args, nil)
// Expand config and devices.
err := vm.expandConfig(profiles)
if err != nil {
return nil, err
}
err = vm.expandDevices(profiles)
if err != nil {
return nil, err
}
return vm, 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) *qemu {
vm := &qemu{
common: common{
dbType: args.Type,
localConfig: args.Config,
localDevices: args.Devices,
project: args.Project,
state: s,
profiles: args.Profiles,
},
id: args.ID,
name: args.Name,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
snapshot: args.Snapshot,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
stateful: args.Stateful,
node: args.Node,
expiryDate: args.ExpiryDate,
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(vm.architecture)
if err == nil {
vm.architectureName = archName
}
// Cleanup the zero values.
if vm.expiryDate.IsZero() {
vm.expiryDate = time.Time{}
}
if vm.creationDate.IsZero() {
vm.creationDate = time.Time{}
}
if vm.lastUsedDate.IsZero() {
vm.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
vm.expandedDevices = expandedDevices
}
return vm
}
// qemuCreate creates a new storage volume record and returns an initialised Instance.
func qemuCreate(s *state.State, args db.InstanceArgs) (instance.Instance, error) {
// Create the instance struct.
vm := &qemu{
common: common{
dbType: args.Type,
localConfig: args.Config,
localDevices: args.Devices,
state: s,
profiles: args.Profiles,
project: args.Project,
},
id: args.ID,
name: args.Name,
node: args.Node,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
snapshot: args.Snapshot,
stateful: args.Stateful,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
expiryDate: args.ExpiryDate,
}
// Get the architecture name.
archName, err := osarch.ArchitectureName(vm.architecture)
if err == nil {
vm.architectureName = archName
}
// Cleanup the zero values.
if vm.expiryDate.IsZero() {
vm.expiryDate = time.Time{}
}
if vm.creationDate.IsZero() {
vm.creationDate = time.Time{}
}
if vm.lastUsedDate.IsZero() {
vm.lastUsedDate = time.Time{}
}
ctxMap := log.Ctx{
"project": args.Project,
"name": vm.name,
"ephemeral": vm.ephemeral,
}
logger.Info("Creating instance", ctxMap)
revert := true
defer func() {
if !revert {
return
}
vm.Delete()
}()
// Load the config.
err = vm.init()
if err != nil {
logger.Error("Failed creating instance", ctxMap)
return nil, err
}
// Validate expanded config.
err = instance.ValidConfig(s.OS, vm.expandedConfig, false, true)
if err != nil {
logger.Error("Failed creating instance", ctxMap)
return nil, err
}
err = instance.ValidDevices(s, s.Cluster, vm.Type(), vm.expandedDevices, true)
if err != nil {
logger.Error("Failed creating instance", ctxMap)
return nil, errors.Wrap(err, "Invalid devices")
}
// Retrieve the instance's storage pool.
_, rootDiskDevice, err := shared.GetRootDiskDevice(vm.expandedDevices.CloneNative())
if err != nil {
return nil, err
}
if rootDiskDevice["pool"] == "" {
return nil, fmt.Errorf("The instances's root device is missing the pool property")
}
storagePool := rootDiskDevice["pool"]
// Get the storage pool ID for the instance.
poolID, pool, err := s.Cluster.StoragePoolGet(storagePool)
if err != nil {
return nil, err
}
// Fill in any default volume config.
volumeConfig := map[string]string{}
err = storagePools.VolumeFillDefault(storagePool, volumeConfig, pool)
if err != nil {
return nil, err
}
// Create a new database entry for the instance's storage volume.
_, err = s.Cluster.StoragePoolVolumeCreate(args.Project, args.Name, "", db.StoragePoolVolumeTypeVM, vm.IsSnapshot(), poolID, volumeConfig)
if err != nil {
return nil, err
}
if !vm.IsSnapshot() {
// Update MAAS.
err = vm.maasUpdate(nil)
if err != nil {
logger.Error("Failed creating instance", ctxMap)
return nil, err
}
// Add devices to instance.
for k, m := range vm.expandedDevices {
err = vm.deviceAdd(k, m)
if err != nil && err != device.ErrUnsupportedDevType {
return nil, errors.Wrapf(err, "Failed to add device '%s'", k)
}
}
}
logger.Info("Created instance", ctxMap)
vm.state.Events.SendLifecycle(vm.project, "virtual-machine-created",
fmt.Sprintf("/1.0/virtual-machines/%s", vm.name), nil)
revert = false
return vm, nil
}
// qemu is the QEMU virtual machine driver.
type qemu struct {
common
// Properties.
architecture int
snapshot bool
creationDate time.Time
lastUsedDate time.Time
ephemeral bool
id int
name string
description string
stateful bool
// Clustering.
node string
// Progress tracking.
op *operations.Operation
expiryDate time.Time
// Cached handles.
// Do not use these variables directly, instead use their associated get functions so they
// will be initialised on demand.
agentClient *http.Client
storagePool storagePools.Pool
architectureName string
}
// getAgentClient returns the current agent client handle. To avoid TLS setup each time this
// function is called, the handle is cached internally in the Qemu struct.
func (vm *qemu) getAgentClient() (*http.Client, error) {
if vm.agentClient != nil {
return vm.agentClient, nil
}
// The connection uses mutual authentication, so use the LXD server's key & cert for client.
agentCert, _, clientCert, clientKey, err := vm.generateAgentCert()
if err != nil {
return nil, err
}
agent, err := vsock.HTTPClient(vm.vsockID(), clientCert, clientKey, agentCert)
if err != nil {
return nil, err
}
return agent, nil
}
// getStoragePool returns the current storage pool handle. To avoid a DB lookup each time this
// function is called, the handle is cached internally in the Qemu struct.
func (vm *qemu) getStoragePool() (storagePools.Pool, error) {
if vm.storagePool != nil {
return vm.storagePool, nil
}
pool, err := storagePools.GetPoolByInstance(vm.state, vm)
if err != nil {
return nil, err
}
vm.storagePool = pool
return vm.storagePool, nil
}
func (vm *qemu) getMonitorEventHandler() func(event string, data map[string]interface{}) {
id := vm.id
state := vm.state
return func(event string, data map[string]interface{}) {
if !shared.StringInSlice(event, []string{"SHUTDOWN"}) {
return
}
inst, err := instance.LoadByID(state, id)
if err != nil {
logger.Errorf("Failed to load instance with id=%d", id)
return
}
if event == "SHUTDOWN" {
target := "stop"
entry, ok := data["reason"]
if ok && entry == "guest-reset" {
target = "reboot"
}
err = inst.(*qemu).OnStop(target)
if err != nil {
logger.Errorf("Failed to cleanly stop instance '%s': %v", project.Instance(inst.Project(), inst.Name()), err)
return
}
}
}
}
// mount the instance's config volume if needed.
func (vm *qemu) mount() (bool, error) {
var pool storagePools.Pool
pool, err := vm.getStoragePool()
if err != nil {
return false, err
}
ourMount, err := pool.MountInstance(vm, nil)
if err != nil {
return false, err
}
return ourMount, nil
}
// unmount the instance's config volume if needed.
func (vm *qemu) unmount() (bool, error) {
pool, err := vm.getStoragePool()
if err != nil {
return false, err
}
unmounted, err := pool.UnmountInstance(vm, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
// generateAgentCert creates the necessary server key and certificate if needed.
func (vm *qemu) generateAgentCert() (string, string, string, string, error) {
// Mount the instance's config volume if needed.
ourMount, err := vm.mount()
if err != nil {
return "", "", "", "", err
}
if ourMount {
defer vm.unmount()
}
agentCertFile := filepath.Join(vm.Path(), "agent.crt")
agentKeyFile := filepath.Join(vm.Path(), "agent.key")
clientCertFile := filepath.Join(vm.Path(), "agent-client.crt")
clientKeyFile := filepath.Join(vm.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
agentCert, err := ioutil.ReadFile(agentCertFile)
if err != nil {
return "", "", "", "", err
}
agentKey, err := ioutil.ReadFile(agentKeyFile)
if err != nil {
return "", "", "", "", err
}
clientCert, err := ioutil.ReadFile(clientCertFile)
if err != nil {
return "", "", "", "", err
}
clientKey, err := ioutil.ReadFile(clientKeyFile)
if err != nil {
return "", "", "", "", err
}
return string(agentCert), string(agentKey), string(clientCert), string(clientKey), nil
}
// Freeze freezes the instance.
func (vm *qemu) Freeze() error {
// Connect to the monitor.
monitor, err := qmp.Connect(vm.getMonitorPath(), vm.getMonitorEventHandler())
if err != nil {
return err
}
// Send the stop command.
err = monitor.Pause()
if err != nil {
return err
}
return nil
}
// OnStop is run when the instance stops.
func (vm *qemu) OnStop(target string) error {
// Pick up the existing stop operation lock created in Stop() function.
op := operationlock.Get(vm.id)
if op != nil && op.Action() != "stop" {
return fmt.Errorf("Instance is already running a %s operation", op.Action())
}
// Cleanup.
vm.cleanupDevices()
os.Remove(vm.pidFilePath())
os.Remove(vm.getMonitorPath())
vm.unmount()
// Record power state.
err := vm.state.Cluster.ContainerSetState(vm.id, "STOPPED")
if err != nil {
op.Done(err)
return err
}
if target == "reboot" {
err := vm.Start(false)
if err != nil {
return err
}
}
if op != nil {
op.Done(nil)
}
return nil
}
// Shutdown shuts the instance down.
func (vm *qemu) Shutdown(timeout time.Duration) error {
if !vm.IsRunning() {
return fmt.Errorf("The instance is already stopped")
}
// Setup a new operation
op, err := operationlock.Create(vm.id, "stop", true, true)
if err != nil {
return err
}
// Connect to the monitor.
monitor, err := qmp.Connect(vm.getMonitorPath(), vm.getMonitorEventHandler())
if err != nil {
op.Done(err)
return err
}
// Get the wait channel.
chDisconnect, err := monitor.Wait()
if err != nil {
if err == qmp.ErrMonitorDisconnect {
op.Done(nil)
return nil
}
op.Done(err)
return err
}
// 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
}
// If timeout provided, block until the VM is not running or the timeout has elapsed.
if timeout > 0 {
select {
case <-chDisconnect:
op.Done(nil)
vm.state.Events.SendLifecycle(vm.project, "instance-shutdown", fmt.Sprintf("/1.0/virtual-machines/%s", vm.name), nil)
return nil
case <-time.After(timeout):
op.Done(fmt.Errorf("Instance was not shutdown after timeout"))
return fmt.Errorf("Instance was not shutdown after timeout")
}
} else {
<-chDisconnect // Block until VM is not running if no timeout provided.
}
op.Done(nil)
vm.state.Events.SendLifecycle(vm.project, "instance-shutdown", fmt.Sprintf("/1.0/virtual-machines/%s", vm.name), nil)
return nil
}
func (vm *qemu) ovmfPath() string {
if os.Getenv("LXD_OVMF_PATH") != "" {
return os.Getenv("LXD_OVMF_PATH")
}
return "/usr/share/OVMF"
}
// Start starts the instance.
func (vm *qemu) Start(stateful bool) error {
// Ensure the correct vhost_vsock kernel module is loaded before establishing the vsock.
err := util.LoadModule("vhost_vsock")
if err != nil {
return err
}
if vm.IsRunning() {
return fmt.Errorf("The instance is already running")
}
// Setup a new operation
op, err := operationlock.Create(vm.id, "start", false, false)
if err != nil {
return errors.Wrap(err, "Create instance start operation")
}
defer op.Done(nil)
revert := revert.New()
defer revert.Fail()
// Mount the instance's config volume.
_, err = vm.mount()
if err != nil {
op.Done(err)
return err
}
revert.Add(func() { vm.unmount() })
err = vm.generateConfigShare()
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(vm.LogPath(), 0700)
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(vm.DevicesPath(), 0711)
if err != nil {
op.Done(err)
return err
}
err = os.MkdirAll(vm.ShmountsPath(), 0711)
if err != nil {
op.Done(err)
return err
}
// Get a UUID for Qemu.
vmUUID := vm.localConfig["volatile.vm.uuid"]
if vmUUID == "" {
vmUUID = uuid.New()
vm.VolatileSet(map[string]string{"volatile.vm.uuid": vmUUID})
}
// Copy OVMF settings firmware to nvram file.
// This firmware file can be modified by the VM so it must be copied from the defaults.
if !shared.PathExists(vm.getNvramPath()) {
err = vm.setupNvram()
if err != nil {
op.Done(err)
return err
}
}
devConfs := make([]*deviceConfig.RunConfig, 0, len(vm.expandedDevices))
// Setup devices in sorted order, this ensures that device mounts are added in path order.
for _, dev := range vm.expandedDevices.Sorted() {
// Start the device.
runConf, err := vm.deviceStart(dev.Name, dev.Config, false)
if err != nil {
op.Done(err)
return errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
if runConf == nil {
continue
}
// Use a local function argument to ensure the current device is added to the reverter.
func(localDev deviceConfig.DeviceNamed) {
revert.Add(func() {
err := vm.deviceStop(localDev.Name, localDev.Config)
if err != nil {
logger.Errorf("Failed to cleanup device %q: %v", localDev.Name, err)
}
})
}(dev)
devConfs = append(devConfs, runConf)
}
// Get qemu configuration.
qemuBinary, err := vm.qemuArchConfig()
if err != nil {
op.Done(err)
return err
}
// Define a set of files to open and pass their file descriptors to qemu command.
fdFiles := make([]string, 0)
confFile, err := vm.generateQemuConfigFile(devConfs, &fdFiles)
if err != nil {
op.Done(err)
return err
}
// Check qemu is installed.
qemuPath, err := exec.LookPath(qemuBinary)
if err != nil {
op.Done(err)
return err
}
qemuCmd := []string{
"--",
qemuPath,
"-S",
"-name", vm.Name(),
"-uuid", vmUUID,
"-daemonize",
"-cpu", "host",
"-nographic",
"-serial", "chardev:console",
"-nodefaults",
"-no-reboot",
"-no-user-config",
"-sandbox", "on,obsolete=deny,elevateprivileges=allow,spawn=deny,resourcecontrol=deny",
"-readconfig", confFile,
"-pidfile", vm.pidFilePath(),
"-D", vm.LogFilePath(),
"-chroot", vm.Path(),
}
// Attempt to drop privileges.
if vm.state.OS.UnprivUser != "" {
qemuCmd = append(qemuCmd, "-runas", vm.state.OS.UnprivUser)
// Change ownership of config directory files so they are accessible to the
// unprivileged qemu process so that the 9p share can work.
//
// Security note: The 9P share will present the UID owner of these files on the host
// to the VM. In order to ensure that non-root users in the VM cannot access these
// files be sure to mount the 9P share in the VM with the "access=0" option to allow
// only root user in VM to access the mounted share.
err := filepath.Walk(filepath.Join(vm.Path(), "config"),
func(path string, info os.FileInfo, err error) error {
if err != nil {
op.Done(err)
return err
}
err = os.Chown(path, vm.state.OS.UnprivUID, -1)
if err != nil {
op.Done(err)
return err
}
return nil
})
if err != nil {
op.Done(err)
return err
}
}
if shared.IsTrue(vm.expandedConfig["limits.memory.hugepages"]) {
qemuCmd = append(qemuCmd, "-mem-path", "/dev/hugepages/", "-mem-prealloc")
}
if vm.expandedConfig["raw.qemu"] != "" {
fields := strings.Split(vm.expandedConfig["raw.qemu"], " ")
qemuCmd = append(qemuCmd, fields...)
}
// Run the qemu command via forklimits so we can selectively increase ulimits.
forkLimitsCmd := []string{
"forklimits",
"limit=memlock:unlimited:unlimited", // Required for PCI passthrough.
}
for i := range fdFiles {
// Pass through any file descriptors as 3+i (as first 3 file descriptors are taken as standard).
forkLimitsCmd = append(forkLimitsCmd, fmt.Sprintf("fd=%d", 3+i))
}
cmd := exec.Command(vm.state.OS.ExecPath, append(forkLimitsCmd, qemuCmd...)...)
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// Open any extra files and pass their file handles to qemu command.
for _, file := range fdFiles {
info, err := os.Stat(file)
if err != nil {
err = errors.Wrapf(err, "Error detecting file type %q", file)
op.Done(err)
return err
}
var f *os.File
mode := info.Mode()
if mode&os.ModeSocket != 0 {
c, err := vm.openUnixSocket(file)
if err != nil {
err = errors.Wrapf(err, "Error opening socket file %q", file)
op.Done(err)
return err
}
f, err = c.File()
if err != nil {
err = errors.Wrapf(err, "Error getting socket file descriptor %q", file)
op.Done(err)
return err
}
defer c.Close()
defer f.Close() // Close file after qemu has started.
} else {
f, err = os.OpenFile(file, os.O_RDWR, 0)
if err != nil {
err = errors.Wrapf(err, "Error opening exta file %q", file)
op.Done(err)
return err
}
defer f.Close() // Close file after qemu has started.
}
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
}
err = cmd.Run()
if err != nil {
err = errors.Wrapf(err, "Failed to run: %s: %s", strings.Join(cmd.Args, " "), strings.TrimSpace(string(stderr.Bytes())))
op.Done(err)
return err
}
pid, err := vm.pid()
if err != nil {
logger.Errorf(`Failed to get VM process ID "%d"`, pid)
return err
}
revert.Add(func() {
proc, err := os.FindProcess(pid)
if err != nil {
logger.Errorf(`Failed to find VM process "%d"`, pid)
return
}
proc.Kill()
if err != nil {
logger.Errorf(`Failed to kill VM process "%d"`, pid)
}
})
// Start QMP monitoring.
monitor, err := qmp.Connect(vm.getMonitorPath(), vm.getMonitorEventHandler())
if err != nil {
op.Done(err)
return err
}
// Apply CPU pinning.
cpuLimit, ok := vm.expandedConfig["limits.cpu"]
if ok && cpuLimit != "" {
_, err := strconv.Atoi(cpuLimit)
if err != nil {
// Expand to a set of CPU identifiers and get the pinning map.
_, _, _, pins, err := vm.cpuTopology(cpuLimit)
if err != nil {
op.Done(err)
return err
}
// Get the list of PIDs from the VM.
pids, err := monitor.GetCPUs()
if err != nil {
op.Done(err)
return err
}
// Confirm nothing weird is going on.
if len(pins) != len(pids) {
return fmt.Errorf("QEMU has less vCPUs than configured")
}
for i, pid := range pids {
set := unix.CPUSet{}
set.Set(int(pins[uint64(i)]))
// Apply the pin.
err := unix.SchedSetaffinity(pid, &set)
if err != nil {
op.Done(err)
return err
}
}
}
}
// Start the VM.
err = monitor.Start()
if err != nil {
op.Done(err)
return err
}
// Database updates
err = vm.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
// Record current state
err = tx.ContainerSetState(vm.id, "RUNNING")
if err != nil {
err = errors.Wrap(err, "Error updating instance state")
op.Done(err)
return err
}
// Update time instance last started time
err = tx.ContainerLastUsedUpdate(vm.id, time.Now().UTC())
if err != nil {
err = errors.Wrap(err, "Error updating instance last used")
op.Done(err)
return err
}
return nil
})
if err != nil {
op.Done(err)
return err
}
revert.Success()
vm.state.Events.SendLifecycle(vm.project, "virtual-machine-started", fmt.Sprintf("/1.0/virtual-machines/%s", vm.name), nil)
return nil
}
// openUnixSocket connects to a UNIX socket and returns the connection.
func (vm *qemu) openUnixSocket(sockPath string) (*net.UnixConn, error) {
addr, err := net.ResolveUnixAddr("unix", sockPath)
if err != nil {
return nil, err
}
c, err := net.DialUnix("unix", nil, addr)
if err != nil {
return nil, err
}
return c, nil
}
func (vm *qemu) setupNvram() error {
// No UEFI nvram for ppc64le.
if vm.architecture == osarch.ARCH_64BIT_POWERPC_LITTLE_ENDIAN {
return nil
}
// Mount the instance's config volume.
ourMount, err := vm.mount()
if err != nil {
return err
}
if ourMount {
defer vm.unmount()
}
srcOvmfFile := filepath.Join(vm.ovmfPath(), "OVMF_VARS.fd")
if vm.expandedConfig["security.secureboot"] == "" || shared.IsTrue(vm.expandedConfig["security.secureboot"]) {
srcOvmfFile = filepath.Join(vm.ovmfPath(), "OVMF_VARS.ms.fd")
}
if !shared.PathExists(srcOvmfFile) {
return fmt.Errorf("Required EFI firmware settings file missing: %s", srcOvmfFile)
}
os.Remove(vm.getNvramPath())
err = shared.FileCopy(srcOvmfFile, vm.getNvramPath())
if err != nil {
return err
}
return nil
}
func (vm *qemu) qemuArchConfig() (string, error) {
if vm.architecture == osarch.ARCH_64BIT_INTEL_X86 {
return "qemu-system-x86_64", nil
} else if vm.architecture == osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN {
return "qemu-system-aarch64", nil
} else if vm.architecture == osarch.ARCH_64BIT_POWERPC_LITTLE_ENDIAN {
return "qemu-system-ppc64", nil
}
return "", fmt.Errorf("Architecture isn't supported for virtual machines")
}
// deviceVolatileGetFunc returns a function that retrieves a named device's volatile config and
// removes its device prefix from the keys.
func (vm *qemu) deviceVolatileGetFunc(devName string) func() map[string]string {
return func() map[string]string {
volatile := make(map[string]string)
prefix := fmt.Sprintf("volatile.%s.", devName)
for k, v := range vm.localConfig {
if strings.HasPrefix(k, prefix) {