blob: df36685c43d14a7bba09e0eb531fd611e398fc29 [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
17package launch
18
19import (
Lorenz Brun3ff5af32020-06-24 16:34:11 +020020 "bytes"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020021 "context"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020022 "crypto/rand"
23 "errors"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020024 "fmt"
25 "io"
26 "io/ioutil"
Leopold Schabela013ffa2020-06-03 15:09:32 +020027 "log"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020028 "net"
29 "os"
30 "os/exec"
31 "path/filepath"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020032 "strconv"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020033 "strings"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020034 "syscall"
Lorenz Bruned0503c2020-07-28 17:21:25 +020035 "time"
36
Lorenz Brun3ff5af32020-06-24 16:34:11 +020037 "github.com/golang/protobuf/proto"
Serge Bazanski77cb6c52020-12-19 00:09:22 +010038 grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020039 "golang.org/x/sys/unix"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020040 "google.golang.org/grpc"
41
Serge Bazanski31370b02021-01-07 16:31:14 +010042 "source.monogon.dev/metropolis/node"
43 "source.monogon.dev/metropolis/pkg/freeport"
44 apb "source.monogon.dev/metropolis/proto/api"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020045)
46
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020047type qemuValue map[string][]string
48
Lorenz Brun3ff5af32020-06-24 16:34:11 +020049// toOption encodes structured data into a QEMU option.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020050// Example: "test", {"key1": {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020051func (value qemuValue) toOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020052 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020053 if name != "" {
54 optionValues = append(optionValues, name)
55 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020056 for name, values := range value {
57 if len(values) == 0 {
58 optionValues = append(optionValues, name)
59 }
60 for _, val := range values {
61 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
62 }
63 }
64 return strings.Join(optionValues, ",")
65}
66
67func copyFile(src, dst string) error {
68 in, err := os.Open(src)
69 if err != nil {
Serge Bazanskibe57a032021-05-11 13:41:52 +020070 return fmt.Errorf("when opening source: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020071 }
72 defer in.Close()
73
74 out, err := os.Create(dst)
75 if err != nil {
Serge Bazanskibe57a032021-05-11 13:41:52 +020076 return fmt.Errorf("when creating destination: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020077 }
78 defer out.Close()
79
80 _, err = io.Copy(out, in)
81 if err != nil {
Serge Bazanskibe57a032021-05-11 13:41:52 +020082 return fmt.Errorf("when copying file: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020083 }
84 return out.Close()
85}
86
87// PortMap represents where VM ports are mapped to on the host. It maps from the VM port number to the host port number.
88type PortMap map[uint16]uint16
89
90// toQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-doc.html#:~:text=hostfwd=) for all
91// mapped ports.
92func (p PortMap) toQemuForwards() []string {
93 var hostfwdOptions []string
94 for vmPort, hostPort := range p {
95 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%v-:%v", hostPort, vmPort))
96 }
97 return hostfwdOptions
98}
99
100// DialGRPC creates a gRPC client for a VM port that's forwarded/mapped to the host. The given port is automatically
101// resolved to the host-mapped port.
102func (p PortMap) DialGRPC(port uint16, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
103 mappedPort, ok := p[port]
104 if !ok {
105 return nil, fmt.Errorf("cannot dial port: port %v is not mapped/forwarded", port)
106 }
107 grpcClient, err := grpc.Dial(fmt.Sprintf("localhost:%v", mappedPort), opts...)
108 if err != nil {
109 return nil, fmt.Errorf("failed to dial port %v: %w", port, err)
110 }
111 return grpcClient, nil
112}
113
114// Options contains all options that can be passed to Launch()
115type Options struct {
116 // Ports contains the port mapping where to expose the internal ports of the VM to the host. See IdentityPortMap()
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200117 // and ConflictFreePortMap(). Ignored when ConnectToSocket is set.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200118 Ports PortMap
119
Serge Bazanski662b5b32020-12-21 13:49:00 +0100120 // If set to true, reboots are honored. Otherwise all reboots exit the Launch() command. Metropolis nodes
121 // generally restarts on almost all errors, so unless you want to test reboot behavior this should be false.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200122 AllowReboot bool
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200123
Serge Bazanski662b5b32020-12-21 13:49:00 +0100124 // By default the VM is connected to the Host via SLIRP. If ConnectToSocket is set, it is instead connected
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200125 // to the given file descriptor/socket. If this is set, all port maps from the Ports option are ignored.
126 // Intended for networking this instance together with others for running more complex network configurations.
127 ConnectToSocket *os.File
128
Serge Bazanski686444e2020-12-21 14:21:14 +0100129 // SerialPort is a io.ReadWriter over which you can communicate with the serial port of the machine
130 // It can be set to an existing file descriptor (like os.Stdout/os.Stderr) or any Go structure implementing this interface.
131 SerialPort io.ReadWriter
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200132
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100133 // NodeParameters is passed into the VM and subsequently used for bootstrapping or registering into a cluster.
134 NodeParameters *apb.NodeParameters
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200135}
136
Serge Bazanski662b5b32020-12-21 13:49:00 +0100137// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski549b72b2021-01-07 14:54:19 +0100138var NodePorts = []uint16{node.ConsensusPort, node.NodeServicePort, node.MasterServicePort,
139 node.ExternalServicePort, node.DebugServicePort, node.KubernetesAPIPort, node.DebuggerPort}
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200140
Lorenz Bruned0503c2020-07-28 17:21:25 +0200141// IdentityPortMap returns a port map where each given port is mapped onto itself on the host. This is mainly useful
Serge Bazanski662b5b32020-12-21 13:49:00 +0100142// for development against Metropolis. The dbg command requires this mapping.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200143func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200144 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200145 for _, port := range ports {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200146 portMap[port] = port
147 }
148 return portMap
149}
150
Lorenz Bruned0503c2020-07-28 17:21:25 +0200151// ConflictFreePortMap returns a port map where each given port is mapped onto a random free port on the host. This is
Serge Bazanski662b5b32020-12-21 13:49:00 +0100152// intended for automated testing where multiple instances of Metropolis nodes might be running. Please call this
153// function for each Launch command separately and as close to it as possible since it cannot guarantee that the ports
154// will remain free.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200155func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200156 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200157 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200158 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200159 if err != nil {
160 return portMap, fmt.Errorf("failed to get free host port: %w", err)
161 }
162 // Defer closing of the listening port until the function is done and all ports are allocated
163 defer listenCloser.Close()
164 portMap[port] = mappedPort
165 }
166 return portMap, nil
167}
168
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200169// Gets a random EUI-48 Ethernet MAC address
170func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
171 macBuf := make([]byte, 6)
172 _, err := rand.Read(macBuf)
173 if err != nil {
174 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
175 }
176
177 // Set U/L bit and clear I/G bit (locally administered individual MAC)
178 // Ref IEEE 802-2014 Section 8.2.2
179 macBuf[0] = (macBuf[0] | 2) & 0xfe
180 mac := net.HardwareAddr(macBuf)
181 return &mac, nil
182}
183
Serge Bazanski662b5b32020-12-21 13:49:00 +0100184// Launch launches a Metropolis node instance with the given options. The instance runs mostly paravirtualized but
185// with some emulated hardware similar to how a cloud provider might set up its VMs. The disk is fully writable but
186// is run in snapshot mode meaning that changes are not kept beyond a single invocation.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200187func Launch(ctx context.Context, options Options) error {
188 // Pin temp directory to /tmp until we can use abstract socket namespace in QEMU (next release after 5.0,
189 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9). swtpm accepts already-open FDs
190 // so we can pass in an abstract socket namespace FD that we open and pass the name of it to QEMU. Not pinning this
191 // crashes both swtpm and qemu because we run into UNIX socket length limitations (for legacy reasons 108 chars).
192 tempDir, err := ioutil.TempDir("/tmp", "launch*")
193 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200194 return fmt.Errorf("failed to create temporary directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200195 }
196 defer os.RemoveAll(tempDir)
197
198 // Copy TPM state into a temporary directory since it's being modified by the emulator
199 tpmTargetDir := filepath.Join(tempDir, "tpm")
Serge Bazanski77cb6c52020-12-19 00:09:22 +0100200 tpmSrcDir := "metropolis/node/tpm"
Serge Bazanskibe57a032021-05-11 13:41:52 +0200201 if err := os.Mkdir(tpmTargetDir, 0755); err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200202 return fmt.Errorf("failed to create TPM state directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200203 }
204 tpmFiles, err := ioutil.ReadDir(tpmSrcDir)
205 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200206 return fmt.Errorf("failed to read TPM directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200207 }
208 for _, file := range tpmFiles {
209 name := file.Name()
Serge Bazanskibe57a032021-05-11 13:41:52 +0200210 src := filepath.Join(tpmSrcDir, name)
211 target := filepath.Join(tpmTargetDir, name)
212 if err := copyFile(src, target); err != nil {
213 return fmt.Errorf("failed to copy TPM directory: file %q to %q: %w", src, target, err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200214 }
215 }
216
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200217 var qemuNetType string
218 var qemuNetConfig qemuValue
219 if options.ConnectToSocket != nil {
220 qemuNetType = "socket"
221 qemuNetConfig = qemuValue{
222 "id": {"net0"},
223 "fd": {"3"},
224 }
225 } else {
226 qemuNetType = "user"
227 qemuNetConfig = qemuValue{
228 "id": {"net0"},
229 "net": {"10.42.0.0/24"},
230 "dhcpstart": {"10.42.0.10"},
231 "hostfwd": options.Ports.toQemuForwards(),
232 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200233 }
234
235 tpmSocketPath := filepath.Join(tempDir, "tpm-socket")
236
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200237 mac, err := generateRandomEthernetMAC()
238 if err != nil {
239 return err
240 }
241
Lorenz Brunca24cfa2020-08-18 13:49:37 +0200242 qemuArgs := []string{"-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults", "-m", "4096",
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200243 "-cpu", "host", "-smp", "sockets=1,cpus=1,cores=2,threads=2,maxcpus=4",
244 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
245 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Serge Bazanski662b5b32020-12-21 13:49:00 +0100246 "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file=metropolis/node/node.img",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200247 "-netdev", qemuNetConfig.toOption(qemuNetType),
248 "-device", "virtio-net-pci,netdev=net0,mac=" + mac.String(),
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200249 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
250 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
251 "-device", "tpm-tis,tpmdev=tpm0",
252 "-device", "virtio-rng-pci",
253 "-serial", "stdio"}
254
255 if !options.AllowReboot {
256 qemuArgs = append(qemuArgs, "-no-reboot")
257 }
258
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100259 if options.NodeParameters != nil {
260 parametersPath := filepath.Join(tempDir, "parameters.pb")
261 parametersRaw, err := proto.Marshal(options.NodeParameters)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200262 if err != nil {
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100263 return fmt.Errorf("failed to encode node paraeters: %w", err)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200264 }
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100265 if err := ioutil.WriteFile(parametersPath, parametersRaw, 0644); err != nil {
266 return fmt.Errorf("failed to write node parameters: %w", err)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200267 }
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100268 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200269 }
270
Leopold Schabela013ffa2020-06-03 15:09:32 +0200271 // Start TPM emulator as a subprocess
272 tpmCtx, tpmCancel := context.WithCancel(ctx)
273 defer tpmCancel()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200274
Leopold Schabela013ffa2020-06-03 15:09:32 +0200275 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmTargetDir, "--ctrl", "type=unixio,path="+tpmSocketPath)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200276 tpmEmuCmd.Stderr = os.Stderr
277 tpmEmuCmd.Stdout = os.Stdout
Leopold Schabela013ffa2020-06-03 15:09:32 +0200278
279 err = tpmEmuCmd.Start()
280 if err != nil {
281 return fmt.Errorf("failed to start TPM emulator: %w", err)
282 }
283
284 // Start the main qemu binary
285 systemCmd := exec.CommandContext(ctx, "qemu-system-x86_64", qemuArgs...)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200286 if options.ConnectToSocket != nil {
287 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
288 }
289
290 var stdErrBuf bytes.Buffer
291 systemCmd.Stderr = &stdErrBuf
292 systemCmd.Stdout = options.SerialPort
Leopold Schabela013ffa2020-06-03 15:09:32 +0200293
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200294 err = systemCmd.Run()
Leopold Schabela013ffa2020-06-03 15:09:32 +0200295
296 // Stop TPM emulator and wait for it to exit to properly reap the child process
297 tpmCancel()
298 log.Print("Waiting for TPM emulator to exit")
299 // Wait returns a SIGKILL error because we just cancelled its context.
300 // We still need to call it to avoid creating zombies.
301 _ = tpmEmuCmd.Wait()
302
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200303 var exerr *exec.ExitError
304 if err != nil && errors.As(err, &exerr) {
305 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
306 if status.Signaled() && status.Signal() == syscall.SIGKILL {
307 // Process was killed externally (most likely by our context being canceled).
308 // This is a normal exit for us, so return nil
309 return nil
310 }
311 exerr.Stderr = stdErrBuf.Bytes()
312 newErr := QEMUError(*exerr)
313 return &newErr
314 }
315 return err
316}
317
318// NewSocketPair creates a new socket pair. By connecting both ends to different instances you can connect them
319// with a virtual "network cable". The ends can be passed into the ConnectToSocket option.
320func NewSocketPair() (*os.File, *os.File, error) {
321 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
322 if err != nil {
323 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
324 }
325
326 fd1 := os.NewFile(uintptr(fds[0]), "network0")
327 fd2 := os.NewFile(uintptr(fds[1]), "network1")
328 return fd1, fd2, nil
329}
330
331// HostInterfaceMAC is the MAC address the host SLIRP network interface has if it is not disabled (see
332// DisableHostNetworkInterface in MicroVMOptions)
333var HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
334
335// MicroVMOptions contains all options to start a MicroVM
336type MicroVMOptions struct {
337 // Path to the ELF kernel binary
338 KernelPath string
339
340 // Path to the Initramfs
341 InitramfsPath string
342
343 // Cmdline contains additional kernel commandline options
344 Cmdline string
345
346 // SerialPort is a File(descriptor) over which you can communicate with the serial port of the machine
347 // It can be set to an existing file descriptor (like os.Stdout/os.Stderr) or you can use NewSocketPair() to get one
348 // end to talk to from Go.
349 SerialPort *os.File
350
351 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary number of additional serial ports
352 ExtraChardevs []*os.File
353
354 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which are mapped into the VM as virtio
355 // network interfaces. The first interface is always a SLIRP-backed interface for communicating with the host.
356 ExtraNetworkInterfaces []*os.File
357
358 // PortMap contains ports that are mapped to the host through the built-in SLIRP network interface.
359 PortMap PortMap
360
361 // DisableHostNetworkInterface disables the SLIRP-backed host network interface that is normally the first network
362 // interface. If this is set PortMap is ignored. Mostly useful for speeding up QEMU's startup time for tests.
363 DisableHostNetworkInterface bool
364}
365
366// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot (<40ms).
367func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
368 // Generate options for all the file descriptors we'll be passing as virtio "serial ports"
369 var extraArgs []string
370 for idx, _ := range opts.ExtraChardevs {
371 idxStr := strconv.Itoa(idx)
372 id := "extra" + idxStr
373 // That this works is pretty much a hack, but upstream QEMU doesn't have a bidirectional chardev backend not
374 // based around files/sockets on the disk which are a giant pain to work with.
375 // We're using QEMU's fdset functionality to make FDs available as pseudo-files and then "ab"using the pipe
376 // backend's fallback functionality to get a single bidirectional chardev backend backed by a passed-down
377 // RDWR fd.
378 // Ref https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg01256.html
379 addFdConf := qemuValue{
380 "set": {idxStr},
381 "fd": {strconv.Itoa(idx + 3)},
382 }
383 chardevConf := qemuValue{
384 "id": {id},
385 "path": {"/dev/fdset/" + idxStr},
386 }
387 deviceConf := qemuValue{
388 "chardev": {id},
389 }
390 extraArgs = append(extraArgs, "-add-fd", addFdConf.toOption(""),
391 "-chardev", chardevConf.toOption("pipe"), "-device", deviceConf.toOption("virtserialport"))
392 }
393
394 for idx, _ := range opts.ExtraNetworkInterfaces {
395 id := fmt.Sprintf("net%v", idx)
396 netdevConf := qemuValue{
397 "id": {id},
398 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
399 }
400 extraArgs = append(extraArgs, "-netdev", netdevConf.toOption("socket"), "-device", "virtio-net-device,netdev="+id)
401 }
402
403 // This sets up a minimum viable environment for our Linux kernel.
404 // It clears all standard QEMU configuration and sets up a MicroVM machine
405 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy emulation turned off. This means
406 // the only "hardware" the Linux kernel inside can communicate with is a single virtio-mmio region. Over that MMIO
407 // interface we run a paravirtualized RNG (since the kernel in there has nothing to gather that from and it
408 // delays booting), a single paravirtualized console and an arbitrary number of extra serial ports for talking to
409 // various things that might run inside. The kernel, initramfs and command line are mapped into VM memory at boot
410 // time and not loaded from any sort of disk. Booting and shutting off one of these VMs takes <100ms.
411 baseArgs := []string{"-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
412 "-accel", "kvm", "-cpu", "host",
413 // Needed until QEMU updates their bundled qboot version (needs https://github.com/bonzini/qboot/pull/28)
414 "-bios", "external/com_github_bonzini_qboot/bios.bin",
415 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
416 "-kernel", opts.KernelPath,
417 // We force using a triple-fault reboot strategy since otherwise the kernel first tries others (like ACPI) which
418 // are not available in this very restricted environment. Similarly we need to override the boot console since
419 // there's nothing on the ISA bus that the kernel could talk to. We also force quiet for performance reasons.
420 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
421 "-initrd", opts.InitramfsPath,
422 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
423 "-device", "virtio-serial-device,max_ports=16",
424 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
425 }
426
427 if !opts.DisableHostNetworkInterface {
428 qemuNetType := "user"
429 qemuNetConfig := qemuValue{
430 "id": {"usernet0"},
431 "net": {"10.42.0.0/24"},
432 "dhcpstart": {"10.42.0.10"},
433 }
434 if opts.PortMap != nil {
435 qemuNetConfig["hostfwd"] = opts.PortMap.toQemuForwards()
436 }
437
438 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.toOption(qemuNetType),
439 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
440 }
441
442 var stdErrBuf bytes.Buffer
443 cmd := exec.CommandContext(ctx, "qemu-system-x86_64", append(baseArgs, extraArgs...)...)
444 cmd.Stdout = opts.SerialPort
445 cmd.Stderr = &stdErrBuf
446
447 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
448 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
449
450 err := cmd.Run()
451 var exerr *exec.ExitError
452 if err != nil && errors.As(err, &exerr) {
453 exerr.Stderr = stdErrBuf.Bytes()
454 newErr := QEMUError(*exerr)
455 return &newErr
456 }
457 return err
458}
459
460// QEMUError is a special type of ExitError used when QEMU fails. In addition to normal ExitError features it
461// prints stderr for debugging.
462type QEMUError exec.ExitError
463
464func (e *QEMUError) Error() string {
465 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200466}
Lorenz Bruned0503c2020-07-28 17:21:25 +0200467
468// NanoswitchPorts contains all ports forwarded by Nanoswitch to the first VM
469var NanoswitchPorts = []uint16{
Serge Bazanski549b72b2021-01-07 14:54:19 +0100470 node.ExternalServicePort,
471 node.DebugServicePort,
472 node.KubernetesAPIPort,
Lorenz Bruned0503c2020-07-28 17:21:25 +0200473}
474
Serge Bazanski662b5b32020-12-21 13:49:00 +0100475// ClusterOptions contains all options for launching a Metropolis cluster
Lorenz Bruned0503c2020-07-28 17:21:25 +0200476type ClusterOptions struct {
477 // The number of nodes this cluster should be started with initially
478 NumNodes int
479}
480
Serge Bazanski662b5b32020-12-21 13:49:00 +0100481// LaunchCluster launches a cluster of Metropolis node VMs together with a Nanoswitch instance to network them all together.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200482func LaunchCluster(ctx context.Context, opts ClusterOptions) (apb.NodeDebugServiceClient, PortMap, error) {
483 var switchPorts []*os.File
484 var vmPorts []*os.File
485 for i := 0; i < opts.NumNodes; i++ {
486 switchPort, vmPort, err := NewSocketPair()
487 if err != nil {
488 return nil, nil, fmt.Errorf("failed to get socketpair: %w", err)
489 }
490 switchPorts = append(switchPorts, switchPort)
491 vmPorts = append(vmPorts, vmPort)
492 }
493
494 if opts.NumNodes == 0 {
495 return nil, nil, errors.New("refusing to start cluster with zero nodes")
496 }
497
498 if opts.NumNodes > 2 {
499 return nil, nil, errors.New("launching more than 2 nodes is unsupported pending replacement of golden tickets")
500 }
501
502 go func() {
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100503 if err := Launch(ctx, Options{
504 ConnectToSocket: vmPorts[0],
505 NodeParameters: &apb.NodeParameters{
506 Cluster: &apb.NodeParameters_ClusterBootstrap_{
507 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{},
508 },
509 },
510 }); err != nil {
511
Lorenz Bruned0503c2020-07-28 17:21:25 +0200512 // Launch() only terminates when QEMU has terminated. At that point our function probably doesn't run anymore
513 // so we have no way of communicating the error back up, so let's just log it. Also a failure in launching
514 // VMs should be very visible by the unavailability of the clients we return.
515 log.Printf("Failed to launch vm0: %v", err)
516 }
517 }()
518
519 portMap, err := ConflictFreePortMap(NanoswitchPorts)
520 if err != nil {
521 return nil, nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
522 }
523
524 go func() {
525 if err := RunMicroVM(ctx, &MicroVMOptions{
Serge Bazanskif055a7f2021-04-13 16:22:33 +0200526 KernelPath: "metropolis/test/ktest/vmlinux",
Serge Bazanski77cb6c52020-12-19 00:09:22 +0100527 InitramfsPath: "metropolis/test/nanoswitch/initramfs.lz4",
Lorenz Bruned0503c2020-07-28 17:21:25 +0200528 ExtraNetworkInterfaces: switchPorts,
529 PortMap: portMap,
530 }); err != nil {
531 log.Printf("Failed to launch nanoswitch: %v", err)
532 }
533 }()
534 copts := []grpcretry.CallOption{
535 grpcretry.WithBackoff(grpcretry.BackoffExponential(100 * time.Millisecond)),
536 }
Serge Bazanski549b72b2021-01-07 14:54:19 +0100537 conn, err := portMap.DialGRPC(node.DebugServicePort, grpc.WithInsecure(),
Lorenz Bruned0503c2020-07-28 17:21:25 +0200538 grpc.WithUnaryInterceptor(grpcretry.UnaryClientInterceptor(copts...)))
539 if err != nil {
540 return nil, nil, fmt.Errorf("failed to dial debug service: %w", err)
541 }
Lorenz Bruned0503c2020-07-28 17:21:25 +0200542 debug := apb.NewNodeDebugServiceClient(conn)
543
544 if opts.NumNodes == 2 {
Serge Bazanski0ed2f962021-03-15 16:39:30 +0100545 return nil, nil, fmt.Errorf("multinode unimplemented")
Lorenz Bruned0503c2020-07-28 17:21:25 +0200546 }
547
548 return debug, portMap, nil
549}