-
Notifications
You must be signed in to change notification settings - Fork 168
/
qemu.go
2071 lines (1880 loc) · 65.6 KB
/
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
// Copyright 2019 Red Hat
//
// 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.
// qemu.go is a Go interface to running `qemu` as a subprocess.
//
// Why not libvirt?
// Two main reasons. First, we really do want to use qemu, and not
// something else. We rely on qemu features/APIs and there's a general
// assumption that the qemu process is local (e.g. we expose 9p/virtiofs filesystem
// sharing). Second, libvirt runs as a daemon, but we want the
// VMs "lifecycle bound" to their creating process (e.g. kola),
// so that e.g. Ctrl-C (SIGINT) kills both reliably.
//
// Other related projects (as a reference to share ideas if not code)
// https://github.com/google/syzkaller/blob/3e84253bf41d63c55f92679b1aab9102f2f4949a/vm/qemu/qemu.go
// https://github.com/intel/govmm
package platform
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"math/rand"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/coreos/coreos-assembler/mantle/platform/conf"
"github.com/coreos/coreos-assembler/mantle/util"
coreosarch "github.com/coreos/stream-metadata-go/arch"
"github.com/digitalocean/go-qemu/qmp"
"github.com/coreos/coreos-assembler/mantle/system"
"github.com/coreos/coreos-assembler/mantle/system/exec"
"github.com/pkg/errors"
)
var (
// ErrInitramfsEmergency is the marker error returned upon node blocking in emergency mode in initramfs.
ErrInitramfsEmergency = errors.New("entered emergency.target in initramfs")
)
// HostForwardPort contains details about port-forwarding for the VM.
type HostForwardPort struct {
Service string
HostPort int
GuestPort int
}
// QemuMachineOptions is specialized MachineOption struct for QEMU.
type QemuMachineOptions struct {
MachineOptions
HostForwardPorts []HostForwardPort
DisablePDeathSig bool
OverrideBackingFile string
Firmware string
Nvme bool
Cex bool
}
// QEMUMachine represents a qemu instance.
type QEMUMachine interface {
// Embedding the Machine interface
Machine
// RemovePrimaryBlockDevice removes the primary device from a given qemu
// instance and sets the secondary device as primary.
RemovePrimaryBlockDevice() error
}
// Disk holds the details of a virtual disk.
type Disk struct {
Size string // disk image size in bytes, optional suffixes "K", "M", "G", "T" allowed.
BackingFile string // raw disk image to use.
BackingFormat string // qcow2, raw, etc. If unspecified will be autodetected.
Channel string // virtio (default), nvme, scsi
DeviceOpts []string // extra options to pass to qemu -device. "serial=XXXX" makes disks show up as /dev/disk/by-id/virtio-<serial>
DriveOpts []string // extra options to pass to -drive
SectorSize int // if not 0, override disk sector size
LogicalSectorSize int // if not 0, override disk sector size
NbdDisk bool // if true, the disks should be presented over nbd:unix socket
MultiPathDisk bool // if true, present multiple paths
Wwn uint64 // Optional World wide name for the SCSI disk. If not set or set to 0, a random one will be generated. Used only with "channel=scsi". Must be an integer
attachEndPoint string // qemuPath to attach to
dstFileName string // the prepared file
nbdServCmd exec.Cmd // command to serve the disk
}
func ParseDisk(spec string, allowNoSize bool) (*Disk, error) {
var channel string
sectorSize := 0
logicalSectorSize := 0
serialOpt := []string{}
multipathed := false
var wwn uint64
size, diskmap, err := util.ParseDiskSpec(spec, allowNoSize)
if err != nil {
return nil, fmt.Errorf("failed to parse disk spec %q: %w", spec, err)
}
for key, value := range diskmap {
switch key {
case "channel":
channel = value
case "4k":
sectorSize = 4096
case "512e":
sectorSize = 4096
logicalSectorSize = 512
case "mpath":
multipathed = true
case "serial":
value = "serial=" + value
serialOpt = append(serialOpt, value)
case "wwn":
wwn, err = strconv.ParseUint(value, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid value %s for wwn. Must be an integer", value)
}
default:
return nil, fmt.Errorf("invalid key %q", key)
}
}
sizeStr := ""
if size > 0 {
sizeStr = fmt.Sprintf("%dG", size)
}
return &Disk{
Size: sizeStr,
Channel: channel,
DeviceOpts: serialOpt,
SectorSize: sectorSize,
LogicalSectorSize: logicalSectorSize,
MultiPathDisk: multipathed,
Wwn: wwn,
}, nil
}
// bootIso is an internal struct used by AddIso() and setupIso()
type bootIso struct {
path string
bootindex string
}
// QemuInstance holds an instantiated VM through its lifecycle.
type QemuInstance struct {
qemu exec.Cmd
architecture string
tempdir string
swtpm exec.Cmd
// Helpers are child processes such as nbd or virtiofsd that should be lifecycle bound to qemu
helpers []exec.Cmd
hostForwardedPorts []HostForwardPort
journalPipe *os.File
qmpSocket *qmp.SocketMonitor
qmpSocketPath string
}
// Signaled returns whether QEMU process was signaled.
func (inst *QemuInstance) Signaled() bool {
return inst.qemu.Signaled()
}
// Pid returns the PID of QEMU process.
func (inst *QemuInstance) Pid() int {
return inst.qemu.Pid()
}
// Kill kills the VM instance.
func (inst *QemuInstance) Kill() error {
plog.Debugf("Killing qemu (%v)", inst.qemu.Pid())
return inst.qemu.Kill()
}
// SSHAddress returns the IP address with the forwarded port (host-side).
func (inst *QemuInstance) SSHAddress() (string, error) {
for _, fwdPorts := range inst.hostForwardedPorts {
if fwdPorts.Service == "ssh" {
return fmt.Sprintf("127.0.0.1:%d", fwdPorts.HostPort), nil
}
}
return "", fmt.Errorf("didn't find an address")
}
// Wait for the qemu process to exit
func (inst *QemuInstance) Wait() error {
return inst.qemu.Wait()
}
// WaitIgnitionError will only return if the instance
// failed inside the initramfs. The resulting string will
// be a newline-delimited stream of JSON strings, as returned
// by `journalctl -o json`.
func (inst *QemuInstance) WaitIgnitionError(ctx context.Context) (string, error) {
b := bufio.NewReaderSize(inst.journalPipe, 64768)
var r strings.Builder
iscorrupted := false
_, err := b.Peek(1)
if err != nil {
// It's normal to get EOF if we didn't catch an error and qemu
// is shutting down. We also need to handle when the Destroy()
// function closes the journal FD on us.
if e, ok := err.(*os.PathError); ok && e.Err == os.ErrClosed {
return "", nil
} else if err == io.EOF {
return "", nil
}
return "", errors.Wrapf(err, "Reading from journal")
}
for {
if err := ctx.Err(); err != nil {
return "", err
}
line, prefix, err := b.ReadLine()
if err != nil {
return r.String(), errors.Wrapf(err, "Reading from journal channel")
}
if prefix {
iscorrupted = true
}
if len(line) == 0 || string(line) == "{}" {
break
}
r.Write(line)
r.Write([]byte("\n"))
}
if iscorrupted {
return r.String(), fmt.Errorf("journal was truncated due to overly long line")
}
return r.String(), nil
}
// WaitAll wraps the process exit as well as WaitIgnitionError,
// returning an error if either fail.
func (inst *QemuInstance) WaitAll(ctx context.Context) error {
c := make(chan error)
waitCtx, cancel := context.WithCancel(ctx)
defer cancel()
// Early stop due to failure in initramfs.
go func() {
buf, err := inst.WaitIgnitionError(waitCtx)
if err != nil {
c <- err
return
}
// TODO: parse buf and try to nicely render something.
if buf != "" {
c <- ErrInitramfsEmergency
return
}
}()
// Machine terminated.
go func() {
select {
case <-waitCtx.Done():
c <- waitCtx.Err()
case c <- inst.Wait():
}
}()
return <-c
}
// Destroy kills the instance and associated sidecar processes.
func (inst *QemuInstance) Destroy() {
if inst.qmpSocket != nil {
inst.qmpSocket.Disconnect() //nolint // Ignore Errors
inst.qmpSocket = nil
os.Remove(inst.qmpSocketPath) //nolint // Ignore Errors
}
if inst.journalPipe != nil {
plog.Debugf("Sleep 1 to allow for more journal messages to get flushed")
time.Sleep(1 * time.Second)
inst.journalPipe.Close()
inst.journalPipe = nil
}
// kill is safe if already dead
if err := inst.Kill(); err != nil {
plog.Errorf("Error killing qemu instance %v: %v", inst.Pid(), err)
}
if inst.swtpm != nil {
inst.swtpm.Kill() //nolint // Ignore errors
inst.swtpm = nil
}
for _, p := range inst.helpers {
if p != nil {
p.Kill() //nolint // Ignore errors
}
}
inst.helpers = nil
if inst.tempdir != "" {
if err := os.RemoveAll(inst.tempdir); err != nil {
plog.Errorf("Error removing tempdir: %v", err)
}
}
}
// SwitchBootOrder tweaks the boot order for the instance.
// Currently effective on aarch64: switches the boot order to boot from disk on reboot. For s390x and aarch64, bootindex
// is used to boot from the network device (boot once is not supported). For s390x, the boot ordering was not a problem as it
// would always read from disk first. For aarch64, the bootindex needs to be switched to boot from disk before a reboot
func (inst *QemuInstance) SwitchBootOrder() (err2 error) {
switch inst.architecture {
case "s390x", "aarch64":
break
default:
//Not applicable for other arches
return nil
}
devs, err := inst.listDevices()
if err != nil {
return errors.Wrapf(err, "Could not list devices through qmp")
}
blkdevs, err := inst.listBlkDevices()
if err != nil {
return errors.Wrapf(err, "Could not list blk devices through qmp")
}
var bootdev, primarydev, secondarydev string
// Get boot device for PXE boots
for _, dev := range devs.Return {
switch dev.Type {
case "child<virtio-net-pci>", "child<virtio-net-ccw>":
bootdev = filepath.Join("/machine/peripheral-anon", dev.Name)
default:
break
}
}
// Get boot device for ISO boots and target block device
for _, dev := range blkdevs.Return {
devpath := filepath.Clean(strings.TrimSuffix(dev.DevicePath, "virtio-backend"))
switch dev.Device {
case "installiso":
bootdev = devpath
case "disk-1", "mpath10":
primarydev = devpath
case "mpath11":
secondarydev = devpath
case "":
if dev.Inserted.NodeName == "installiso" {
bootdev = devpath
}
default:
break
}
}
if bootdev == "" {
return fmt.Errorf("Could not find boot device using QMP.\n"+
"Full list of peripherals: %v.\n"+
"Full list of block devices: %v.\n",
devs.Return, blkdevs.Return)
}
if primarydev == "" {
return fmt.Errorf("Could not find target disk using QMP.\n"+
"Full list of block devices: %v.\n",
blkdevs.Return)
}
// unset bootindex for the boot device
if err := inst.setBootIndexForDevice(bootdev, -1); err != nil {
return errors.Wrapf(err, "Could not set bootindex for bootdev")
}
// set bootindex to 1 to boot from disk
if err := inst.setBootIndexForDevice(primarydev, 1); err != nil {
return errors.Wrapf(err, "Could not set bootindex for primarydev")
}
// set bootindex to 2 for secondary multipath disk
if secondarydev != "" {
if err := inst.setBootIndexForDevice(secondarydev, 2); err != nil {
return errors.Wrapf(err, "Could not set bootindex for secondarydev")
}
}
return nil
}
// RemovePrimaryBlockDevice deletes the primary device from a qemu instance
// and sets the secondary device as primary. It expects that all block devices
// with device name disk-<N> are mirrors.
func (inst *QemuInstance) RemovePrimaryBlockDevice() (err2 error) {
var primaryDevice string
var secondaryDevicePath string
blkdevs, err := inst.listBlkDevices()
if err != nil {
return errors.Wrapf(err, "Could not list block devices through qmp")
}
// This tries to identify the primary device by looking into
// a `BackingFileDepth` parameter of a device and check if
// it is a removable and part of `virtio-blk-pci` devices.
for _, dev := range blkdevs.Return {
if !dev.Removable && strings.HasPrefix(dev.Device, "disk-") {
if dev.Inserted.BackingFileDepth == 1 {
primaryDevice = dev.DevicePath
} else {
secondaryDevicePath = dev.DevicePath
}
}
}
if err := inst.setBootIndexForDevice(primaryDevice, -1); err != nil {
return errors.Wrapf(err, "Could not set bootindex for %v", primaryDevice)
}
primaryDevice = primaryDevice[:strings.LastIndex(primaryDevice, "/")]
if err := inst.deleteBlockDevice(primaryDevice); err != nil {
return errors.Wrapf(err, "Could not delete primary device %v", primaryDevice)
}
if len(secondaryDevicePath) == 0 {
return errors.Wrapf(err, "Could not find secondary device")
}
if err := inst.setBootIndexForDevice(secondaryDevicePath, 1); err != nil {
return errors.Wrapf(err, "Could not set bootindex for %v", secondaryDevicePath)
}
return nil
}
// A directory mounted from the host into the guest, via 9p or virtiofs
type HostMount struct {
src string
dest string
readonly bool
}
// QemuBuilder is a configurator that can then create a qemu instance
type QemuBuilder struct {
// ConfigFile is a path to Ignition configuration
ConfigFile string
// ForceConfigInjection is useful for booting `metal` images directly
ForceConfigInjection bool
configInjected bool
// File to which to redirect the serial console
ConsoleFile string
// If set, use QEMU full emulation for the target architecture
architecture string
// MemoryMiB defaults to 1024 on most architectures, others it may be 2048
MemoryMiB int
// Processors < 0 means to use host count, unset means 1, values > 1 are directly used
Processors int
UUID string
Firmware string
Swtpm bool
Pdeathsig bool
Argv []string
// AppendKernelArgs are appended to the bootloader config
AppendKernelArgs string
// AppendFirstbootKernelArgs are written to /boot/ignition
AppendFirstbootKernelArgs string
Hostname string
InheritConsole bool
iso *bootIso
isoAsDisk bool
primaryDisk *Disk
// primaryIsBoot is true if the only boot media should be the primary disk
primaryIsBoot bool
// tempdir holds our temporary files
tempdir string
// ignition is a config object that can be used instead of
// ConfigFile.
ignition *conf.Conf
ignitionSet bool
ignitionRendered bool
UsermodeNetworking bool
usermodeNetworkingAddr string
RestrictNetworking bool
requestedHostForwardPorts []HostForwardPort
additionalNics int
netbootP string
netbootDir string
finalized bool
diskID uint
disks []*Disk
// virtioSerialID is incremented for each device
virtioSerialID uint
// hostMounts is an array of directories mounted (via 9p or virtiofs) from the host
hostMounts []HostMount
// fds is file descriptors we own to pass to qemu
fds []*os.File
// IBM Secure Execution
secureExecution bool
ignitionPubKey string
}
// NewQemuBuilder creates a new build for QEMU with default settings.
func NewQemuBuilder() *QemuBuilder {
var defaultFirmware string
switch coreosarch.CurrentRpmArch() {
case "x86_64":
defaultFirmware = "bios"
case "aarch64":
defaultFirmware = "uefi"
default:
defaultFirmware = ""
}
ret := QemuBuilder{
Firmware: defaultFirmware,
Swtpm: true,
Pdeathsig: true,
Argv: []string{},
architecture: coreosarch.CurrentRpmArch(),
}
return &ret
}
func (builder *QemuBuilder) ensureTempdir() error {
if builder.tempdir != "" {
return nil
}
tempdir, err := os.MkdirTemp("/var/tmp", "mantle-qemu")
if err != nil {
return err
}
builder.tempdir = tempdir
return nil
}
// SetConfig injects Ignition; this can be used in place of ConfigFile.
func (builder *QemuBuilder) SetConfig(config *conf.Conf) {
if builder.ignitionRendered {
panic("SetConfig called after config rendered")
}
if builder.ignitionSet {
panic("SetConfig called multiple times")
}
builder.ignition = config
builder.ignitionSet = true
}
// Small wrapper around os.CreateTemp() to avoid leaking our tempdir to
// others.
func (builder *QemuBuilder) TempFile(pattern string) (*os.File, error) {
if err := builder.ensureTempdir(); err != nil {
return nil, err
}
return os.CreateTemp(builder.tempdir, pattern)
}
// renderIgnition lazily renders a parsed config if one is set
func (builder *QemuBuilder) renderIgnition() error {
if !builder.ignitionSet || builder.ignitionRendered {
return nil
}
if builder.ConfigFile != "" {
panic("Both ConfigFile and ignition set")
}
if err := builder.ensureTempdir(); err != nil {
return err
}
builder.ConfigFile = filepath.Join(builder.tempdir, "config.ign")
if err := builder.ignition.WriteFile(builder.ConfigFile); err != nil {
return err
}
builder.ignition = nil
builder.ignitionRendered = true
return nil
}
// AddFd appends a file descriptor that will be passed to qemu,
// returning a "/dev/fdset/<num>" argument that one can use with e.g.
// -drive file=/dev/fdset/<num>.
func (builder *QemuBuilder) AddFd(fd *os.File) string {
set := len(builder.fds) + 1
builder.fds = append(builder.fds, fd)
return fmt.Sprintf("/dev/fdset/%d", set)
}
// virtio returns a virtio device argument for qemu, which is architecture dependent
func virtio(arch, device, args string) string {
var suffix string
switch arch {
case "x86_64", "ppc64le", "aarch64":
suffix = "pci"
case "s390x":
suffix = "ccw"
default:
panic(fmt.Sprintf("RpmArch %s unhandled in virtio()", arch))
}
return fmt.Sprintf("virtio-%s-%s,%s", device, suffix, args)
}
// EnableUsermodeNetworking configure forwarding for all requested ports,
// via usermode network helpers.
func (builder *QemuBuilder) EnableUsermodeNetworking(h []HostForwardPort, usernetAddr string) {
builder.UsermodeNetworking = true
builder.requestedHostForwardPorts = h
builder.usermodeNetworkingAddr = usernetAddr
}
func (builder *QemuBuilder) SetNetbootP(filename, dir string) {
builder.UsermodeNetworking = true
builder.netbootP = filename
builder.netbootDir = dir
}
func (builder *QemuBuilder) AddAdditionalNics(additionalNics int) {
builder.additionalNics = additionalNics
}
func (builder *QemuBuilder) setupNetworking() error {
netdev := "user,id=eth0"
for i := range builder.requestedHostForwardPorts {
address := fmt.Sprintf(":%d", builder.requestedHostForwardPorts[i].HostPort)
// Possible race condition between getting the port here and using it
// with qemu -- trade off for simpler port management
l, err := net.Listen("tcp", address)
if err != nil {
return err
}
l.Close()
builder.requestedHostForwardPorts[i].HostPort = l.Addr().(*net.TCPAddr).Port
netdev += fmt.Sprintf(",hostfwd=tcp:127.0.0.1:%d-:%d",
builder.requestedHostForwardPorts[i].HostPort,
builder.requestedHostForwardPorts[i].GuestPort)
}
if builder.Hostname != "" {
netdev += fmt.Sprintf(",hostname=%s", builder.Hostname)
}
if builder.RestrictNetworking {
netdev += ",restrict=on"
}
if builder.usermodeNetworkingAddr != "" {
netdev += ",net=" + builder.usermodeNetworkingAddr
}
if builder.netbootP != "" {
// do an early stat so we fail with a nicer error now instead of in the VM
if _, err := os.Stat(filepath.Join(builder.netbootDir, builder.netbootP)); err != nil {
return err
}
tftpDir := ""
relpath := ""
if builder.netbootDir == "" {
absPath, err := filepath.Abs(builder.netbootP)
if err != nil {
return err
}
tftpDir = filepath.Dir(absPath)
relpath = filepath.Base(absPath)
} else {
absPath, err := filepath.Abs(builder.netbootDir)
if err != nil {
return err
}
tftpDir = absPath
relpath = builder.netbootP
}
netdev += fmt.Sprintf(",tftp=%s,bootfile=/%s", tftpDir, relpath)
builder.Append("-boot", "order=n")
}
builder.Append("-netdev", netdev, "-device", virtio(builder.architecture, "net", "netdev=eth0"))
return nil
}
func (builder *QemuBuilder) setupAdditionalNetworking() error {
macCounter := 0
netOffset := 30
for i := 1; i <= builder.additionalNics; i++ {
idSuffix := fmt.Sprintf("%d", i)
netSuffix := fmt.Sprintf("%d", netOffset+i)
macSuffix := fmt.Sprintf("%02x", macCounter)
netdev := fmt.Sprintf("user,id=eth%s,dhcpstart=10.0.2.%s", idSuffix, netSuffix)
device := virtio(builder.architecture, "net", fmt.Sprintf("netdev=eth%s,mac=52:55:00:d1:56:%s", idSuffix, macSuffix))
builder.Append("-netdev", netdev, "-device", device)
macCounter++
}
return nil
}
// SetArchitecture enables qemu full emulation for the target architecture.
func (builder *QemuBuilder) SetArchitecture(arch string) error {
switch arch {
case "x86_64", "aarch64", "s390x", "ppc64le":
builder.architecture = arch
return nil
}
return fmt.Errorf("architecture %s not supported by coreos-assembler qemu", arch)
}
// SetSecureExecution enables qemu confidential guest support and adds hostkey to ignition config.
func (builder *QemuBuilder) SetSecureExecution(gpgkey string, hostkey string, config *conf.Conf) error {
if supports, err := builder.supportsSecureExecution(); err != nil {
return err
} else if !supports {
return fmt.Errorf("Secure Execution was requested but isn't supported/enabled")
}
if gpgkey == "" {
return fmt.Errorf("Secure Execution was requested, but we don't have a GPG Public Key to encrypt the config")
}
if config != nil {
if hostkey == "" {
// dummy hostkey; this is good enough at least for the first boot (to prevent genprotimg from failing)
dummy, err := builder.TempFile("hostkey.*")
if err != nil {
return fmt.Errorf("creating hostkey: %v", err)
}
c := exec.Command("openssl", "req", "-x509", "-sha512", "-nodes", "-days", "1", "-subj", "/C=US/O=IBM/CN=secex",
"-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:secp521r1", "-out", dummy.Name())
if err := c.Run(); err != nil {
return fmt.Errorf("generating hostkey: %v", err)
}
hostkey = dummy.Name()
}
if contents, err := os.ReadFile(hostkey); err != nil {
return fmt.Errorf("reading hostkey: %v", err)
} else {
config.AddFile("/etc/se-hostkeys/ibm-z-hostkey-1", string(contents), 0644)
}
}
builder.secureExecution = true
builder.ignitionPubKey = gpgkey
builder.Append("-object", "s390-pv-guest,id=pv0", "-machine", "confidential-guest-support=pv0")
return nil
}
// When running kola secex tests with '--parallel=auto', this function fails with:
//
// kola: retryloop: failed to bring up machines: encrypting ignition_crypted.1234: exit status 2
//
// Use mutex to protect `gpg --encrypt`
var gpgMutex sync.Mutex
func (builder *QemuBuilder) encryptIgnitionConfig() error {
crypted, err := builder.TempFile("ignition_crypted.*")
if err != nil {
return fmt.Errorf("creating crypted config: %v", err)
}
gpgMutex.Lock()
defer gpgMutex.Unlock()
c := exec.Command("gpg", "--recipient-file", builder.ignitionPubKey, "--yes", "--output", crypted.Name(), "--armor", "--encrypt", builder.ConfigFile)
if err := c.Run(); err != nil {
return fmt.Errorf("encrypting %s: %v", crypted.Name(), err)
}
builder.ConfigFile = crypted.Name()
return nil
}
// MountHost sets up a mount point from the host to guest.
// Note that virtiofs does not currently support read-only mounts (which is really surprising!).
// We do mount it read-only by default in the guest, however.
func (builder *QemuBuilder) MountHost(source, dest string, readonly bool) {
builder.hostMounts = append(builder.hostMounts, HostMount{src: source, dest: dest, readonly: readonly})
}
// supportsFwCfg if the target system supports injecting
// Ignition via the qemu -fw_cfg option.
func (builder *QemuBuilder) supportsFwCfg() bool {
switch builder.architecture {
case "s390x", "ppc64le":
return false
}
return true
}
// supportsSecureExecution if s390x host (zKVM/LPAR) has "Secure Execution for Linux" feature enabled
func (builder *QemuBuilder) supportsSecureExecution() (bool, error) {
if builder.architecture != "s390x" {
return false, nil
}
content, err := os.ReadFile("/sys/firmware/uv/prot_virt_host")
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, fmt.Errorf("reading protvirt flag: %v", err)
}
if len(content) < 1 {
return false, nil
}
enabled := content[0] == '1'
return enabled, nil
}
// supportsSwtpm if the target system supports a virtual TPM device
func (builder *QemuBuilder) supportsSwtpm() bool {
switch builder.architecture {
case "s390x":
// s390x does not support a backend for TPM
return false
}
return true
}
// fileRemoteLocation is a bit misleading. We are NOT putting the ignition config in the root parition. We mount the boot partition on / just to get around the fact that
// the root partition does not need to be mounted to inject ignition config. Now that we have LUKS , we have to do more work to detect a LUKS root partition
// and it is not needed here.
const fileRemoteLocation = "/ignition/config.ign"
// findLabel finds the partition based on the label. The partition belongs to the image attached to the guestfish instance identified by pid.
func findLabel(label, pid string) (string, error) {
if pid == "" {
return "", fmt.Errorf("The pid cannot be empty")
}
if label == "" {
return "", fmt.Errorf("The label cannot be empty")
}
remote := fmt.Sprintf("--remote=%s", pid)
cmd := exec.Command("guestfish", remote, "findfs-label", label)
stdout, err := cmd.Output()
if err != nil {
return "", errors.Wrapf(err, "get stdout for findfs-label failed")
}
return strings.TrimSpace(string(stdout)), nil
}
type coreosGuestfish struct {
cmd *exec.ExecCmd
remote string
}
func newGuestfish(arch, diskImagePath string, diskSectorSize int) (*coreosGuestfish, error) {
// Set guestfish backend to direct in order to avoid libvirt as backend.
// Using libvirt can lead to permission denied issues if it does not have access
// rights to the qcow image
guestfishArgs := []string{"--listen"}
if diskSectorSize != 0 {
guestfishArgs = append(guestfishArgs, fmt.Sprintf("--blocksize=%d", diskSectorSize))
}
guestfishArgs = append(guestfishArgs, "-a", diskImagePath)
cmd := exec.Command("guestfish", guestfishArgs...)
cmd.Env = append(os.Environ(), "LIBGUESTFS_BACKEND=direct")
// make sure it inherits stderr so we see any error message
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Wrapf(err, "getting stdout pipe")
}
defer stdout.Close()
if err := cmd.Start(); err != nil {
return nil, errors.Wrapf(err, "running guestfish")
}
buf, err := io.ReadAll(stdout)
if err != nil {
return nil, errors.Wrapf(err, "reading guestfish output")
}
if err := cmd.Wait(); err != nil {
return nil, errors.Wrapf(err, "waiting for guestfish response")
}
//GUESTFISH_PID=$PID; export GUESTFISH_PID
gfVarPid := strings.Split(string(buf), ";")
if len(gfVarPid) != 2 {
return nil, fmt.Errorf("Failing parsing GUESTFISH_PID got: expecting length 2 got instead %d", len(gfVarPid))
}
gfVarPidArr := strings.Split(gfVarPid[0], "=")
if len(gfVarPidArr) != 2 {
return nil, fmt.Errorf("Failing parsing GUESTFISH_PID got: expecting length 2 got instead %d", len(gfVarPid))
}
pid := gfVarPidArr[1]
remote := fmt.Sprintf("--remote=%s", pid)
if err := exec.Command("guestfish", remote, "run").Run(); err != nil {
return nil, errors.Wrapf(err, "guestfish launch failed")
}
rootfs, err := findLabel("root", pid)
if err != nil {
return nil, errors.Wrapf(err, "guestfish command failed to find root label")
}
if err := exec.Command("guestfish", remote, "mount", rootfs, "/").Run(); err != nil {
return nil, errors.Wrapf(err, "guestfish root mount failed")
}
bootfs, err := findLabel("boot", pid)
if err != nil {
return nil, errors.Wrapf(err, "guestfish command failed to find boot label")
}
if err := exec.Command("guestfish", remote, "mount", bootfs, "/boot").Run(); err != nil {
return nil, errors.Wrapf(err, "guestfish boot mount failed")
}
return &coreosGuestfish{
cmd: cmd,
remote: remote,
}, nil
}
func (gf *coreosGuestfish) destroy() {
if err := exec.Command("guestfish", gf.remote, "exit").Run(); err != nil {
plog.Errorf("guestfish exit failed: %v", err)
}
}
// setupPreboot performs changes necessary before the disk is booted
func setupPreboot(arch, confPath, firstbootkargs, kargs string, diskImagePath string, diskSectorSize int) error {
gf, err := newGuestfish(arch, diskImagePath, diskSectorSize)
if err != nil {
return err
}
defer gf.destroy()
if confPath != "" {
if err := exec.Command("guestfish", gf.remote, "mkdir-p", "/boot/ignition").Run(); err != nil {
return errors.Wrapf(err, "guestfish directory creation failed")
}
if err := exec.Command("guestfish", gf.remote, "upload", confPath, "/boot"+fileRemoteLocation).Run(); err != nil {
return errors.Wrapf(err, "guestfish upload failed")
}
}
// See /boot/grub2/grub.cfg
if firstbootkargs != "" {
grubStr := fmt.Sprintf("set ignition_network_kcmdline=\"%s\"\n", firstbootkargs)
if err := exec.Command("guestfish", gf.remote, "write", "/boot/ignition.firstboot", grubStr).Run(); err != nil {
return errors.Wrapf(err, "guestfish write")
}
}
// Parsing BLS
var linux string
var initrd string
var allkargs string
zipl_sync := arch == "s390x" && (firstbootkargs != "" || kargs != "")
if kargs != "" || zipl_sync {
confpathout, err := exec.Command("guestfish", gf.remote, "glob-expand", "/boot/loader/entries/ostree*conf").Output()
if err != nil {
return errors.Wrapf(err, "finding bootloader config path")
}
confs := strings.Split(strings.TrimSpace(string(confpathout)), "\n")
if len(confs) != 1 {
return fmt.Errorf("Multiple values for bootloader config: %v", confpathout)
}
confpath := confs[0]
origconf, err := exec.Command("guestfish", gf.remote, "read-file", confpath).Output()
if err != nil {
return errors.Wrapf(err, "reading bootloader config")
}
var buf strings.Builder
for _, line := range strings.Split(string(origconf), "\n") {
if strings.HasPrefix(line, "options ") {
line += " " + kargs
allkargs = strings.TrimPrefix(line, "options ")
} else if strings.HasPrefix(line, "linux ") {
linux = "/boot" + strings.TrimPrefix(line, "linux ")
} else if strings.HasPrefix(line, "initrd ") {
initrd = "/boot" + strings.TrimPrefix(line, "initrd ")
}
buf.Write([]byte(line))
buf.Write([]byte("\n"))
}
if kargs != "" {
if err := exec.Command("guestfish", gf.remote, "write", confpath, buf.String()).Run(); err != nil {
return errors.Wrapf(err, "writing bootloader config")
}
}
}
// s390x requires zipl to update low-level data on block device
if zipl_sync {
allkargs = strings.TrimSpace(allkargs + " ignition.firstboot " + firstbootkargs)
if err := runZipl(gf, linux, initrd, allkargs); err != nil {