blob: f45685273b0ae2775b24960dd8e7d0f6cdb8e65c [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
37 grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020038
Lorenz Brun3ff5af32020-06-24 16:34:11 +020039 "github.com/golang/protobuf/proto"
40 "golang.org/x/sys/unix"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020041 "google.golang.org/grpc"
42
43 "git.monogon.dev/source/nexantic.git/core/internal/common"
Serge Bazanskiefdb6e92020-07-13 17:19:27 +020044 apb "git.monogon.dev/source/nexantic.git/core/proto/api"
Serge Bazanskicb883e22020-07-06 17:47:55 +020045 freeport "git.monogon.dev/source/nexantic.git/golibs/common"
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020046)
47
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020048type qemuValue map[string][]string
49
Lorenz Brun3ff5af32020-06-24 16:34:11 +020050// toOption encodes structured data into a QEMU option.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020051// Example: "test", {"key1": {"val1"}, "key2": {"val2", "val3"}} returns "test,key1=val1,key2=val2,key2=val3"
Lorenz Brun3ff5af32020-06-24 16:34:11 +020052func (value qemuValue) toOption(name string) string {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020053 var optionValues []string
Lorenz Brun3ff5af32020-06-24 16:34:11 +020054 if name != "" {
55 optionValues = append(optionValues, name)
56 }
Lorenz Brunfc5dbc62020-05-28 12:18:07 +020057 for name, values := range value {
58 if len(values) == 0 {
59 optionValues = append(optionValues, name)
60 }
61 for _, val := range values {
62 optionValues = append(optionValues, fmt.Sprintf("%v=%v", name, val))
63 }
64 }
65 return strings.Join(optionValues, ",")
66}
67
68func copyFile(src, dst string) error {
69 in, err := os.Open(src)
70 if err != nil {
71 return err
72 }
73 defer in.Close()
74
75 out, err := os.Create(dst)
76 if err != nil {
77 return err
78 }
79 defer out.Close()
80
81 _, err = io.Copy(out, in)
82 if err != nil {
83 return err
84 }
85 return out.Close()
86}
87
88// PortMap represents where VM ports are mapped to on the host. It maps from the VM port number to the host port number.
89type PortMap map[uint16]uint16
90
91// toQemuForwards generates QEMU hostfwd values (https://qemu.weilnetz.de/doc/qemu-doc.html#:~:text=hostfwd=) for all
92// mapped ports.
93func (p PortMap) toQemuForwards() []string {
94 var hostfwdOptions []string
95 for vmPort, hostPort := range p {
96 hostfwdOptions = append(hostfwdOptions, fmt.Sprintf("tcp::%v-:%v", hostPort, vmPort))
97 }
98 return hostfwdOptions
99}
100
101// DialGRPC creates a gRPC client for a VM port that's forwarded/mapped to the host. The given port is automatically
102// resolved to the host-mapped port.
103func (p PortMap) DialGRPC(port uint16, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
104 mappedPort, ok := p[port]
105 if !ok {
106 return nil, fmt.Errorf("cannot dial port: port %v is not mapped/forwarded", port)
107 }
108 grpcClient, err := grpc.Dial(fmt.Sprintf("localhost:%v", mappedPort), opts...)
109 if err != nil {
110 return nil, fmt.Errorf("failed to dial port %v: %w", port, err)
111 }
112 return grpcClient, nil
113}
114
115// Options contains all options that can be passed to Launch()
116type Options struct {
117 // 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 +0200118 // and ConflictFreePortMap(). Ignored when ConnectToSocket is set.
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200119 Ports PortMap
120
121 // If set to true, reboots are honored. Otherwise all reboots exit the Launch() command. Smalltown generally restarts
122 // on almost all errors, so unless you want to test reboot behavior this should be false.
123 AllowReboot bool
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200124
125 // By default the Smalltown VM is connected to the Host via SLIRP. If ConnectToSocket is set, it is instead connected
126 // to the given file descriptor/socket. If this is set, all port maps from the Ports option are ignored.
127 // Intended for networking this instance together with others for running more complex network configurations.
128 ConnectToSocket *os.File
129
130 // SerialPort is a File(descriptor) over which you can communicate with the serial port of the machine
131 // It can be set to an existing file descriptor (like os.Stdout/os.Stderr) or you can use NewSocketPair() to get one
132 // end to talk to from Go.
133 SerialPort *os.File
134
135 // 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 +0200136 EnrolmentConfig *apb.EnrolmentConfig
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200137}
138
Lorenz Bruned0503c2020-07-28 17:21:25 +0200139// NodePorts is the list of ports a fully operational Smalltown node listens on
140var NodePorts = []uint16{common.ConsensusPort, common.NodeServicePort, common.MasterServicePort,
Lorenz Brun70f65b22020-07-08 17:02:47 +0200141 common.ExternalServicePort, common.DebugServicePort, common.KubernetesAPIPort, common.DebuggerPort}
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200142
Lorenz Bruned0503c2020-07-28 17:21:25 +0200143// 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 +0200144// for development against Smalltown. The dbg command requires this mapping.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200145func IdentityPortMap(ports []uint16) PortMap {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200146 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200147 for _, port := range ports {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200148 portMap[port] = port
149 }
150 return portMap
151}
152
Lorenz Bruned0503c2020-07-28 17:21:25 +0200153// 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 +0200154// intended for automated testing where multiple instances of Smalltown might be running. Please call this function for
155// each Launch command separately and as close to it as possible since it cannot guarantee that the ports will remain
156// free.
Lorenz Bruned0503c2020-07-28 17:21:25 +0200157func ConflictFreePortMap(ports []uint16) (PortMap, error) {
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200158 portMap := make(PortMap)
Lorenz Bruned0503c2020-07-28 17:21:25 +0200159 for _, port := range ports {
Serge Bazanskicb883e22020-07-06 17:47:55 +0200160 mappedPort, listenCloser, err := freeport.AllocateTCPPort()
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200161 if err != nil {
162 return portMap, fmt.Errorf("failed to get free host port: %w", err)
163 }
164 // Defer closing of the listening port until the function is done and all ports are allocated
165 defer listenCloser.Close()
166 portMap[port] = mappedPort
167 }
168 return portMap, nil
169}
170
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200171// Gets a random EUI-48 Ethernet MAC address
172func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
173 macBuf := make([]byte, 6)
174 _, err := rand.Read(macBuf)
175 if err != nil {
176 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
177 }
178
179 // Set U/L bit and clear I/G bit (locally administered individual MAC)
180 // Ref IEEE 802-2014 Section 8.2.2
181 macBuf[0] = (macBuf[0] | 2) & 0xfe
182 mac := net.HardwareAddr(macBuf)
183 return &mac, nil
184}
185
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200186// Launch launches a Smalltown instance with the given options. The instance runs mostly paravirtualized but with some
187// emulated hardware similar to how a cloud provider might set up its VMs. The disk is fully writable but is run
188// in snapshot mode meaning that changes are not kept beyond a single invocation.
189func Launch(ctx context.Context, options Options) error {
190 // Pin temp directory to /tmp until we can use abstract socket namespace in QEMU (next release after 5.0,
191 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9). swtpm accepts already-open FDs
192 // so we can pass in an abstract socket namespace FD that we open and pass the name of it to QEMU. Not pinning this
193 // crashes both swtpm and qemu because we run into UNIX socket length limitations (for legacy reasons 108 chars).
194 tempDir, err := ioutil.TempDir("/tmp", "launch*")
195 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200196 return fmt.Errorf("failed to create temporary directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200197 }
198 defer os.RemoveAll(tempDir)
199
200 // Copy TPM state into a temporary directory since it's being modified by the emulator
201 tpmTargetDir := filepath.Join(tempDir, "tpm")
202 tpmSrcDir := "core/tpm"
203 if err := os.Mkdir(tpmTargetDir, 0644); err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200204 return fmt.Errorf("failed to create TPM state directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200205 }
206 tpmFiles, err := ioutil.ReadDir(tpmSrcDir)
207 if err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200208 return fmt.Errorf("failed to read TPM directory: %w", err)
Lorenz Brunfc5dbc62020-05-28 12:18:07 +0200209 }
210 for _, file := range tpmFiles {
211 name := file.Name()
212 if err := copyFile(filepath.Join(tpmSrcDir, name), filepath.Join(tpmTargetDir, name)); err != nil {
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200213 return fmt.Errorf("failed to copy TPM directory: %w", 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",
246 "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file=core/smalltown.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
Lorenz Brun3ff5af32020-06-24 16:34:11 +0200259 if options.EnrolmentConfig != nil {
260 enrolmentConfigPath := filepath.Join(tempDir, "enrolment.pb")
261 enrolmentConfigRaw, err := proto.Marshal(options.EnrolmentConfig)
262 if err != nil {
263 return fmt.Errorf("failed to encode enrolment config: %w", err)
264 }
265 if err := ioutil.WriteFile(enrolmentConfigPath, enrolmentConfigRaw, 0644); err != nil {
266 return fmt.Errorf("failed to write enrolment config: %w", err)
267 }
268 qemuArgs = append(qemuArgs, "-fw_cfg", "name=com.nexantic.smalltown/enrolment.pb,file="+enrolmentConfigPath)
269 }
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{
470 common.ExternalServicePort,
471 common.DebugServicePort,
472 common.KubernetesAPIPort,
473}
474
475// ClusterOptions contains all options for launching a Smalltown cluster
476type ClusterOptions struct {
477 // The number of nodes this cluster should be started with initially
478 NumNodes int
479}
480
481// LaunchCluster launches a cluster of Smalltown VMs together with a Nanoswitch instance to network them all together.
482func 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() {
503 if err := Launch(ctx, Options{ConnectToSocket: vmPorts[0]}); err != nil {
504 // Launch() only terminates when QEMU has terminated. At that point our function probably doesn't run anymore
505 // so we have no way of communicating the error back up, so let's just log it. Also a failure in launching
506 // VMs should be very visible by the unavailability of the clients we return.
507 log.Printf("Failed to launch vm0: %v", err)
508 }
509 }()
510
511 portMap, err := ConflictFreePortMap(NanoswitchPorts)
512 if err != nil {
513 return nil, nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
514 }
515
516 go func() {
517 if err := RunMicroVM(ctx, &MicroVMOptions{
518 KernelPath: "core/tools/ktest/linux-testing.elf",
519 InitramfsPath: "core/cmd/nanoswitch/initramfs.lz4",
520 ExtraNetworkInterfaces: switchPorts,
521 PortMap: portMap,
522 }); err != nil {
523 log.Printf("Failed to launch nanoswitch: %v", err)
524 }
525 }()
526 copts := []grpcretry.CallOption{
527 grpcretry.WithBackoff(grpcretry.BackoffExponential(100 * time.Millisecond)),
528 }
529 conn, err := portMap.DialGRPC(common.DebugServicePort, grpc.WithInsecure(),
530 grpc.WithUnaryInterceptor(grpcretry.UnaryClientInterceptor(copts...)))
531 if err != nil {
532 return nil, nil, fmt.Errorf("failed to dial debug service: %w", err)
533 }
534 defer conn.Close()
535 debug := apb.NewNodeDebugServiceClient(conn)
536
537 if opts.NumNodes == 2 {
538 res, err := debug.GetGoldenTicket(ctx, &apb.GetGoldenTicketRequest{
539 // HACK: this is assigned by DHCP, and we assume that everything goes well.
540 ExternalIp: "10.1.0.3",
541 }, grpcretry.WithMax(10))
542 if err != nil {
543 return nil, nil, fmt.Errorf("failed to get golden ticket: %w", err)
544 }
545
546 ec := &apb.EnrolmentConfig{
547 GoldenTicket: res.Ticket,
548 }
549
550 go func() {
551 if err := Launch(ctx, Options{ConnectToSocket: vmPorts[1], EnrolmentConfig: ec}); err != nil {
552 log.Printf("Failed to launch vm1: %v", err)
553 }
554 }()
555 }
556
557 return debug, portMap, nil
558}