blob: daf2f4bb4a85ee49686bf7d95cbecc137929a6e9 [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"
Leopoldaf5086b2023-01-15 14:12:42 +010026 "log"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020027 "net"
28 "os"
29 "os/exec"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020030 "strconv"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020031 "strings"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020032 "syscall"
Lorenz Bruned0503c2020-07-28 17:21:25 +020033
Lorenz Brun3ff5af32020-06-24 16:34:11 +020034 "golang.org/x/sys/unix"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020035
Serge Bazanski31370b02021-01-07 16:31:14 +010036 "source.monogon.dev/metropolis/pkg/freeport"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020037)
38
Serge Bazanski66e58952021-10-05 17:06:56 +020039type QemuValue map[string][]string
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020040
Serge Bazanski66e58952021-10-05 17:06:56 +020041// ToOption encodes structured data into a QEMU option. Example: "test", {"key1":
Serge Bazanski216fe7b2021-05-21 18:36:16 +020042// {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Serge Bazanski66e58952021-10-05 17:06:56 +020043func (value QemuValue) ToOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020044 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020045 if name != "" {
46 optionValues = append(optionValues, name)
47 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020048 for name, values := range value {
49 if len(values) == 0 {
50 optionValues = append(optionValues, name)
51 }
52 for _, val := range values {
53 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
54 }
55 }
56 return strings.Join(optionValues, ",")
57}
58
Leopoldaf5086b2023-01-15 14:12:42 +010059// PrettyPrintQemuArgs prints the given QEMU arguments to stderr.
60func PrettyPrintQemuArgs(name string, args []string) {
61 var argsFmt string
62 for _, arg := range args {
63 argsFmt += arg
64 if !strings.HasPrefix(arg, "-") {
65 argsFmt += "\n "
66 } else {
67 argsFmt += " "
68 }
69 }
70 log.Printf("Running %s:\n %s\n", name, argsFmt)
71}
72
Serge Bazanski216fe7b2021-05-21 18:36:16 +020073// PortMap represents where VM ports are mapped to on the host. It maps from the VM
74// port number to the host port number.
Serge Bazanskibe742842022-04-04 13:18:50 +020075type PortMap map[uint16]uint16
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020076
Serge Bazanski66e58952021-10-05 17:06:56 +020077// ToQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-
Serge Bazanski216fe7b2021-05-21 18:36:16 +020078// doc.html#:~:text=hostfwd=) for all mapped ports.
Serge Bazanski66e58952021-10-05 17:06:56 +020079func (p PortMap) ToQemuForwards() []string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020080 var hostfwdOptions []string
81 for vmPort, hostPort := range p {
Serge Bazanski52304a82021-10-29 16:56:18 +020082 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%d-:%d", hostPort, vmPort))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020083 }
84 return hostfwdOptions
85}
86
Serge Bazanski216fe7b2021-05-21 18:36:16 +020087// IdentityPortMap returns a port map where each given port is mapped onto itself
88// on the host. This is mainly useful for development against Metropolis. The dbg
89// command requires this mapping.
Serge Bazanskibe742842022-04-04 13:18:50 +020090func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020091 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +020092 for _, port := range ports {
Serge Bazanski52304a82021-10-29 16:56:18 +020093 portMap[port] = uint16(port)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020094 }
95 return portMap
96}
97
Serge Bazanski216fe7b2021-05-21 18:36:16 +020098// ConflictFreePortMap returns a port map where each given port is mapped onto a
99// random free port on the host. This is intended for automated testing where
100// multiple instances of Metropolis nodes might be running. Please call this
101// function for each Launch command separately and as close to it as possible since
102// it cannot guarantee that the ports will remain free.
Serge Bazanskibe742842022-04-04 13:18:50 +0200103func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200104 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200105 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200106 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200107 if err != nil {
108 return portMap, fmt.Errorf("failed to get free host port: %w", err)
109 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200110 // Defer closing of the listening port until the function is done and all ports are
111 // allocated
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200112 defer listenCloser.Close()
113 portMap[port] = mappedPort
114 }
115 return portMap, nil
116}
117
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200118// NewSocketPair creates a new socket pair. By connecting both ends to different
119// instances you can connect them with a virtual "network cable". The ends can be
120// passed into the ConnectToSocket option.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200121func NewSocketPair() (*os.File, *os.File, error) {
122 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
123 if err != nil {
124 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
125 }
126
127 fd1 := os.NewFile(uintptr(fds[0]), "network0")
128 fd2 := os.NewFile(uintptr(fds[1]), "network1")
129 return fd1, fd2, nil
130}
131
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200132// HostInterfaceMAC is the MAC address the host SLIRP network interface has if it
133// is not disabled (see DisableHostNetworkInterface in MicroVMOptions)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200134var HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
135
136// MicroVMOptions contains all options to start a MicroVM
137type MicroVMOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +0100138 // Name is a human-readable identifier to be used in debug output.
139 Name string
140
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200141 // Path to the ELF kernel binary
142 KernelPath string
143
144 // Path to the Initramfs
145 InitramfsPath string
146
147 // Cmdline contains additional kernel commandline options
148 Cmdline string
149
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200150 // SerialPort is a File(descriptor) over which you can communicate with the serial
151 // port of the machine It can be set to an existing file descriptor (like
152 // os.Stdout/os.Stderr) or you can use NewSocketPair() to get one end to talk to
153 // from Go.
Lorenz Brun942f5e22022-01-27 15:03:10 +0100154 SerialPort io.Writer
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200155
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200156 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary
157 // number of additional serial ports
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200158 ExtraChardevs []*os.File
159
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200160 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which
161 // are mapped into the VM as virtio network interfaces. The first interface is
162 // always a SLIRP-backed interface for communicating with the host.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200163 ExtraNetworkInterfaces []*os.File
164
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200165 // PortMap contains ports that are mapped to the host through the built-in SLIRP
166 // network interface.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200167 PortMap PortMap
168
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200169 // DisableHostNetworkInterface disables the SLIRP-backed host network interface
170 // that is normally the first network interface. If this is set PortMap is ignored.
171 // Mostly useful for speeding up QEMU's startup time for tests.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200172 DisableHostNetworkInterface bool
173}
174
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200175// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot
176// (<40ms).
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200177func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200178 // Generate options for all the file descriptors we'll be passing as virtio "serial
179 // ports"
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200180 var extraArgs []string
181 for idx, _ := range opts.ExtraChardevs {
182 idxStr := strconv.Itoa(idx)
183 id := "extra" + idxStr
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200184 // That this works is pretty much a hack, but upstream QEMU doesn't have a
185 // bidirectional chardev backend not based around files/sockets on the disk which
186 // are a giant pain to work with. We're using QEMU's fdset functionality to make
187 // FDs available as pseudo-files and then "ab"using the pipe backend's fallback
188 // functionality to get a single bidirectional chardev backend backed by a passed-
189 // down RDWR fd. Ref https://lists.gnu.org/archive/html/qemu-devel/2015-
190 // 12/msg01256.html
Serge Bazanski66e58952021-10-05 17:06:56 +0200191 addFdConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200192 "set": {idxStr},
193 "fd": {strconv.Itoa(idx + 3)},
194 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200195 chardevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200196 "id": {id},
197 "path": {"/dev/fdset/" + idxStr},
198 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200199 deviceConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200200 "chardev": {id},
201 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200202 extraArgs = append(extraArgs, "-add-fd", addFdConf.ToOption(""),
203 "-chardev", chardevConf.ToOption("pipe"), "-device", deviceConf.ToOption("virtserialport"))
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200204 }
205
206 for idx, _ := range opts.ExtraNetworkInterfaces {
207 id := fmt.Sprintf("net%v", idx)
Serge Bazanski66e58952021-10-05 17:06:56 +0200208 netdevConf := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200209 "id": {id},
210 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
211 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200212 extraArgs = append(extraArgs, "-netdev", netdevConf.ToOption("socket"), "-device", "virtio-net-device,netdev="+id)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200213 }
214
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200215 // This sets up a minimum viable environment for our Linux kernel. It clears all
216 // standard QEMU configuration and sets up a MicroVM machine
217 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy
218 // emulation turned off. This means the only "hardware" the Linux kernel inside can
219 // communicate with is a single virtio-mmio region. Over that MMIO interface we run
220 // a paravirtualized RNG (since the kernel in there has nothing to gather that from
221 // and it delays booting), a single paravirtualized console and an arbitrary number
222 // of extra serial ports for talking to various things that might run inside. The
223 // kernel, initramfs and command line are mapped into VM memory at boot time and
224 // not loaded from any sort of disk. Booting and shutting off one of these VMs
225 // takes <100ms.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200226 baseArgs := []string{"-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
227 "-accel", "kvm", "-cpu", "host",
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200228 // Needed until QEMU updates their bundled qboot version (needs
229 // https://github.com/bonzini/qboot/pull/28)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200230 "-bios", "external/com_github_bonzini_qboot/bios.bin",
231 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
232 "-kernel", opts.KernelPath,
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200233 // We force using a triple-fault reboot strategy since otherwise the kernel first
234 // tries others (like ACPI) which are not available in this very restricted
235 // environment. Similarly we need to override the boot console since there's
236 // nothing on the ISA bus that the kernel could talk to. We also force quiet for
237 // performance reasons.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200238 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
239 "-initrd", opts.InitramfsPath,
240 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
241 "-device", "virtio-serial-device,max_ports=16",
242 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
243 }
244
245 if !opts.DisableHostNetworkInterface {
246 qemuNetType := "user"
Serge Bazanski66e58952021-10-05 17:06:56 +0200247 qemuNetConfig := QemuValue{
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200248 "id": {"usernet0"},
249 "net": {"10.42.0.0/24"},
250 "dhcpstart": {"10.42.0.10"},
251 }
252 if opts.PortMap != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200253 qemuNetConfig["hostfwd"] = opts.PortMap.ToQemuForwards()
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200254 }
255
Serge Bazanski66e58952021-10-05 17:06:56 +0200256 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.ToOption(qemuNetType),
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200257 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
258 }
259
260 var stdErrBuf bytes.Buffer
261 cmd := exec.CommandContext(ctx, "qemu-system-x86_64", append(baseArgs, extraArgs...)...)
262 cmd.Stdout = opts.SerialPort
263 cmd.Stderr = &stdErrBuf
264
265 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
266 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
267
Leopoldaf5086b2023-01-15 14:12:42 +0100268 PrettyPrintQemuArgs(opts.Name, cmd.Args)
269
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200270 err := cmd.Run()
Serge Bazanski66e58952021-10-05 17:06:56 +0200271 // If it's a context error, just quit. There's no way to tell a
272 // killed-due-to-context vs killed-due-to-external-reason error returned by Run,
273 // so we approximate by looking at the context's status.
274 if err != nil && ctx.Err() != nil {
275 return ctx.Err()
276 }
277
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200278 var exerr *exec.ExitError
279 if err != nil && errors.As(err, &exerr) {
280 exerr.Stderr = stdErrBuf.Bytes()
281 newErr := QEMUError(*exerr)
282 return &newErr
283 }
284 return err
285}
286
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200287// QEMUError is a special type of ExitError used when QEMU fails. In addition to
288// normal ExitError features it prints stderr for debugging.
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200289type QEMUError exec.ExitError
290
291func (e *QEMUError) Error() string {
292 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200293}