blob: 2d495e0f81421b53ec83c6b847ad4c0c4e648c12 [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 Bazanskicb883e22020-07-06 17:47:55 +020042 freeport "git.monogon.dev/source/nexantic.git/golibs/common"
Serge Bazanski77cb6c52020-12-19 00:09:22 +010043 common "git.monogon.dev/source/nexantic.git/metropolis/node"
44 apb "git.monogon.dev/source/nexantic.git/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 {
70 return err
71 }
72 defer in.Close()
73
74 out, err := os.Create(dst)
75 if err != nil {
76 return err
77 }
78 defer out.Close()
79
80 _, err = io.Copy(out, in)
81 if err != nil {
82 return err
83 }
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
120 // If set to true, reboots are honored. Otherwise all reboots exit the Launch() command. Smalltown generally restarts
121 // on almost all errors, so unless you want to test reboot behavior this should be false.
122 AllowReboot bool
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200123
124 // By default the Smalltown VM is connected to the Host via SLIRP. If ConnectToSocket is set, it is instead connected
125 // 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
129 // SerialPort is a File(descriptor) 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 you can use NewSocketPair() to get one
131 // end to talk to from Go.
132 SerialPort *os.File
133
134 // EnrolmentConfig is passed into the VM and subsequently used for bootstrapping if no enrolment config is built-in
Serge Bazanskiefdb6e92020-07-13 17:19:27 +0200135 EnrolmentConfig *apb.EnrolmentConfig
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200136}
137
Lorenz Bruned0503c2020-07-28 17:21:25 +0200138// NodePorts is the list of ports a fully operational Smalltown node listens on
139var NodePorts = []uint16{common.ConsensusPort, common.NodeServicePort, common.MasterServicePort,
Lorenz Brun70f65b22020-07-08 17:02:47 +0200140 common.ExternalServicePort, common.DebugServicePort, common.KubernetesAPIPort, common.DebuggerPort}
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200141
Lorenz Bruned0503c2020-07-28 17:21:25 +0200142// IdentityPortMap returns a port map where each given port is mapped onto itself on the host. This is mainly useful
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200143// for development against Smalltown. The dbg command requires this mapping.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200144func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200145 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200146 for _, port := range ports {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200147 portMap[port] = port
148 }
149 return portMap
150}
151
Lorenz Bruned0503c2020-07-28 17:21:25 +0200152// ConflictFreePortMap returns a port map where each given port is mapped onto a random free port on the host. This is
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200153// intended for automated testing where multiple instances of Smalltown might be running. Please call this function for
154// each Launch command separately and as close to it as possible since it cannot guarantee that the ports will remain
155// free.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200156func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200157 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200158 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200159 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200160 if err != nil {
161 return portMap, fmt.Errorf("failed to get free host port: %w", err)
162 }
163 // Defer closing of the listening port until the function is done and all ports are allocated
164 defer listenCloser.Close()
165 portMap[port] = mappedPort
166 }
167 return portMap, nil
168}
169
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200170// Gets a random EUI-48 Ethernet MAC address
171func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
172 macBuf := make([]byte, 6)
173 _, err := rand.Read(macBuf)
174 if err != nil {
175 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
176 }
177
178 // Set U/L bit and clear I/G bit (locally administered individual MAC)
179 // Ref IEEE 802-2014 Section 8.2.2
180 macBuf[0] = (macBuf[0] | 2) & 0xfe
181 mac := net.HardwareAddr(macBuf)
182 return &mac, nil
183}
184
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200185// Launch launches a Smalltown instance with the given options. The instance runs mostly paravirtualized but with some
186// emulated hardware similar to how a cloud provider might set up its VMs. The disk is fully writable but is run
187// in snapshot mode meaning that changes are not kept beyond a single invocation.
188func Launch(ctx context.Context, options Options) error {
189 // Pin temp directory to /tmp until we can use abstract socket namespace in QEMU (next release after 5.0,
190 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9). swtpm accepts already-open FDs
191 // so we can pass in an abstract socket namespace FD that we open and pass the name of it to QEMU. Not pinning this
192 // crashes both swtpm and qemu because we run into UNIX socket length limitations (for legacy reasons 108 chars).
193 tempDir, err := ioutil.TempDir("/tmp", "launch*")
194 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200195 return fmt.Errorf("failed to create temporary directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200196 }
197 defer os.RemoveAll(tempDir)
198
199 // Copy TPM state into a temporary directory since it's being modified by the emulator
200 tpmTargetDir := filepath.Join(tempDir, "tpm")
Serge Bazanski77cb6c52020-12-19 00:09:22 +0100201 tpmSrcDir := "metropolis/node/tpm"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200202 if err := os.Mkdir(tpmTargetDir, 0644); err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200203 return fmt.Errorf("failed to create TPM state directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200204 }
205 tpmFiles, err := ioutil.ReadDir(tpmSrcDir)
206 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200207 return fmt.Errorf("failed to read TPM directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200208 }
209 for _, file := range tpmFiles {
210 name := file.Name()
211 if err := copyFile(filepath.Join(tpmSrcDir, name), filepath.Join(tpmTargetDir, name)); err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200212 return fmt.Errorf("failed to copy TPM directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200213 }
214 }
215
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200216 var qemuNetType string
217 var qemuNetConfig qemuValue
218 if options.ConnectToSocket != nil {
219 qemuNetType = "socket"
220 qemuNetConfig = qemuValue{
221 "id": {"net0"},
222 "fd": {"3"},
223 }
224 } else {
225 qemuNetType = "user"
226 qemuNetConfig = qemuValue{
227 "id": {"net0"},
228 "net": {"10.42.0.0/24"},
229 "dhcpstart": {"10.42.0.10"},
230 "hostfwd": options.Ports.toQemuForwards(),
231 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200232 }
233
234 tpmSocketPath := filepath.Join(tempDir, "tpm-socket")
235
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200236 mac, err := generateRandomEthernetMAC()
237 if err != nil {
238 return err
239 }
240
Lorenz Brunca24cfa2020-08-18 13:49:37 +0200241 qemuArgs := []string{"-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults", "-m", "4096",
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200242 "-cpu", "host", "-smp", "sockets=1,cpus=1,cores=2,threads=2,maxcpus=4",
243 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
244 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Serge Bazanski77cb6c52020-12-19 00:09:22 +0100245 "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file=metropolis/node/smalltown.img",
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200246 "-netdev", qemuNetConfig.toOption(qemuNetType),
247 "-device", "virtio-net-pci,netdev=net0,mac=" + mac.String(),
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200248 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
249 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
250 "-device", "tpm-tis,tpmdev=tpm0",
251 "-device", "virtio-rng-pci",
252 "-serial", "stdio"}
253
254 if !options.AllowReboot {
255 qemuArgs = append(qemuArgs, "-no-reboot")
256 }
257
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200258 if options.EnrolmentConfig != nil {
259 enrolmentConfigPath := filepath.Join(tempDir, "enrolment.pb")
260 enrolmentConfigRaw, err := proto.Marshal(options.EnrolmentConfig)
261 if err != nil {
262 return fmt.Errorf("failed to encode enrolment config: %w", err)
263 }
264 if err := ioutil.WriteFile(enrolmentConfigPath, enrolmentConfigRaw, 0644); err != nil {
265 return fmt.Errorf("failed to write enrolment config: %w", err)
266 }
267 qemuArgs = append(qemuArgs, "-fw_cfg", "name=com.nexantic.smalltown/enrolment.pb,file="+enrolmentConfigPath)
268 }
269
Leopold Schabela013ffa2020-06-03 15:09:32 +0200270 // Start TPM emulator as a subprocess
271 tpmCtx, tpmCancel := context.WithCancel(ctx)
272 defer tpmCancel()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200273
Leopold Schabela013ffa2020-06-03 15:09:32 +0200274 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmTargetDir, "--ctrl", "type=unixio,path="+tpmSocketPath)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200275 tpmEmuCmd.Stderr = os.Stderr
276 tpmEmuCmd.Stdout = os.Stdout
Leopold Schabela013ffa2020-06-03 15:09:32 +0200277
278 err = tpmEmuCmd.Start()
279 if err != nil {
280 return fmt.Errorf("failed to start TPM emulator: %w", err)
281 }
282
283 // Start the main qemu binary
284 systemCmd := exec.CommandContext(ctx, "qemu-system-x86_64", qemuArgs...)
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200285 if options.ConnectToSocket != nil {
286 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
287 }
288
289 var stdErrBuf bytes.Buffer
290 systemCmd.Stderr = &stdErrBuf
291 systemCmd.Stdout = options.SerialPort
Leopold Schabela013ffa2020-06-03 15:09:32 +0200292
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200293 err = systemCmd.Run()
Leopold Schabela013ffa2020-06-03 15:09:32 +0200294
295 // Stop TPM emulator and wait for it to exit to properly reap the child process
296 tpmCancel()
297 log.Print("Waiting for TPM emulator to exit")
298 // Wait returns a SIGKILL error because we just cancelled its context.
299 // We still need to call it to avoid creating zombies.
300 _ = tpmEmuCmd.Wait()
301
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200302 var exerr *exec.ExitError
303 if err != nil && errors.As(err, &exerr) {
304 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
305 if status.Signaled() && status.Signal() == syscall.SIGKILL {
306 // Process was killed externally (most likely by our context being canceled).
307 // This is a normal exit for us, so return nil
308 return nil
309 }
310 exerr.Stderr = stdErrBuf.Bytes()
311 newErr := QEMUError(*exerr)
312 return &newErr
313 }
314 return err
315}
316
317// NewSocketPair creates a new socket pair. By connecting both ends to different instances you can connect them
318// with a virtual "network cable". The ends can be passed into the ConnectToSocket option.
319func NewSocketPair() (*os.File, *os.File, error) {
320 fds, err := unix.Socketpair(unix.AF_UNIX, syscall.SOCK_STREAM, 0)
321 if err != nil {
322 return nil, nil, fmt.Errorf("failed to call socketpair: %w", err)
323 }
324
325 fd1 := os.NewFile(uintptr(fds[0]), "network0")
326 fd2 := os.NewFile(uintptr(fds[1]), "network1")
327 return fd1, fd2, nil
328}
329
330// HostInterfaceMAC is the MAC address the host SLIRP network interface has if it is not disabled (see
331// DisableHostNetworkInterface in MicroVMOptions)
332var HostInterfaceMAC = net.HardwareAddr{0x02, 0x72, 0x82, 0xbf, 0xc3, 0x56}
333
334// MicroVMOptions contains all options to start a MicroVM
335type MicroVMOptions struct {
336 // Path to the ELF kernel binary
337 KernelPath string
338
339 // Path to the Initramfs
340 InitramfsPath string
341
342 // Cmdline contains additional kernel commandline options
343 Cmdline string
344
345 // SerialPort is a File(descriptor) over which you can communicate with the serial port of the machine
346 // It can be set to an existing file descriptor (like os.Stdout/os.Stderr) or you can use NewSocketPair() to get one
347 // end to talk to from Go.
348 SerialPort *os.File
349
350 // ExtraChardevs can be used similar to SerialPort, but can contain an arbitrary number of additional serial ports
351 ExtraChardevs []*os.File
352
353 // ExtraNetworkInterfaces can contain an arbitrary number of file descriptors which are mapped into the VM as virtio
354 // network interfaces. The first interface is always a SLIRP-backed interface for communicating with the host.
355 ExtraNetworkInterfaces []*os.File
356
357 // PortMap contains ports that are mapped to the host through the built-in SLIRP network interface.
358 PortMap PortMap
359
360 // DisableHostNetworkInterface disables the SLIRP-backed host network interface that is normally the first network
361 // interface. If this is set PortMap is ignored. Mostly useful for speeding up QEMU's startup time for tests.
362 DisableHostNetworkInterface bool
363}
364
365// RunMicroVM launches a tiny VM mostly intended for testing. Very quick to boot (<40ms).
366func RunMicroVM(ctx context.Context, opts *MicroVMOptions) error {
367 // Generate options for all the file descriptors we'll be passing as virtio "serial ports"
368 var extraArgs []string
369 for idx, _ := range opts.ExtraChardevs {
370 idxStr := strconv.Itoa(idx)
371 id := "extra" + idxStr
372 // That this works is pretty much a hack, but upstream QEMU doesn't have a bidirectional chardev backend not
373 // based around files/sockets on the disk which are a giant pain to work with.
374 // We're using QEMU's fdset functionality to make FDs available as pseudo-files and then "ab"using the pipe
375 // backend's fallback functionality to get a single bidirectional chardev backend backed by a passed-down
376 // RDWR fd.
377 // Ref https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg01256.html
378 addFdConf := qemuValue{
379 "set": {idxStr},
380 "fd": {strconv.Itoa(idx + 3)},
381 }
382 chardevConf := qemuValue{
383 "id": {id},
384 "path": {"/dev/fdset/" + idxStr},
385 }
386 deviceConf := qemuValue{
387 "chardev": {id},
388 }
389 extraArgs = append(extraArgs, "-add-fd", addFdConf.toOption(""),
390 "-chardev", chardevConf.toOption("pipe"), "-device", deviceConf.toOption("virtserialport"))
391 }
392
393 for idx, _ := range opts.ExtraNetworkInterfaces {
394 id := fmt.Sprintf("net%v", idx)
395 netdevConf := qemuValue{
396 "id": {id},
397 "fd": {strconv.Itoa(idx + 3 + len(opts.ExtraChardevs))},
398 }
399 extraArgs = append(extraArgs, "-netdev", netdevConf.toOption("socket"), "-device", "virtio-net-device,netdev="+id)
400 }
401
402 // This sets up a minimum viable environment for our Linux kernel.
403 // It clears all standard QEMU configuration and sets up a MicroVM machine
404 // (https://github.com/qemu/qemu/blob/master/docs/microvm.rst) with all legacy emulation turned off. This means
405 // the only "hardware" the Linux kernel inside can communicate with is a single virtio-mmio region. Over that MMIO
406 // interface we run a paravirtualized RNG (since the kernel in there has nothing to gather that from and it
407 // delays booting), a single paravirtualized console and an arbitrary number of extra serial ports for talking to
408 // various things that might run inside. The kernel, initramfs and command line are mapped into VM memory at boot
409 // time and not loaded from any sort of disk. Booting and shutting off one of these VMs takes <100ms.
410 baseArgs := []string{"-nodefaults", "-no-user-config", "-nographic", "-no-reboot",
411 "-accel", "kvm", "-cpu", "host",
412 // Needed until QEMU updates their bundled qboot version (needs https://github.com/bonzini/qboot/pull/28)
413 "-bios", "external/com_github_bonzini_qboot/bios.bin",
414 "-M", "microvm,x-option-roms=off,pic=off,pit=off,rtc=off,isa-serial=off",
415 "-kernel", opts.KernelPath,
416 // We force using a triple-fault reboot strategy since otherwise the kernel first tries others (like ACPI) which
417 // are not available in this very restricted environment. Similarly we need to override the boot console since
418 // there's nothing on the ISA bus that the kernel could talk to. We also force quiet for performance reasons.
419 "-append", "reboot=t console=hvc0 quiet " + opts.Cmdline,
420 "-initrd", opts.InitramfsPath,
421 "-device", "virtio-rng-device,max-bytes=1024,period=1000",
422 "-device", "virtio-serial-device,max_ports=16",
423 "-chardev", "stdio,id=con0", "-device", "virtconsole,chardev=con0",
424 }
425
426 if !opts.DisableHostNetworkInterface {
427 qemuNetType := "user"
428 qemuNetConfig := qemuValue{
429 "id": {"usernet0"},
430 "net": {"10.42.0.0/24"},
431 "dhcpstart": {"10.42.0.10"},
432 }
433 if opts.PortMap != nil {
434 qemuNetConfig["hostfwd"] = opts.PortMap.toQemuForwards()
435 }
436
437 baseArgs = append(baseArgs, "-netdev", qemuNetConfig.toOption(qemuNetType),
438 "-device", "virtio-net-device,netdev=usernet0,mac="+HostInterfaceMAC.String())
439 }
440
441 var stdErrBuf bytes.Buffer
442 cmd := exec.CommandContext(ctx, "qemu-system-x86_64", append(baseArgs, extraArgs...)...)
443 cmd.Stdout = opts.SerialPort
444 cmd.Stderr = &stdErrBuf
445
446 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraChardevs...)
447 cmd.ExtraFiles = append(cmd.ExtraFiles, opts.ExtraNetworkInterfaces...)
448
449 err := cmd.Run()
450 var exerr *exec.ExitError
451 if err != nil && errors.As(err, &exerr) {
452 exerr.Stderr = stdErrBuf.Bytes()
453 newErr := QEMUError(*exerr)
454 return &newErr
455 }
456 return err
457}
458
459// QEMUError is a special type of ExitError used when QEMU fails. In addition to normal ExitError features it
460// prints stderr for debugging.
461type QEMUError exec.ExitError
462
463func (e *QEMUError) Error() string {
464 return fmt.Sprintf("%v: %v", e.String(), string(e.Stderr))
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200465}
Lorenz Bruned0503c2020-07-28 17:21:25 +0200466
467// NanoswitchPorts contains all ports forwarded by Nanoswitch to the first VM
468var NanoswitchPorts = []uint16{
469 common.ExternalServicePort,
470 common.DebugServicePort,
471 common.KubernetesAPIPort,
472}
473
474// ClusterOptions contains all options for launching a Smalltown cluster
475type ClusterOptions struct {
476 // The number of nodes this cluster should be started with initially
477 NumNodes int
478}
479
480// LaunchCluster launches a cluster of Smalltown VMs together with a Nanoswitch instance to network them all together.
481func LaunchCluster(ctx context.Context, opts ClusterOptions) (apb.NodeDebugServiceClient, PortMap, error) {
482 var switchPorts []*os.File
483 var vmPorts []*os.File
484 for i := 0; i < opts.NumNodes; i++ {
485 switchPort, vmPort, err := NewSocketPair()
486 if err != nil {
487 return nil, nil, fmt.Errorf("failed to get socketpair: %w", err)
488 }
489 switchPorts = append(switchPorts, switchPort)
490 vmPorts = append(vmPorts, vmPort)
491 }
492
493 if opts.NumNodes == 0 {
494 return nil, nil, errors.New("refusing to start cluster with zero nodes")
495 }
496
497 if opts.NumNodes > 2 {
498 return nil, nil, errors.New("launching more than 2 nodes is unsupported pending replacement of golden tickets")
499 }
500
501 go func() {
502 if err := Launch(ctx, Options{ConnectToSocket: vmPorts[0]}); err != nil {
503 // Launch() only terminates when QEMU has terminated. At that point our function probably doesn't run anymore
504 // so we have no way of communicating the error back up, so let's just log it. Also a failure in launching
505 // VMs should be very visible by the unavailability of the clients we return.
506 log.Printf("Failed to launch vm0: %v", err)
507 }
508 }()
509
510 portMap, err := ConflictFreePortMap(NanoswitchPorts)
511 if err != nil {
512 return nil, nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
513 }
514
515 go func() {
516 if err := RunMicroVM(ctx, &MicroVMOptions{
Serge Bazanski77cb6c52020-12-19 00:09:22 +0100517 KernelPath: "metropolis/test/ktest/linux-testing.elf",
518 InitramfsPath: "metropolis/test/nanoswitch/initramfs.lz4",
Lorenz Bruned0503c2020-07-28 17:21:25 +0200519 ExtraNetworkInterfaces: switchPorts,
520 PortMap: portMap,
521 }); err != nil {
522 log.Printf("Failed to launch nanoswitch: %v", err)
523 }
524 }()
525 copts := []grpcretry.CallOption{
526 grpcretry.WithBackoff(grpcretry.BackoffExponential(100 * time.Millisecond)),
527 }
528 conn, err := portMap.DialGRPC(common.DebugServicePort, grpc.WithInsecure(),
529 grpc.WithUnaryInterceptor(grpcretry.UnaryClientInterceptor(copts...)))
530 if err != nil {
531 return nil, nil, fmt.Errorf("failed to dial debug service: %w", err)
532 }
533 defer conn.Close()
534 debug := apb.NewNodeDebugServiceClient(conn)
535
536 if opts.NumNodes == 2 {
537 res, err := debug.GetGoldenTicket(ctx, &apb.GetGoldenTicketRequest{
538 // HACK: this is assigned by DHCP, and we assume that everything goes well.
539 ExternalIp: "10.1.0.3",
540 }, grpcretry.WithMax(10))
541 if err != nil {
542 return nil, nil, fmt.Errorf("failed to get golden ticket: %w", err)
543 }
544
545 ec := &apb.EnrolmentConfig{
546 GoldenTicket: res.Ticket,
547 }
548
549 go func() {
550 if err := Launch(ctx, Options{ConnectToSocket: vmPorts[1], EnrolmentConfig: ec}); err != nil {
551 log.Printf("Failed to launch vm1: %v", err)
552 }
553 }()
554 }
555
556 return debug, portMap, nil
557}