blob: 1b063def8f8849a30253631440a54fcd6c9d9de2 [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
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01004// Package qemu implements test harnesses for running qemu VMs from tests.
5package qemu
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02006
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
Tim Windelschmidtb03d9ff2025-04-02 15:04:03 +020025var (
26 // HostInterfaceMAC is the MAC address the host SLIRP network interface has if it
27 // is not disabled (see DisableHostNetworkInterface in MicroVMOptions)
28 HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
29)
30
Serge Bazanski66e58952021-10-05 17:06:56 +020031type QemuValue map[string][]string
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020032
Serge Bazanski66e58952021-10-05 17:06:56 +020033// ToOption encodes structured data into a QEMU option. Example: "test", {"key1":
Serge Bazanski216fe7b2021-05-21 18:36:16 +020034// {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Serge Bazanski66e58952021-10-05 17:06:56 +020035func (value QemuValue) ToOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020036 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020037 if name != "" {
38 optionValues = append(optionValues, name)
39 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020040 for name, values := range value {
41 if len(values) == 0 {
42 optionValues = append(optionValues, name)
43 }
44 for _, val := range values {
45 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
46 }
47 }
48 return strings.Join(optionValues, ",")
49}
50
Leopoldaf5086b2023-01-15 14:12:42 +010051// PrettyPrintQemuArgs prints the given QEMU arguments to stderr.
52func PrettyPrintQemuArgs(name string, args []string) {
53 var argsFmt string
54 for _, arg := range args {
55 argsFmt += arg
56 if !strings.HasPrefix(arg, "-") {
57 argsFmt += "\n "
58 } else {
59 argsFmt += " "
60 }
61 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010062 fmt.Fprintf(os.Stderr, "Running %s:\n %s\n", name, argsFmt)
Leopoldaf5086b2023-01-15 14:12:42 +010063}
64
Serge Bazanski216fe7b2021-05-21 18:36:16 +020065// PortMap represents where VM ports are mapped to on the host. It maps from the VM
66// port number to the host port number.
Serge Bazanskibe742842022-04-04 13:18:50 +020067type PortMap map[uint16]uint16
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020068
Serge Bazanski66e58952021-10-05 17:06:56 +020069// ToQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-
Serge Bazanski216fe7b2021-05-21 18:36:16 +020070// doc.html#:~:text=hostfwd=) for all mapped ports.
Serge Bazanski66e58952021-10-05 17:06:56 +020071func (p PortMap) ToQemuForwards() []string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020072 var hostfwdOptions []string
73 for vmPort, hostPort := range p {
Serge Bazanski52304a82021-10-29 16:56:18 +020074 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%d-:%d", hostPort, vmPort))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020075 }
76 return hostfwdOptions
77}
78
Serge Bazanski216fe7b2021-05-21 18:36:16 +020079// IdentityPortMap returns a port map where each given port is mapped onto itself
80// on the host. This is mainly useful for development against Metropolis. The dbg
81// command requires this mapping.
Serge Bazanskibe742842022-04-04 13:18:50 +020082func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020083 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020084 for _, port := range ports {
Tim Windelschmidt5e460a92024-04-11 01:33:09 +020085 portMap[port] = port
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020086 }
87 return portMap
88}
89
Serge Bazanski216fe7b2021-05-21 18:36:16 +020090// ConflictFreePortMap returns a port map where each given port is mapped onto a
91// random free port on the host. This is intended for automated testing where
92// multiple instances of Metropolis nodes might be running. Please call this
93// function for each Launch command separately and as close to it as possible since
94// it cannot guarantee that the ports will remain free.
Serge Bazanskibe742842022-04-04 13:18:50 +020095func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020096 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020097 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +020098 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020099 if err != nil {
100 return portMap, fmt.Errorf("failed to get free host port: %w", err)
101 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200102 // Defer closing of the listening port until the function is done and all ports are
103 // allocated
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200104 defer listenCloser.Close()
105 portMap[port] = mappedPort
106 }
107 return portMap, nil
108}
109
Lorenz Brun150f24a2023-07-13 20:11:06 +0200110// GuestServiceMap maps an IP/port combination inside the virtual guest network
111// to a TCPAddr reachable by the host. If the guest connects to the virtual
112// address/port, this connection gets forwarded to the host.
113type GuestServiceMap map[*net.TCPAddr]net.TCPAddr
114
115// ToQemuForwards generates QEMU guestfwd values (https://qemu.weilnetz.de/doc/qemu-
116// doc.html#:~:text=guestfwd=) for all mapped addresses.
117func (p GuestServiceMap) ToQemuForwards() []string {
118 var guestfwdOptions []string
119 for guestAddr, hostAddr := range p {
120 guestfwdOptions = append(guestfwdOptions, fmt.Sprintf("tcp:%s-tcp:%s", guestAddr.String(), hostAddr.String()))
121 }
122 return guestfwdOptions
123}
124
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200125// NewSocketPair creates a new socket pair. By connecting both ends to different
126// instances you can connect them with a virtual "network cable". The ends can be
127// passed into the ConnectToSocket option.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200128func NewSocketPair() (*os.File, *os.File, error) {
129 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
130 if err != nil {
131 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
132 }
133
134 fd1 := os.NewFile(uintptr(fds[0]), "network0")
135 fd2 := os.NewFile(uintptr(fds[1]), "network1")
136 return fd1, fd2, nil
137}
138
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200139// MicroVMOptions contains all options to start a MicroVM
140type MicroVMOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +0100141 // Name is a human-readable identifier to be used in debug output.
142 Name string
143
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200144 // Path to the ELF kernel binary
145 KernelPath string
146
147 // Path to the Initramfs
148 InitramfsPath string
149
150 // Cmdline contains additional kernel commandline options
151 Cmdline string
152
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200153 // SerialPort is a File(descriptor) over which you can communicate with the serial
154 // port of the machine It can be set to an existing file descriptor (like
155 // os.Stdout/os.Stderr) or you can use NewSocketPair() to get one end to talk to
156 // from Go.
Lorenz Brun942f5e22022-01-27 15:03:10 +0100157 SerialPort io.Writer
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200158
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200159 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary
160 // number of additional serial ports
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200161 ExtraChardevs []*os.File
162
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200163 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which
164 // are mapped into the VM as virtio network interfaces. The first interface is
165 // always a SLIRP-backed interface for communicating with the host.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200166 ExtraNetworkInterfaces []*os.File
167
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200168 // PortMap contains ports that are mapped to the host through the built-in SLIRP
169 // network interface.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200170 PortMap PortMap
171
Lorenz Brun150f24a2023-07-13 20:11:06 +0200172 // GuestServiceMap contains TCP services made available in the guest virtual
173 // network which are running on the host.
174 GuestServiceMap GuestServiceMap
175
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200176 // DisableHostNetworkInterface disables the SLIRP-backed host network interface
177 // that is normally the first network interface. If this is set PortMap is ignored.
178 // Mostly useful for speeding up QEMU's startup time for tests.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200179 DisableHostNetworkInterface bool
Leopoldacfad5b2023-01-15 14:05:25 +0100180
181 // PcapDump can be used to dump all network traffic to a pcap file.
182 // If unset, no dump is created.
183 PcapDump string
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200184}
185
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200186// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot
187// (<40ms).
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200188func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200189 // Generate options for all the file descriptors we'll be passing as virtio "serial
190 // ports"
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200191 var extraArgs []string
Lorenz Brunce68ab92023-06-06 03:32:39 +0200192 for idx := range opts.ExtraChardevs {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200193 idxStr := strconv.Itoa(idx)
194 id := "extra" + idxStr
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200195 // That this works is pretty much a hack, but upstream QEMU doesn't have a
196 // bidirectional chardev backend not based around files/sockets on the disk which
197 // are a giant pain to work with. We're using QEMU's fdset functionality to make
198 // FDs available as pseudo-files and then "ab"using the pipe backend's fallback
199 // functionality to get a single bidirectional chardev backend backed by a passed-
200 // down RDWR fd. Ref https://lists.gnu.org/archive/html/qemu-devel/2015-
201 // 12/msg01256.html
Serge Bazanski66e58952021-10-05 17:06:56 +0200202 addFdConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200203 "set": {idxStr},
204 "fd": {strconv.Itoa(idx + 3)},
205 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200206 chardevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200207 "id": {id},
208 "path": {"/dev/fdset/" + idxStr},
209 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200210 deviceConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200211 "chardev": {id},
212 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200213 extraArgs = append(extraArgs, "-add-fd", addFdConf.ToOption(""),
214 "-chardev", chardevConf.ToOption("pipe"), "-device", deviceConf.ToOption("virtserialport"))
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200215 }
216
Lorenz Brunce68ab92023-06-06 03:32:39 +0200217 for idx := range opts.ExtraNetworkInterfaces {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200218 id := fmt.Sprintf("net%v", idx)
Serge Bazanski66e58952021-10-05 17:06:56 +0200219 netdevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200220 "id": {id},
221 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
222 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200223 extraArgs = append(extraArgs, "-netdev", netdevConf.ToOption("socket"), "-device", "virtio-net-device,netdev="+id)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200224 }
225
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200226 // This sets up a minimum viable environment for our Linux kernel. It clears all
227 // standard QEMU configuration and sets up a MicroVM machine
228 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy
229 // emulation turned off. This means the only "hardware" the Linux kernel inside can
230 // communicate with is a single virtio-mmio region. Over that MMIO interface we run
231 // a paravirtualized RNG (since the kernel in there has nothing to gather that from
232 // and it delays booting), a single paravirtualized console and an arbitrary number
233 // of extra serial ports for talking to various things that might run inside. The
234 // kernel, initramfs and command line are mapped into VM memory at boot time and
235 // not loaded from any sort of disk. Booting and shutting off one of these VMs
236 // takes <100ms.
Lorenz Brunce68ab92023-06-06 03:32:39 +0200237 baseArgs := []string{
238 "-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200239 "-accel", "kvm", "-cpu", "host",
Lorenz Brunce68ab92023-06-06 03:32:39 +0200240 "-m", "1G",
Tim Windelschmidt492434a2024-10-22 14:29:55 +0200241 // Needed because QEMU does not boot without specifying the qboot bios
242 // even tho the documentation clearly states that this is the default.
243 "-bios", "/usr/share/qemu/qboot.rom",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200244 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
245 "-kernel", opts.KernelPath,
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200246 // We force using a triple-fault reboot strategy since otherwise the kernel first
247 // tries others (like ACPI) which are not available in this very restricted
248 // environment. Similarly we need to override the boot console since there's
249 // nothing on the ISA bus that the kernel could talk to. We also force quiet for
250 // performance reasons.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200251 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
252 "-initrd", opts.InitramfsPath,
253 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
254 "-device", "virtio-serial-device,max_ports=16",
255 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
256 }
257
258 if !opts.DisableHostNetworkInterface {
259 qemuNetType := "user"
Serge Bazanski66e58952021-10-05 17:06:56 +0200260 qemuNetConfig := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200261 "id": {"usernet0"},
262 "net": {"10.42.0.0/24"},
263 "dhcpstart": {"10.42.0.10"},
264 }
265 if opts.PortMap != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200266 qemuNetConfig["hostfwd"] = opts.PortMap.ToQemuForwards()
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200267 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200268 if opts.GuestServiceMap != nil {
269 qemuNetConfig["guestfwd"] = opts.GuestServiceMap.ToQemuForwards()
270 }
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200271
Serge Bazanski66e58952021-10-05 17:06:56 +0200272 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.ToOption(qemuNetType),
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200273 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
274 }
275
Leopoldacfad5b2023-01-15 14:05:25 +0100276 if !opts.DisableHostNetworkInterface && opts.PcapDump != "" {
277 qemuNetDump := QemuValue{
278 "id": {"usernet0"},
279 "netdev": {"usernet0"},
280 "file": {opts.PcapDump},
281 }
282 extraArgs = append(extraArgs, "-object", qemuNetDump.ToOption("filter-dump"))
283 }
284
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200285 var stdErrBuf bytes.Buffer
Lorenz Brunb69a71c2024-12-23 14:12:46 +0100286 cmd := exec.CommandContext(ctx, "/usr/bin/qemu-system-x86_64", append(baseArgs, extraArgs...)...)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200287 cmd.Stdout = opts.SerialPort
288 cmd.Stderr = &stdErrBuf
289
290 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
291 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
292
Leopoldaf5086b2023-01-15 14:12:42 +0100293 PrettyPrintQemuArgs(opts.Name, cmd.Args)
294
Tim Windelschmidt492434a2024-10-22 14:29:55 +0200295 err := cmd.Run()
Serge Bazanski66e58952021-10-05 17:06:56 +0200296 // If it's a context error, just quit. There's no way to tell a
297 // killed-due-to-context vs killed-due-to-external-reason error returned by Run,
298 // so we approximate by looking at the context's status.
299 if err != nil && ctx.Err() != nil {
300 return ctx.Err()
301 }
302
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200303 var exerr *exec.ExitError
304 if err != nil && errors.As(err, &exerr) {
305 exerr.Stderr = stdErrBuf.Bytes()
306 newErr := QEMUError(*exerr)
307 return &newErr
308 }
309 return err
310}
311
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200312// QEMUError is a special type of ExitError used when QEMU fails. In addition to
313// normal ExitError features it prints stderr for debugging.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200314type QEMUError exec.ExitError
315
316func (e *QEMUError) Error() string {
317 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200318}