blob: d38df79a6fe6bd33d3c0dcc4a947457603dae90a [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02002// SPDX-License-Identifier: Apache-2.0
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02003
Serge Bazanski66e58952021-10-05 17:06:56 +02004// launch implements test harnesses for running qemu VMs from tests.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02005package launch
6
7import (
Lorenz Brun3ff5af32020-06-24 16:34:11 +02008 "bytes"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02009 "context"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020010 "errors"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020011 "fmt"
Lorenz Brun942f5e22022-01-27 15:03:10 +010012 "io"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020013 "net"
14 "os"
15 "os/exec"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020016 "strconv"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020017 "strings"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020018 "syscall"
Lorenz Bruned0503c2020-07-28 17:21:25 +020019
Lorenz Brun3ff5af32020-06-24 16:34:11 +020020 "golang.org/x/sys/unix"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020021
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020022 "source.monogon.dev/osbase/freeport"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020023)
24
Serge Bazanski66e58952021-10-05 17:06:56 +020025type QemuValue map[string][]string
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020026
Serge Bazanski66e58952021-10-05 17:06:56 +020027// ToOption encodes structured data into a QEMU option. Example: "test", {"key1":
Serge Bazanski216fe7b2021-05-21 18:36:16 +020028// {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Serge Bazanski66e58952021-10-05 17:06:56 +020029func (value QemuValue) ToOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020030 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020031 if name != "" {
32 optionValues = append(optionValues, name)
33 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020034 for name, values := range value {
35 if len(values) == 0 {
36 optionValues = append(optionValues, name)
37 }
38 for _, val := range values {
39 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
40 }
41 }
42 return strings.Join(optionValues, ",")
43}
44
Leopoldaf5086b2023-01-15 14:12:42 +010045// PrettyPrintQemuArgs prints the given QEMU arguments to stderr.
46func PrettyPrintQemuArgs(name string, args []string) {
47 var argsFmt string
48 for _, arg := range args {
49 argsFmt += arg
50 if !strings.HasPrefix(arg, "-") {
51 argsFmt += "\n "
52 } else {
53 argsFmt += " "
54 }
55 }
Serge Bazanski05f813b2023-03-16 17:58:39 +010056 Log("Running %s:\n %s\n", name, argsFmt)
Leopoldaf5086b2023-01-15 14:12:42 +010057}
58
Serge Bazanski216fe7b2021-05-21 18:36:16 +020059// PortMap represents where VM ports are mapped to on the host. It maps from the VM
60// port number to the host port number.
Serge Bazanskibe742842022-04-04 13:18:50 +020061type PortMap map[uint16]uint16
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020062
Serge Bazanski66e58952021-10-05 17:06:56 +020063// ToQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-
Serge Bazanski216fe7b2021-05-21 18:36:16 +020064// doc.html#:~:text=hostfwd=) for all mapped ports.
Serge Bazanski66e58952021-10-05 17:06:56 +020065func (p PortMap) ToQemuForwards() []string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020066 var hostfwdOptions []string
67 for vmPort, hostPort := range p {
Serge Bazanski52304a82021-10-29 16:56:18 +020068 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%d-:%d", hostPort, vmPort))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020069 }
70 return hostfwdOptions
71}
72
Serge Bazanski216fe7b2021-05-21 18:36:16 +020073// IdentityPortMap returns a port map where each given port is mapped onto itself
74// on the host. This is mainly useful for development against Metropolis. The dbg
75// command requires this mapping.
Serge Bazanskibe742842022-04-04 13:18:50 +020076func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020077 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020078 for _, port := range ports {
Tim Windelschmidt5e460a92024-04-11 01:33:09 +020079 portMap[port] = port
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020080 }
81 return portMap
82}
83
Serge Bazanski216fe7b2021-05-21 18:36:16 +020084// ConflictFreePortMap returns a port map where each given port is mapped onto a
85// random free port on the host. This is intended for automated testing where
86// multiple instances of Metropolis nodes might be running. Please call this
87// function for each Launch command separately and as close to it as possible since
88// it cannot guarantee that the ports will remain free.
Serge Bazanskibe742842022-04-04 13:18:50 +020089func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020090 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020091 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +020092 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020093 if err != nil {
94 return portMap, fmt.Errorf("failed to get free host port: %w", err)
95 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +020096 // Defer closing of the listening port until the function is done and all ports are
97 // allocated
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020098 defer listenCloser.Close()
99 portMap[port] = mappedPort
100 }
101 return portMap, nil
102}
103
Lorenz Brun150f24a2023-07-13 20:11:06 +0200104// GuestServiceMap maps an IP/port combination inside the virtual guest network
105// to a TCPAddr reachable by the host. If the guest connects to the virtual
106// address/port, this connection gets forwarded to the host.
107type GuestServiceMap map[*net.TCPAddr]net.TCPAddr
108
109// ToQemuForwards generates QEMU guestfwd values (https://qemu.weilnetz.de/doc/qemu-
110// doc.html#:~:text=guestfwd=) for all mapped addresses.
111func (p GuestServiceMap) ToQemuForwards() []string {
112 var guestfwdOptions []string
113 for guestAddr, hostAddr := range p {
114 guestfwdOptions = append(guestfwdOptions, fmt.Sprintf("tcp:%s-tcp:%s", guestAddr.String(), hostAddr.String()))
115 }
116 return guestfwdOptions
117}
118
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200119// NewSocketPair creates a new socket pair. By connecting both ends to different
120// instances you can connect them with a virtual "network cable". The ends can be
121// passed into the ConnectToSocket option.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200122func NewSocketPair() (*os.File, *os.File, error) {
123 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
124 if err != nil {
125 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
126 }
127
128 fd1 := os.NewFile(uintptr(fds[0]), "network0")
129 fd2 := os.NewFile(uintptr(fds[1]), "network1")
130 return fd1, fd2, nil
131}
132
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200133// HostInterfaceMAC is the MAC address the host SLIRP network interface has if it
134// is not disabled (see DisableHostNetworkInterface in MicroVMOptions)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200135var HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
136
137// MicroVMOptions contains all options to start a MicroVM
138type MicroVMOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +0100139 // Name is a human-readable identifier to be used in debug output.
140 Name string
141
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200142 // Path to the ELF kernel binary
143 KernelPath string
144
145 // Path to the Initramfs
146 InitramfsPath string
147
148 // Cmdline contains additional kernel commandline options
149 Cmdline string
150
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200151 // SerialPort is a File(descriptor) over which you can communicate with the serial
152 // port of the machine It can be set to an existing file descriptor (like
153 // os.Stdout/os.Stderr) or you can use NewSocketPair() to get one end to talk to
154 // from Go.
Lorenz Brun942f5e22022-01-27 15:03:10 +0100155 SerialPort io.Writer
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200156
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200157 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary
158 // number of additional serial ports
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200159 ExtraChardevs []*os.File
160
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200161 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which
162 // are mapped into the VM as virtio network interfaces. The first interface is
163 // always a SLIRP-backed interface for communicating with the host.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200164 ExtraNetworkInterfaces []*os.File
165
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200166 // PortMap contains ports that are mapped to the host through the built-in SLIRP
167 // network interface.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200168 PortMap PortMap
169
Lorenz Brun150f24a2023-07-13 20:11:06 +0200170 // GuestServiceMap contains TCP services made available in the guest virtual
171 // network which are running on the host.
172 GuestServiceMap GuestServiceMap
173
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200174 // DisableHostNetworkInterface disables the SLIRP-backed host network interface
175 // that is normally the first network interface. If this is set PortMap is ignored.
176 // Mostly useful for speeding up QEMU's startup time for tests.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200177 DisableHostNetworkInterface bool
Leopoldacfad5b2023-01-15 14:05:25 +0100178
179 // PcapDump can be used to dump all network traffic to a pcap file.
180 // If unset, no dump is created.
181 PcapDump string
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200182}
183
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200184// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot
185// (<40ms).
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200186func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200187 // Generate options for all the file descriptors we'll be passing as virtio "serial
188 // ports"
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200189 var extraArgs []string
Lorenz Brunce68ab92023-06-06 03:32:39 +0200190 for idx := range opts.ExtraChardevs {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200191 idxStr := strconv.Itoa(idx)
192 id := "extra" + idxStr
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200193 // That this works is pretty much a hack, but upstream QEMU doesn't have a
194 // bidirectional chardev backend not based around files/sockets on the disk which
195 // are a giant pain to work with. We're using QEMU's fdset functionality to make
196 // FDs available as pseudo-files and then "ab"using the pipe backend's fallback
197 // functionality to get a single bidirectional chardev backend backed by a passed-
198 // down RDWR fd. Ref https://lists.gnu.org/archive/html/qemu-devel/2015-
199 // 12/msg01256.html
Serge Bazanski66e58952021-10-05 17:06:56 +0200200 addFdConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200201 "set": {idxStr},
202 "fd": {strconv.Itoa(idx + 3)},
203 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200204 chardevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200205 "id": {id},
206 "path": {"/dev/fdset/" + idxStr},
207 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200208 deviceConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200209 "chardev": {id},
210 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200211 extraArgs = append(extraArgs, "-add-fd", addFdConf.ToOption(""),
212 "-chardev", chardevConf.ToOption("pipe"), "-device", deviceConf.ToOption("virtserialport"))
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200213 }
214
Lorenz Brunce68ab92023-06-06 03:32:39 +0200215 for idx := range opts.ExtraNetworkInterfaces {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200216 id := fmt.Sprintf("net%v", idx)
Serge Bazanski66e58952021-10-05 17:06:56 +0200217 netdevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200218 "id": {id},
219 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
220 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200221 extraArgs = append(extraArgs, "-netdev", netdevConf.ToOption("socket"), "-device", "virtio-net-device,netdev="+id)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200222 }
223
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200224 // This sets up a minimum viable environment for our Linux kernel. It clears all
225 // standard QEMU configuration and sets up a MicroVM machine
226 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy
227 // emulation turned off. This means the only "hardware" the Linux kernel inside can
228 // communicate with is a single virtio-mmio region. Over that MMIO interface we run
229 // a paravirtualized RNG (since the kernel in there has nothing to gather that from
230 // and it delays booting), a single paravirtualized console and an arbitrary number
231 // of extra serial ports for talking to various things that might run inside. The
232 // kernel, initramfs and command line are mapped into VM memory at boot time and
233 // not loaded from any sort of disk. Booting and shutting off one of these VMs
234 // takes <100ms.
Lorenz Brunce68ab92023-06-06 03:32:39 +0200235 baseArgs := []string{
236 "-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200237 "-accel", "kvm", "-cpu", "host",
Lorenz Brunce68ab92023-06-06 03:32:39 +0200238 "-m", "1G",
Tim Windelschmidt492434a2024-10-22 14:29:55 +0200239 // Needed because QEMU does not boot without specifying the qboot bios
240 // even tho the documentation clearly states that this is the default.
241 "-bios", "/usr/share/qemu/qboot.rom",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200242 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
243 "-kernel", opts.KernelPath,
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200244 // We force using a triple-fault reboot strategy since otherwise the kernel first
245 // tries others (like ACPI) which are not available in this very restricted
246 // environment. Similarly we need to override the boot console since there's
247 // nothing on the ISA bus that the kernel could talk to. We also force quiet for
248 // performance reasons.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200249 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
250 "-initrd", opts.InitramfsPath,
251 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
252 "-device", "virtio-serial-device,max_ports=16",
253 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
254 }
255
256 if !opts.DisableHostNetworkInterface {
257 qemuNetType := "user"
Serge Bazanski66e58952021-10-05 17:06:56 +0200258 qemuNetConfig := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200259 "id": {"usernet0"},
260 "net": {"10.42.0.0/24"},
261 "dhcpstart": {"10.42.0.10"},
262 }
263 if opts.PortMap != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200264 qemuNetConfig["hostfwd"] = opts.PortMap.ToQemuForwards()
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200265 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200266 if opts.GuestServiceMap != nil {
267 qemuNetConfig["guestfwd"] = opts.GuestServiceMap.ToQemuForwards()
268 }
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200269
Serge Bazanski66e58952021-10-05 17:06:56 +0200270 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.ToOption(qemuNetType),
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200271 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
272 }
273
Leopoldacfad5b2023-01-15 14:05:25 +0100274 if !opts.DisableHostNetworkInterface && opts.PcapDump != "" {
275 qemuNetDump := QemuValue{
276 "id": {"usernet0"},
277 "netdev": {"usernet0"},
278 "file": {opts.PcapDump},
279 }
280 extraArgs = append(extraArgs, "-object", qemuNetDump.ToOption("filter-dump"))
281 }
282
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200283 var stdErrBuf bytes.Buffer
Lorenz Brunb69a71c2024-12-23 14:12:46 +0100284 cmd := exec.CommandContext(ctx, "/usr/bin/qemu-system-x86_64", append(baseArgs, extraArgs...)...)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200285 cmd.Stdout = opts.SerialPort
286 cmd.Stderr = &stdErrBuf
287
288 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
289 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
290
Leopoldaf5086b2023-01-15 14:12:42 +0100291 PrettyPrintQemuArgs(opts.Name, cmd.Args)
292
Tim Windelschmidt492434a2024-10-22 14:29:55 +0200293 err := cmd.Run()
Serge Bazanski66e58952021-10-05 17:06:56 +0200294 // If it's a context error, just quit. There's no way to tell a
295 // killed-due-to-context vs killed-due-to-external-reason error returned by Run,
296 // so we approximate by looking at the context's status.
297 if err != nil && ctx.Err() != nil {
298 return ctx.Err()
299 }
300
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200301 var exerr *exec.ExitError
302 if err != nil && errors.As(err, &exerr) {
303 exerr.Stderr = stdErrBuf.Bytes()
304 newErr := QEMUError(*exerr)
305 return &newErr
306 }
307 return err
308}
309
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200310// QEMUError is a special type of ExitError used when QEMU fails. In addition to
311// normal ExitError features it prints stderr for debugging.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200312type QEMUError exec.ExitError
313
314func (e *QEMUError) Error() string {
315 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200316}