blob: 9760f549bff41f3660e0405f9efa7da35371e9ac [file] [log] [blame]
Lorenz Brunfc5dbc62020-05-28 12:18:07 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
Serge Bazanski66e58952021-10-05 17:06:56 +020017// launch implements test harnesses for running qemu VMs from tests.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020018package launch
19
20import (
Lorenz Brun3ff5af32020-06-24 16:34:11 +020021 "bytes"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020022 "context"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020023 "errors"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020024 "fmt"
Lorenz Brun942f5e22022-01-27 15:03:10 +010025 "io"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020026 "net"
27 "os"
28 "os/exec"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020029 "strconv"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020030 "strings"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020031 "syscall"
Lorenz Bruned0503c2020-07-28 17:21:25 +020032
Lorenz Brun3ff5af32020-06-24 16:34:11 +020033 "golang.org/x/sys/unix"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020034
Serge Bazanski31370b02021-01-07 16:31:14 +010035 "source.monogon.dev/metropolis/pkg/freeport"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020036)
37
Serge Bazanski66e58952021-10-05 17:06:56 +020038type QemuValue map[string][]string
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020039
Serge Bazanski66e58952021-10-05 17:06:56 +020040// ToOption encodes structured data into a QEMU option. Example: "test", {"key1":
Serge Bazanski216fe7b2021-05-21 18:36:16 +020041// {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Serge Bazanski66e58952021-10-05 17:06:56 +020042func (value QemuValue) ToOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020043 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020044 if name != "" {
45 optionValues = append(optionValues, name)
46 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020047 for name, values := range value {
48 if len(values) == 0 {
49 optionValues = append(optionValues, name)
50 }
51 for _, val := range values {
52 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
53 }
54 }
55 return strings.Join(optionValues, ",")
56}
57
Leopoldaf5086b2023-01-15 14:12:42 +010058// PrettyPrintQemuArgs prints the given QEMU arguments to stderr.
59func PrettyPrintQemuArgs(name string, args []string) {
60 var argsFmt string
61 for _, arg := range args {
62 argsFmt += arg
63 if !strings.HasPrefix(arg, "-") {
64 argsFmt += "\n "
65 } else {
66 argsFmt += " "
67 }
68 }
Serge Bazanski05f813b2023-03-16 17:58:39 +010069 Log("Running %s:\n %s\n", name, argsFmt)
Leopoldaf5086b2023-01-15 14:12:42 +010070}
71
Serge Bazanski216fe7b2021-05-21 18:36:16 +020072// PortMap represents where VM ports are mapped to on the host. It maps from the VM
73// port number to the host port number.
Serge Bazanskibe742842022-04-04 13:18:50 +020074type PortMap map[uint16]uint16
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020075
Serge Bazanski66e58952021-10-05 17:06:56 +020076// ToQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-
Serge Bazanski216fe7b2021-05-21 18:36:16 +020077// doc.html#:~:text=hostfwd=) for all mapped ports.
Serge Bazanski66e58952021-10-05 17:06:56 +020078func (p PortMap) ToQemuForwards() []string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020079 var hostfwdOptions []string
80 for vmPort, hostPort := range p {
Serge Bazanski52304a82021-10-29 16:56:18 +020081 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%d-:%d", hostPort, vmPort))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020082 }
83 return hostfwdOptions
84}
85
Serge Bazanski216fe7b2021-05-21 18:36:16 +020086// IdentityPortMap returns a port map where each given port is mapped onto itself
87// on the host. This is mainly useful for development against Metropolis. The dbg
88// command requires this mapping.
Serge Bazanskibe742842022-04-04 13:18:50 +020089func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020090 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020091 for _, port := range ports {
Serge Bazanski52304a82021-10-29 16:56:18 +020092 portMap[port] = uint16(port)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020093 }
94 return portMap
95}
96
Serge Bazanski216fe7b2021-05-21 18:36:16 +020097// ConflictFreePortMap returns a port map where each given port is mapped onto a
98// random free port on the host. This is intended for automated testing where
99// multiple instances of Metropolis nodes might be running. Please call this
100// function for each Launch command separately and as close to it as possible since
101// it cannot guarantee that the ports will remain free.
Serge Bazanskibe742842022-04-04 13:18:50 +0200102func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200103 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200104 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200105 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200106 if err != nil {
107 return portMap, fmt.Errorf("failed to get free host port: %w", err)
108 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200109 // Defer closing of the listening port until the function is done and all ports are
110 // allocated
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200111 defer listenCloser.Close()
112 portMap[port] = mappedPort
113 }
114 return portMap, nil
115}
116
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200117// NewSocketPair creates a new socket pair. By connecting both ends to different
118// instances you can connect them with a virtual "network cable". The ends can be
119// passed into the ConnectToSocket option.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200120func NewSocketPair() (*os.File, *os.File, error) {
121 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
122 if err != nil {
123 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
124 }
125
126 fd1 := os.NewFile(uintptr(fds[0]), "network0")
127 fd2 := os.NewFile(uintptr(fds[1]), "network1")
128 return fd1, fd2, nil
129}
130
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200131// HostInterfaceMAC is the MAC address the host SLIRP network interface has if it
132// is not disabled (see DisableHostNetworkInterface in MicroVMOptions)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200133var HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
134
135// MicroVMOptions contains all options to start a MicroVM
136type MicroVMOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +0100137 // Name is a human-readable identifier to be used in debug output.
138 Name string
139
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200140 // Path to the ELF kernel binary
141 KernelPath string
142
143 // Path to the Initramfs
144 InitramfsPath string
145
146 // Cmdline contains additional kernel commandline options
147 Cmdline string
148
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200149 // SerialPort is a File(descriptor) over which you can communicate with the serial
150 // port of the machine It can be set to an existing file descriptor (like
151 // os.Stdout/os.Stderr) or you can use NewSocketPair() to get one end to talk to
152 // from Go.
Lorenz Brun942f5e22022-01-27 15:03:10 +0100153 SerialPort io.Writer
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200154
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200155 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary
156 // number of additional serial ports
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200157 ExtraChardevs []*os.File
158
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200159 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which
160 // are mapped into the VM as virtio network interfaces. The first interface is
161 // always a SLIRP-backed interface for communicating with the host.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200162 ExtraNetworkInterfaces []*os.File
163
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200164 // PortMap contains ports that are mapped to the host through the built-in SLIRP
165 // network interface.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200166 PortMap PortMap
167
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200168 // DisableHostNetworkInterface disables the SLIRP-backed host network interface
169 // that is normally the first network interface. If this is set PortMap is ignored.
170 // Mostly useful for speeding up QEMU's startup time for tests.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200171 DisableHostNetworkInterface bool
Leopoldacfad5b2023-01-15 14:05:25 +0100172
173 // PcapDump can be used to dump all network traffic to a pcap file.
174 // If unset, no dump is created.
175 PcapDump string
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200176}
177
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200178// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot
179// (<40ms).
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200180func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200181 // Generate options for all the file descriptors we'll be passing as virtio "serial
182 // ports"
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200183 var extraArgs []string
184 for idx, _ := range opts.ExtraChardevs {
185 idxStr := strconv.Itoa(idx)
186 id := "extra" + idxStr
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200187 // That this works is pretty much a hack, but upstream QEMU doesn't have a
188 // bidirectional chardev backend not based around files/sockets on the disk which
189 // are a giant pain to work with. We're using QEMU's fdset functionality to make
190 // FDs available as pseudo-files and then "ab"using the pipe backend's fallback
191 // functionality to get a single bidirectional chardev backend backed by a passed-
192 // down RDWR fd. Ref https://lists.gnu.org/archive/html/qemu-devel/2015-
193 // 12/msg01256.html
Serge Bazanski66e58952021-10-05 17:06:56 +0200194 addFdConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200195 "set": {idxStr},
196 "fd": {strconv.Itoa(idx + 3)},
197 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200198 chardevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200199 "id": {id},
200 "path": {"/dev/fdset/" + idxStr},
201 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200202 deviceConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200203 "chardev": {id},
204 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200205 extraArgs = append(extraArgs, "-add-fd", addFdConf.ToOption(""),
206 "-chardev", chardevConf.ToOption("pipe"), "-device", deviceConf.ToOption("virtserialport"))
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200207 }
208
209 for idx, _ := range opts.ExtraNetworkInterfaces {
210 id := fmt.Sprintf("net%v", idx)
Serge Bazanski66e58952021-10-05 17:06:56 +0200211 netdevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200212 "id": {id},
213 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
214 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200215 extraArgs = append(extraArgs, "-netdev", netdevConf.ToOption("socket"), "-device", "virtio-net-device,netdev="+id)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200216 }
217
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200218 // This sets up a minimum viable environment for our Linux kernel. It clears all
219 // standard QEMU configuration and sets up a MicroVM machine
220 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy
221 // emulation turned off. This means the only "hardware" the Linux kernel inside can
222 // communicate with is a single virtio-mmio region. Over that MMIO interface we run
223 // a paravirtualized RNG (since the kernel in there has nothing to gather that from
224 // and it delays booting), a single paravirtualized console and an arbitrary number
225 // of extra serial ports for talking to various things that might run inside. The
226 // kernel, initramfs and command line are mapped into VM memory at boot time and
227 // not loaded from any sort of disk. Booting and shutting off one of these VMs
228 // takes <100ms.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200229 baseArgs := []string{"-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
230 "-accel", "kvm", "-cpu", "host",
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200231 // Needed until QEMU updates their bundled qboot version (needs
232 // https://github.com/bonzini/qboot/pull/28)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200233 "-bios", "external/com_github_bonzini_qboot/bios.bin",
234 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
235 "-kernel", opts.KernelPath,
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200236 // We force using a triple-fault reboot strategy since otherwise the kernel first
237 // tries others (like ACPI) which are not available in this very restricted
238 // environment. Similarly we need to override the boot console since there's
239 // nothing on the ISA bus that the kernel could talk to. We also force quiet for
240 // performance reasons.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200241 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
242 "-initrd", opts.InitramfsPath,
243 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
244 "-device", "virtio-serial-device,max_ports=16",
245 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
246 }
247
248 if !opts.DisableHostNetworkInterface {
249 qemuNetType := "user"
Serge Bazanski66e58952021-10-05 17:06:56 +0200250 qemuNetConfig := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200251 "id": {"usernet0"},
252 "net": {"10.42.0.0/24"},
253 "dhcpstart": {"10.42.0.10"},
254 }
255 if opts.PortMap != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200256 qemuNetConfig["hostfwd"] = opts.PortMap.ToQemuForwards()
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200257 }
258
Serge Bazanski66e58952021-10-05 17:06:56 +0200259 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.ToOption(qemuNetType),
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200260 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
261 }
262
Leopoldacfad5b2023-01-15 14:05:25 +0100263 if !opts.DisableHostNetworkInterface && opts.PcapDump != "" {
264 qemuNetDump := QemuValue{
265 "id": {"usernet0"},
266 "netdev": {"usernet0"},
267 "file": {opts.PcapDump},
268 }
269 extraArgs = append(extraArgs, "-object", qemuNetDump.ToOption("filter-dump"))
270 }
271
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200272 var stdErrBuf bytes.Buffer
273 cmd := exec.CommandContext(ctx, "qemu-system-x86_64", append(baseArgs, extraArgs...)...)
274 cmd.Stdout = opts.SerialPort
275 cmd.Stderr = &stdErrBuf
276
277 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
278 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
279
Leopoldaf5086b2023-01-15 14:12:42 +0100280 PrettyPrintQemuArgs(opts.Name, cmd.Args)
281
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200282 err := cmd.Run()
Serge Bazanski66e58952021-10-05 17:06:56 +0200283 // If it's a context error, just quit. There's no way to tell a
284 // killed-due-to-context vs killed-due-to-external-reason error returned by Run,
285 // so we approximate by looking at the context's status.
286 if err != nil && ctx.Err() != nil {
287 return ctx.Err()
288 }
289
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200290 var exerr *exec.ExitError
291 if err != nil && errors.As(err, &exerr) {
292 exerr.Stderr = stdErrBuf.Bytes()
293 newErr := QEMUError(*exerr)
294 return &newErr
295 }
296 return err
297}
298
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200299// QEMUError is a special type of ExitError used when QEMU fails. In addition to
300// normal ExitError features it prints stderr for debugging.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200301type QEMUError exec.ExitError
302
303func (e *QEMUError) Error() string {
304 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200305}