blob: 1e3f42b6079f867c3a23adb4a841f1a2ac60a71e [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Serge Bazanski66e58952021-10-05 17:06:56 +02004// cluster builds on the launch package and implements launching Metropolis
5// nodes and clusters in a virtualized environment using qemu. It's kept in a
6// separate package as it depends on a Metropolis node image, which might not be
7// required for some use of the launch library.
Tim Windelschmidt9f21f532024-05-07 15:14:20 +02008package launch
Serge Bazanski66e58952021-10-05 17:06:56 +02009
10import (
11 "bytes"
12 "context"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010013 "crypto/ed25519"
Serge Bazanski66e58952021-10-05 17:06:56 +020014 "crypto/rand"
15 "crypto/tls"
Serge Bazanski54e212a2023-06-14 13:45:11 +020016 "crypto/x509"
Serge Bazanskia0bc6d32023-06-28 18:57:40 +020017 "encoding/pem"
Serge Bazanski66e58952021-10-05 17:06:56 +020018 "errors"
19 "fmt"
20 "io"
Serge Bazanski66e58952021-10-05 17:06:56 +020021 "net"
Lorenz Brun150f24a2023-07-13 20:11:06 +020022 "net/http"
Serge Bazanski66e58952021-10-05 17:06:56 +020023 "os"
24 "os/exec"
Leopoldacfad5b2023-01-15 14:05:25 +010025 "path"
Serge Bazanski66e58952021-10-05 17:06:56 +020026 "path/filepath"
Serge Bazanski53458ba2024-06-18 09:56:46 +000027 "strconv"
Serge Bazanski630fb5c2023-04-06 10:50:24 +020028 "strings"
Serge Bazanski66e58952021-10-05 17:06:56 +020029 "syscall"
30 "time"
31
32 "github.com/cenkalti/backoff/v4"
Serge Bazanski66e58952021-10-05 17:06:56 +020033 "go.uber.org/multierr"
Serge Bazanskibe742842022-04-04 13:18:50 +020034 "golang.org/x/net/proxy"
Lorenz Brun87bbf7e2024-03-18 18:22:25 +010035 "golang.org/x/sys/unix"
Serge Bazanski66e58952021-10-05 17:06:56 +020036 "google.golang.org/grpc"
Serge Bazanski636032e2022-01-26 14:21:33 +010037 "google.golang.org/grpc/codes"
38 "google.golang.org/grpc/status"
Serge Bazanski66e58952021-10-05 17:06:56 +020039 "google.golang.org/protobuf/proto"
Serge Bazanskia0bc6d32023-06-28 18:57:40 +020040 "k8s.io/client-go/kubernetes"
41 "k8s.io/client-go/rest"
Jan Schärd1a8b642024-12-03 17:40:41 +010042 "k8s.io/utils/ptr"
Serge Bazanski66e58952021-10-05 17:06:56 +020043
Serge Bazanski37cfcc12024-03-21 11:59:07 +010044 ipb "source.monogon.dev/metropolis/node/core/curator/proto/api"
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +020045 apb "source.monogon.dev/metropolis/proto/api"
46 cpb "source.monogon.dev/metropolis/proto/common"
47
Serge Bazanskica8d9512024-09-12 14:20:57 +020048 "source.monogon.dev/go/logging"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010049 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski66e58952021-10-05 17:06:56 +020050 "source.monogon.dev/metropolis/node"
51 "source.monogon.dev/metropolis/node/core/rpc"
Serge Bazanski5bb8a332022-06-23 17:41:33 +020052 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Jan Schär3b0c8dd2025-06-23 10:32:07 +000053 "source.monogon.dev/osbase/blockdev"
54 "source.monogon.dev/osbase/build/mkimage/osimage"
55 "source.monogon.dev/osbase/oci"
56 ociosimage "source.monogon.dev/osbase/oci/osimage"
Jan Schär9d2f3c62025-04-14 11:17:22 +000057 "source.monogon.dev/osbase/oci/registry"
Jan Schär3b0c8dd2025-06-23 10:32:07 +000058 "source.monogon.dev/osbase/structfs"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010059 "source.monogon.dev/osbase/test/qemu"
Serge Bazanski66e58952021-10-05 17:06:56 +020060)
61
Serge Bazanski53458ba2024-06-18 09:56:46 +000062const (
Serge Bazanski20498dd2024-09-30 17:07:08 +000063 // NodeNumberKey is the key of the node label used to carry a node's numerical
Serge Bazanski53458ba2024-06-18 09:56:46 +000064 // index in the test system.
Serge Bazanski20498dd2024-09-30 17:07:08 +000065 NodeNumberKey string = "test-node-number"
Serge Bazanski53458ba2024-06-18 09:56:46 +000066)
67
Leopold20a036e2023-01-15 00:17:19 +010068// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020069type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010070 // Name is a human-readable identifier to be used in debug output.
71 Name string
72
Jan Schära9b060b2024-08-07 10:42:29 +020073 // CPUs is the number of virtual CPUs of the VM.
74 CPUs int
75
76 // ThreadsPerCPU is the number of threads per CPU. This is multiplied by
77 // CPUs to get the total number of threads.
78 ThreadsPerCPU int
79
80 // MemoryMiB is the RAM size in MiB of the VM.
81 MemoryMiB int
82
Jan Schär07003572024-08-26 10:42:16 +020083 // DiskBytes contains the size of the root disk in bytes or zero if the
84 // unmodified image size is used.
85 DiskBytes uint64
86
Serge Bazanski66e58952021-10-05 17:06:56 +020087 // Ports contains the port mapping where to expose the internal ports of the VM to
88 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
89 // ConnectToSocket is set.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010090 Ports qemu.PortMap
Serge Bazanski66e58952021-10-05 17:06:56 +020091
Leopold20a036e2023-01-15 00:17:19 +010092 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
93 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020094 // want to test reboot behavior this should be false.
95 AllowReboot bool
96
Leopold20a036e2023-01-15 00:17:19 +010097 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
98 // set, it is instead connected to the given file descriptor/socket. If this is
99 // set, all port maps from the Ports option are ignored. Intended for networking
100 // this instance together with others for running more complex network
101 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +0200102 ConnectToSocket *os.File
103
Leopoldacfad5b2023-01-15 14:05:25 +0100104 // When PcapDump is set, all traffic is dumped to a pcap file in the
105 // runtime directory (e.g. "net0.pcap" for the first interface).
106 PcapDump bool
107
Leopold20a036e2023-01-15 00:17:19 +0100108 // SerialPort is an io.ReadWriter over which you can communicate with the serial
109 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +0200110 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
111 SerialPort io.ReadWriter
112
113 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
114 // registering into a cluster.
115 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200116
117 // Mac is the node's MAC address.
118 Mac *net.HardwareAddr
119
120 // Runtime keeps the node's QEMU runtime state.
121 Runtime *NodeRuntime
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200122
123 // RunVNC starts a VNC socket for troubleshooting/testing console code. Note:
124 // this will not work in tests, as those use a built-in qemu which does not
125 // implement a VGA device.
126 RunVNC bool
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200127}
128
Leopold20a036e2023-01-15 00:17:19 +0100129// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200130type NodeRuntime struct {
131 // ld points at the node's launch directory storing data such as storage
132 // images, firmware variables or the TPM state.
133 ld string
134 // sd points at the node's socket directory.
135 sd string
136
137 // ctxT is the context QEMU will execute in.
138 ctxT context.Context
139 // CtxC is the QEMU context's cancellation function.
140 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200141}
142
143// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200144var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200145 node.ConsensusPort,
146
147 node.CuratorServicePort,
148 node.DebugServicePort,
149
150 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100151 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200152 node.CuratorServicePort,
153 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200154 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200155}
156
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200157// setupRuntime creates the node's QEMU runtime directory, together with all
158// files required to preserve its state, a level below the chosen path ld. The
159// node's socket directory is similarily created a level below sd. It may
160// return an I/O error.
Jan Schär07003572024-08-26 10:42:16 +0200161func setupRuntime(ld, sd string, diskBytes uint64) (*NodeRuntime, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200162 // Create a temporary directory to keep all the runtime files.
163 stdp, err := os.MkdirTemp(ld, "node_state*")
164 if err != nil {
165 return nil, fmt.Errorf("failed to create the state directory: %w", err)
166 }
167
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000168 // Initialize the node's storage.
169 ociImage, err := oci.ReadLayout(xNodeImagePath)
Jan Schär07003572024-08-26 10:42:16 +0200170 if err != nil {
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000171 return nil, fmt.Errorf("failed to read OS image: %w", err)
Jan Schär07003572024-08-26 10:42:16 +0200172 }
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000173 osImage, err := ociosimage.Read(ociImage)
174 if err != nil {
175 return nil, fmt.Errorf("failed to read OS image: %w", err)
176 }
Jan Schär07003572024-08-26 10:42:16 +0200177
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000178 efiPayload, err := osImage.PayloadUnverified("kernel.efi")
179 if err != nil {
180 return nil, fmt.Errorf("cannot open EFI payload in OS image: %w", err)
181 }
182 systemImage, err := osImage.PayloadUnverified("system")
183 if err != nil {
184 return nil, fmt.Errorf("cannot open system image in OS image: %w", err)
185 }
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200186
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000187 abloader, err := structfs.OSPathBlob(xAbloaderPath)
188 if err != nil {
189 return nil, fmt.Errorf("cannot open abloader: %w", err)
190 }
191
192 di := filepath.Join(stdp, "image.img")
193 logf("Cluster: generating node image: %s -> %s", xNodeImagePath, di)
194
195 df, err := blockdev.CreateFile(di, 512, int64(diskBytes/512))
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200196 if err != nil {
197 return nil, fmt.Errorf("while opening image for writing: %w", err)
198 }
199 defer df.Close()
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000200
201 installParams := &osimage.Params{
202 PartitionSize: osimage.PartitionSizeInfo{
203 ESP: 128,
204 System: 1024,
205 Data: 128,
206 },
207 Architecture: osImage.Config.ProductInfo.Architecture(),
208 SystemImage: systemImage,
209 EFIPayload: efiPayload,
210 ABLoader: abloader,
211 Output: df,
212 }
213 if _, err := osimage.Write(installParams); err != nil {
214 return nil, fmt.Errorf("while creating node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200215 }
216
217 // Initialize the OVMF firmware variables file.
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000218 dv := filepath.Join(stdp, filepath.Base(xOvmfVarsPath))
219 if err := copyFile(xOvmfVarsPath, dv); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200220 return nil, fmt.Errorf("while copying firmware variables: %w", err)
221 }
222
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200223 // Create the socket directory.
224 sotdp, err := os.MkdirTemp(sd, "node_sock*")
225 if err != nil {
226 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
227 }
228
229 return &NodeRuntime{
230 ld: stdp,
231 sd: sotdp,
232 }, nil
233}
234
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200235// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200236// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200237func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200238 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200239 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanskica8d9512024-09-12 14:20:57 +0200240 r := resolver.New(c.ctxT, resolver.WithLogger(logging.NewFunctionBackend(func(severity logging.Severity, msg string) {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100241 logf("Cluster: client resolver: %s: %s", severity, msg)
Serge Bazanskica8d9512024-09-12 14:20:57 +0200242 })))
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100243 for _, n := range c.Nodes {
244 r.AddEndpoint(resolver.NodeAtAddressWithDefaultPort(n.ManagementAddress))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200245 }
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100246 authClient, err := grpc.NewClient(resolver.MetropolisControlAddress,
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200247 grpc.WithTransportCredentials(authCreds),
248 grpc.WithResolvers(r),
249 grpc.WithContextDialer(c.DialNode),
250 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200251 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100252 return nil, fmt.Errorf("creating client with owner credentials failed: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200253 }
254 c.authClient = authClient
255 }
256 return c.authClient, nil
257}
258
Serge Bazanski66e58952021-10-05 17:06:56 +0200259// LaunchNode launches a single Metropolis node instance with the given options.
260// The instance runs mostly paravirtualized but with some emulated hardware
261// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200262// writable, and the changes are kept across reboots and shutdowns. ld and sd
263// point to the launch directory and the socket directory, holding the nodes'
264// state files (storage, tpm state, firmware state), and UNIX socket files
265// (swtpm <-> QEMU interplay) respectively. The directories must exist before
266// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
267// if either are not initialized.
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200268func LaunchNode(ctx context.Context, ld, sd string, tpmFactory *TPMFactory, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200269 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
270 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200271 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
272 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
273 // that we open and pass the name of it to QEMU. Not pinning this crashes both
274 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
275 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200276
Jan Schära9b060b2024-08-07 10:42:29 +0200277 if options.CPUs == 0 {
278 options.CPUs = 1
279 }
280 if options.ThreadsPerCPU == 0 {
281 options.ThreadsPerCPU = 1
282 }
283 if options.MemoryMiB == 0 {
284 options.MemoryMiB = 2048
285 }
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000286 if options.DiskBytes == 0 {
287 options.DiskBytes = 5 * 1024 * 1024 * 1024
288 }
Jan Schära9b060b2024-08-07 10:42:29 +0200289
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200290 // If it's the node's first start, set up its runtime directories.
291 if options.Runtime == nil {
Jan Schär07003572024-08-26 10:42:16 +0200292 r, err := setupRuntime(ld, sd, options.DiskBytes)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200293 if err != nil {
294 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200295 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200296 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200297 }
298
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200299 // Replace the node's context with a new one.
300 r := options.Runtime
301 if r.CtxC != nil {
302 r.CtxC()
303 }
304 r.ctxT, r.CtxC = context.WithCancel(ctx)
305
Serge Bazanski66e58952021-10-05 17:06:56 +0200306 var qemuNetType string
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100307 var qemuNetConfig qemu.QemuValue
Serge Bazanski66e58952021-10-05 17:06:56 +0200308 if options.ConnectToSocket != nil {
309 qemuNetType = "socket"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100310 qemuNetConfig = qemu.QemuValue{
Serge Bazanski66e58952021-10-05 17:06:56 +0200311 "id": {"net0"},
312 "fd": {"3"},
313 }
314 } else {
315 qemuNetType = "user"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100316 qemuNetConfig = qemu.QemuValue{
Serge Bazanski66e58952021-10-05 17:06:56 +0200317 "id": {"net0"},
318 "net": {"10.42.0.0/24"},
319 "dhcpstart": {"10.42.0.10"},
320 "hostfwd": options.Ports.ToQemuForwards(),
321 }
322 }
323
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200324 // Generate the node's MAC address if it isn't already set in NodeOptions.
325 if options.Mac == nil {
326 mac, err := generateRandomEthernetMAC()
327 if err != nil {
328 return err
329 }
330 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200331 }
332
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200333 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
334 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000335 storagePath := filepath.Join(r.ld, "image.img")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200336 qemuArgs := []string{
Jan Schära9b060b2024-08-07 10:42:29 +0200337 "-machine", "q35",
338 "-accel", "kvm",
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200339 "-display", "none",
Jan Schära9b060b2024-08-07 10:42:29 +0200340 "-nodefaults",
341 "-cpu", "host",
342 "-m", fmt.Sprintf("%dM", options.MemoryMiB),
343 "-smp", fmt.Sprintf("cores=%d,threads=%d", options.CPUs, options.ThreadsPerCPU),
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000344 "-drive", "if=pflash,format=raw,readonly=on,file=" + xOvmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200345 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Jan Schär3b0c8dd2025-06-23 10:32:07 +0000346 "-drive", "if=virtio,format=raw,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200347 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200348 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200349 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
350 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
351 "-device", "tpm-tis,tpmdev=tpm0",
352 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200353 "-serial", "stdio",
354 }
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200355 if options.RunVNC {
356 vncSocketPath := filepath.Join(r.sd, "vnc-socket")
357 qemuArgs = append(qemuArgs,
358 "-vnc", "unix:"+vncSocketPath,
359 "-device", "virtio-vga",
360 )
361 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200362
363 if !options.AllowReboot {
364 qemuArgs = append(qemuArgs, "-no-reboot")
365 }
366
367 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200368 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200369 parametersRaw, err := proto.Marshal(options.NodeParameters)
370 if err != nil {
371 return fmt.Errorf("failed to encode node paraeters: %w", err)
372 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200373 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200374 return fmt.Errorf("failed to write node parameters: %w", err)
375 }
376 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
377 }
378
Leopoldacfad5b2023-01-15 14:05:25 +0100379 if options.PcapDump {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100380 qemuNetDump := qemu.QemuValue{
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200381 "id": {"net0"},
382 "netdev": {"net0"},
383 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100384 }
385 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
386 }
387
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200388 // Manufacture TPM if needed.
389 tpmd := filepath.Join(r.ld, "tpm")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000390 err := tpmFactory.Manufacture(ctx, tpmd, &TPMPlatform{
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200391 Manufacturer: "Monogon",
392 Version: "1.0",
393 Model: "TestCluster",
394 })
395 if err != nil {
396 return fmt.Errorf("could not manufacture TPM: %w", err)
397 }
398
Serge Bazanski66e58952021-10-05 17:06:56 +0200399 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200400 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200401
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000402 tpmEmuCmd := exec.CommandContext(tpmCtx, xSwtpmPath, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000403 // Silence warnings from unsafe libtpms build (uses non-constant-time
404 // cryptographic operations).
405 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200406 tpmEmuCmd.Stderr = os.Stderr
407 tpmEmuCmd.Stdout = os.Stdout
408
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100409 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200410 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200411 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200412 return fmt.Errorf("failed to start TPM emulator: %w", err)
413 }
414
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200415 // Wait for the socket to be created by the TPM emulator before launching
416 // QEMU.
417 for {
418 _, err := os.Stat(tpmSocketPath)
419 if err == nil {
420 break
421 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200422 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200423 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200424 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
425 }
426 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200427 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200428 return fmt.Errorf("while waiting for the TPM socket: %w", err)
429 }
430 time.Sleep(time.Millisecond * 100)
431 }
432
Serge Bazanski66e58952021-10-05 17:06:56 +0200433 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200434 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200435 if options.ConnectToSocket != nil {
436 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
437 }
438
439 var stdErrBuf bytes.Buffer
440 systemCmd.Stderr = &stdErrBuf
441 systemCmd.Stdout = options.SerialPort
442
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100443 qemu.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
Leopoldaf5086b2023-01-15 14:12:42 +0100444
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200445 go func() {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100446 logf("Node: Starting...")
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200447 err = systemCmd.Run()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100448 logf("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200449
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200450 // Stop TPM emulator and wait for it to exit to properly reap the child process
451 tpmCancel()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100452 logf("Node: Waiting for TPM emulator to exit")
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200453 // Wait returns a SIGKILL error because we just cancelled its context.
454 // We still need to call it to avoid creating zombies.
455 errTpm := tpmEmuCmd.Wait()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100456 logf("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200457
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200458 var exerr *exec.ExitError
459 if err != nil && errors.As(err, &exerr) {
460 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
461 if status.Signaled() && status.Signal() == syscall.SIGKILL {
462 // Process was killed externally (most likely by our context being canceled).
463 // This is a normal exit for us, so return nil
464 doneC <- nil
465 return
466 }
467 exerr.Stderr = stdErrBuf.Bytes()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100468 newErr := qemu.QEMUError(*exerr)
469 logf("Node: %q", stdErrBuf.String())
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200470 doneC <- &newErr
471 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200472 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200473 doneC <- err
474 }()
475 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200476}
477
478func copyFile(src, dst string) error {
479 in, err := os.Open(src)
480 if err != nil {
481 return fmt.Errorf("when opening source: %w", err)
482 }
483 defer in.Close()
484
485 out, err := os.Create(dst)
486 if err != nil {
487 return fmt.Errorf("when creating destination: %w", err)
488 }
489 defer out.Close()
490
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100491 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200492 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100493 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200494 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100495
496 // Copy the file while preserving its sparseness. The image files are very
497 // sparse (less than 10% allocated), so this is a lot faster.
498 var lastHoleStart int64
499 for {
500 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
501 if err != nil {
502 return fmt.Errorf("when seeking to next data block: %w", err)
503 }
504 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
505 if err != nil {
506 return fmt.Errorf("when seeking to next hole: %w", err)
507 }
508 lastHoleStart = holeStart
509 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
510 return fmt.Errorf("when seeking to current data block: %w", err)
511 }
512 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
513 return fmt.Errorf("when seeking output to next data block: %w", err)
514 }
515 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
516 return fmt.Errorf("when copying file: %w", err)
517 }
518 if endPos == holeStart {
519 // The next hole is at the end of the file, we're done here.
520 break
521 }
522 }
523
Serge Bazanski66e58952021-10-05 17:06:56 +0200524 return out.Close()
525}
526
Serge Bazanskie78a0892021-10-07 17:03:49 +0200527// getNodes wraps around Management.GetNodes to return a list of nodes in a
528// cluster.
529func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200530 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100531 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100532 err := backoff.Retry(func() error {
533 res = nil
534 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200535 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100536 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200537 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100538 for {
539 node, err := srvN.Recv()
540 if err == io.EOF {
541 break
542 }
543 if err != nil {
544 return fmt.Errorf("GetNodes.Recv: %w", err)
545 }
546 res = append(res, node)
547 }
548 return nil
549 }, bo)
550 if err != nil {
551 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200552 }
553 return res, nil
554}
555
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200556// getNode wraps Management.GetNodes. It returns node information matching
557// given node ID.
558func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
559 nodes, err := getNodes(ctx, mgmt)
560 if err != nil {
561 return nil, fmt.Errorf("could not get nodes: %w", err)
562 }
563 for _, n := range nodes {
Jan Schär39d9c242024-09-24 13:49:55 +0200564 if n.Id == id {
565 return n, nil
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200566 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200567 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200568 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200569}
570
Serge Bazanski66e58952021-10-05 17:06:56 +0200571// Gets a random EUI-48 Ethernet MAC address
572func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
573 macBuf := make([]byte, 6)
574 _, err := rand.Read(macBuf)
575 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200576 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200577 }
578
579 // Set U/L bit and clear I/G bit (locally administered individual MAC)
580 // Ref IEEE 802-2014 Section 8.2.2
581 macBuf[0] = (macBuf[0] | 2) & 0xfe
582 mac := net.HardwareAddr(macBuf)
583 return &mac, nil
584}
585
Serge Bazanskibe742842022-04-04 13:18:50 +0200586const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200587
Serge Bazanskibe742842022-04-04 13:18:50 +0200588// ClusterPorts contains all ports handled by Nanoswitch.
589var ClusterPorts = []uint16{
590 // Forwarded to the first node.
591 uint16(node.CuratorServicePort),
592 uint16(node.DebugServicePort),
593 uint16(node.KubernetesAPIPort),
594 uint16(node.KubernetesAPIWrappedPort),
595
596 // SOCKS proxy to the switch network
597 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200598}
599
600// ClusterOptions contains all options for launching a Metropolis cluster.
601type ClusterOptions struct {
602 // The number of nodes this cluster should be started with.
603 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100604
Jan Schära9b060b2024-08-07 10:42:29 +0200605 // Node are default options of all nodes.
606 Node NodeOptions
607
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100608 // If true, node logs will be saved to individual files instead of being printed
609 // out to stderr. The path of these files will be still printed to stdout.
610 //
611 // The files will be located within the launch directory inside TEST_TMPDIR (or
612 // the default tempdir location, if not set).
613 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200614
615 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
616 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
617 // incomplete.
618 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200619
620 // Optional local registry which will be made available to the cluster to
621 // pull images from. This is a more efficient alternative to preseeding all
622 // images used for testing.
Jan Schär9d2f3c62025-04-14 11:17:22 +0000623 LocalRegistry *registry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200624
625 // InitialClusterConfiguration will be passed to the first node when creating the
626 // cluster, and defines some basic properties of the cluster. If not specified,
627 // the cluster will default to defaults as defined in
628 // metropolis.proto.api.NodeParameters.
629 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200630}
631
632// Cluster is the running Metropolis cluster launched using the LaunchCluster
633// function.
634type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200635 // Owner is the TLS Certificate of the owner of the test cluster. This can be
636 // used to authenticate further clients to the running cluster.
637 Owner tls.Certificate
638 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200639 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100640 Ports qemu.PortMap
Serge Bazanski66e58952021-10-05 17:06:56 +0200641
Serge Bazanskibe742842022-04-04 13:18:50 +0200642 // Nodes is a map from Node ID to its runtime information.
643 Nodes map[string]*NodeInCluster
644 // NodeIDs is a list of node IDs that are backing this cluster, in order of
645 // creation.
646 NodeIDs []string
647
Serge Bazanski54e212a2023-06-14 13:45:11 +0200648 // CACertificate is the cluster's CA certificate.
649 CACertificate *x509.Certificate
650
Serge Bazanski66e58952021-10-05 17:06:56 +0200651 // nodesDone is a list of channels populated with the return codes from all the
652 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100653 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200654 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200655 // nodeOpts are the cluster member nodes' mutable launch options, kept here
656 // to facilitate reboots.
657 nodeOpts []NodeOptions
658 // launchDir points at the directory keeping the nodes' state, such as storage
659 // images, firmware variable files, TPM state.
660 launchDir string
661 // socketDir points at the directory keeping UNIX socket files, such as these
662 // used to facilitate communication between QEMU and swtpm. It's different
663 // from launchDir, and anchored nearer the file system root, due to the
664 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100665 socketDir string
666 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200667
Lorenz Brun276a7462023-07-12 21:28:54 +0200668 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200669 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200670 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200671
672 // authClient is a cached authenticated owner connection to a Curator
673 // instance within the cluster.
674 authClient *grpc.ClientConn
675
676 // ctxT is the context individual node contexts are created from.
677 ctxT context.Context
678 // ctxC is used by Close to cancel the context under which the nodes are
679 // running.
680 ctxC context.CancelFunc
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200681
682 tpmFactory *TPMFactory
Serge Bazanskibe742842022-04-04 13:18:50 +0200683}
684
685// NodeInCluster represents information about a node that's part of a Cluster.
686type NodeInCluster struct {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100687 // ID of the node, which can be used to dial this node's services via
688 // NewNodeClient.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200689 ID string
690 Pubkey []byte
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100691 // Address of the node on the network ran by nanoswitch. Not reachable from
692 // the host unless dialed via NewNodeClient or via the nanoswitch SOCKS
693 // proxy (reachable on Cluster.Ports[SOCKSPort]).
Serge Bazanskibe742842022-04-04 13:18:50 +0200694 ManagementAddress string
695}
696
697// firstConnection performs the initial owner credential escrow with a newly
698// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
699// running at 10.1.0.2, which is always the case with the current nanoswitch
700// implementation.
701//
Leopold20a036e2023-01-15 00:17:19 +0100702// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200703// information as NodeInCluster.
704func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
705 // Dial external service.
706 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100707 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200708 if err != nil {
709 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
710 }
711 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
712 return socksDialer.Dial("tcp", addr)
713 }
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100714 initClient, err := grpc.NewClient(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
Serge Bazanskibe742842022-04-04 13:18:50 +0200715 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100716 return nil, nil, fmt.Errorf("creating client with ephemeral credentials failed: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200717 }
718 defer initClient.Close()
719
720 // Retrieve owner certificate - this can take a while because the node is still
721 // coming up, so do it in a backoff loop.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100722 logf("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200723 aaa := apb.NewAAAClient(initClient)
724 var cert *tls.Certificate
725 err = backoff.Retry(func() error {
726 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
727 if st, ok := status.FromError(err); ok {
728 if st.Code() == codes.Unavailable {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100729 logf("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200730 return err
731 }
732 }
733 return backoff.Permanent(err)
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200734 }, backoff.WithContext(backoff.NewExponentialBackOff(backoff.WithMaxElapsedTime(time.Minute)), ctx))
Serge Bazanskibe742842022-04-04 13:18:50 +0200735 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200736 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200737 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100738 logf("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200739
740 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200741 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100742 authClient, err := grpc.NewClient(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
Serge Bazanskibe742842022-04-04 13:18:50 +0200743 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100744 return nil, nil, fmt.Errorf("creating client with owner credentials failed: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200745 }
746 defer authClient.Close()
747 mgmt := apb.NewManagementClient(authClient)
748
749 var node *NodeInCluster
750 err = backoff.Retry(func() error {
751 nodes, err := getNodes(ctx, mgmt)
752 if err != nil {
753 return fmt.Errorf("retrieving nodes failed: %w", err)
754 }
755 if len(nodes) != 1 {
756 return fmt.Errorf("expected one node, got %d", len(nodes))
757 }
758 n := nodes[0]
759 if n.Status == nil || n.Status.ExternalAddress == "" {
760 return fmt.Errorf("node has no status and/or address")
761 }
762 node = &NodeInCluster{
Jan Schär39d9c242024-09-24 13:49:55 +0200763 ID: n.Id,
Serge Bazanskibe742842022-04-04 13:18:50 +0200764 ManagementAddress: n.Status.ExternalAddress,
765 }
766 return nil
767 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
768 if err != nil {
769 return nil, nil, err
770 }
771
772 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200773}
774
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100775func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200776 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100777 if err != nil {
778 return nil, err
779 }
780 return f, nil
781}
782
Serge Bazanski66e58952021-10-05 17:06:56 +0200783// LaunchCluster launches a cluster of Metropolis node VMs together with a
784// Nanoswitch instance to network them all together.
785//
786// The given context will be used to run all qemu instances in the cluster, and
787// canceling the context or calling Close() will terminate them.
788func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200789 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200790 return nil, errors.New("refusing to start cluster with zero nodes")
791 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200792
Jan Schära9b060b2024-08-07 10:42:29 +0200793 // Prepare the node options. These will be kept as part of Cluster.
794 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
795 // launch. The runtime information can be later used to restart a node.
796 // The 0th node will be initialized first. The rest will follow after it
797 // had bootstrapped the cluster.
798 nodeOpts := make([]NodeOptions, opts.NumNodes)
799 for i := range opts.NumNodes {
800 nodeOpts[i] = opts.Node
801 nodeOpts[i].Name = fmt.Sprintf("node%d", i)
802 nodeOpts[i].SerialPort = newPrefixedStdio(i)
803 }
804 nodeOpts[0].NodeParameters = &apb.NodeParameters{
805 Cluster: &apb.NodeParameters_ClusterBootstrap_{
806 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
807 OwnerPublicKey: InsecurePublicKey,
808 InitialClusterConfiguration: opts.InitialClusterConfiguration,
809 Labels: &cpb.NodeLabels{
810 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +0000811 {Key: NodeNumberKey, Value: "0"},
Jan Schära9b060b2024-08-07 10:42:29 +0200812 },
813 },
814 },
815 },
816 }
817 nodeOpts[0].PcapDump = true
818
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200819 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100820 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200821 if err != nil {
822 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
823 }
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200824
825 nodeLogDir := ld
826 if os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR") != "" {
827 nodeLogDir = os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR")
828 }
829
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100830 // Create the metroctl config directory. We keep it in /tmp because in some
831 // scenarios it's end-user visible and we want it short.
832 md, err := os.MkdirTemp("/tmp", "metroctl-*")
833 if err != nil {
834 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
835 }
836
837 // Create the socket directory. We keep it in /tmp because of socket path limits.
838 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200839 if err != nil {
840 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
841 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200842
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200843 // Set up TPM factory.
844 tpmf, err := NewTPMFactory(filepath.Join(ld, "tpm"))
845 if err != nil {
846 return nil, fmt.Errorf("failed to create TPM factory: %w", err)
847 }
848
Serge Bazanski66e58952021-10-05 17:06:56 +0200849 // Prepare links between nodes and nanoswitch.
850 var switchPorts []*os.File
Jan Schära9b060b2024-08-07 10:42:29 +0200851 for i := range opts.NumNodes {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100852 switchPort, vmPort, err := qemu.NewSocketPair()
Serge Bazanski66e58952021-10-05 17:06:56 +0200853 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200854 return nil, fmt.Errorf("failed to get socketpair: %w", err)
855 }
856 switchPorts = append(switchPorts, switchPort)
Jan Schära9b060b2024-08-07 10:42:29 +0200857 nodeOpts[i].ConnectToSocket = vmPort
Serge Bazanski66e58952021-10-05 17:06:56 +0200858 }
859
Serge Bazanskie78a0892021-10-07 17:03:49 +0200860 // Make a list of channels that will be populated by all running node qemu
861 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200862 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200863 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200864 done[i] = make(chan error, 1)
865 }
866
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100867 if opts.NodeLogsToFiles {
Jan Schära9b060b2024-08-07 10:42:29 +0200868 for i := range opts.NumNodes {
Lorenz Brun4beaf4f2025-01-14 16:10:55 +0100869 path := path.Join(nodeLogDir, fmt.Sprintf("node-%d.txt", i))
Jan Schära9b060b2024-08-07 10:42:29 +0200870 port, err := NewSerialFileLogger(path)
871 if err != nil {
872 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
873 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100874 logf("Node %d logs at %s", i, path)
Jan Schära9b060b2024-08-07 10:42:29 +0200875 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100876 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100877 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200878
879 // Start the first node.
880 ctxT, ctxC := context.WithCancel(ctx)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100881 logf("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200882 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200883 ctxC()
884 return nil, fmt.Errorf("failed to launch first node: %w", err)
885 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200886
Lorenz Brun150f24a2023-07-13 20:11:06 +0200887 localRegistryAddr := net.TCPAddr{
888 IP: net.IPv4(10, 42, 0, 82),
889 Port: 5000,
890 }
891
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100892 var guestSvcMap qemu.GuestServiceMap
Lorenz Brun150f24a2023-07-13 20:11:06 +0200893 if opts.LocalRegistry != nil {
894 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
895 if err != nil {
896 ctxC()
897 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
898 }
899 s := http.Server{
900 Handler: opts.LocalRegistry,
901 }
902 go s.Serve(l)
903 go func() {
904 <-ctxT.Done()
905 s.Close()
906 }()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100907 guestSvcMap = qemu.GuestServiceMap{
Lorenz Brun150f24a2023-07-13 20:11:06 +0200908 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
909 }
910 }
911
Serge Bazanskie78a0892021-10-07 17:03:49 +0200912 // Launch nanoswitch.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100913 portMap, err := qemu.ConflictFreePortMap(ClusterPorts)
Serge Bazanski66e58952021-10-05 17:06:56 +0200914 if err != nil {
915 ctxC()
916 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
917 }
918
919 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100920 var serialPort io.ReadWriter
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100921 var err error
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100922 if opts.NodeLogsToFiles {
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200923
924 loggerPath := path.Join(nodeLogDir, "nanoswitch.txt")
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100925 serialPort, err = NewSerialFileLogger(loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100926 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100927 logf("Could not open log file for nanoswitch: %v", err)
928 os.Exit(1)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100929 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100930 logf("Nanoswitch logs at %s", loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100931 } else {
932 serialPort = newPrefixedStdio(99)
933 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100934 if err := qemu.RunMicroVM(ctxT, &qemu.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100935 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000936 KernelPath: xKernelPath,
937 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200938 ExtraNetworkInterfaces: switchPorts,
939 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200940 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100941 SerialPort: serialPort,
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200942 PcapDump: path.Join(nodeLogDir, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200943 }); err != nil {
944 if !errors.Is(err, ctxT.Err()) {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100945 logf("Failed to launch nanoswitch: %v", err)
946 os.Exit(1)
Serge Bazanski66e58952021-10-05 17:06:56 +0200947 }
948 }
949 }()
950
Serge Bazanskibe742842022-04-04 13:18:50 +0200951 // Build SOCKS dialer.
952 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
953 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200954 if err != nil {
955 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200956 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200957 }
958
Serge Bazanskibe742842022-04-04 13:18:50 +0200959 // Retrieve owner credentials and first node.
960 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200961 if err != nil {
962 ctxC()
963 return nil, err
964 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200965
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100966 // Write credentials to the metroctl directory.
967 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
968 ctxC()
969 return nil, fmt.Errorf("could not write owner key: %w", err)
970 }
971 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
972 ctxC()
973 return nil, fmt.Errorf("could not write owner certificate: %w", err)
974 }
975
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100976 logf("Cluster: Node %d is %s", 0, firstNode.ID)
Serge Bazanski53458ba2024-06-18 09:56:46 +0000977
978 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200979 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200980 cluster := &Cluster{
981 Owner: *cert,
982 Ports: portMap,
983 Nodes: map[string]*NodeInCluster{
984 firstNode.ID: firstNode,
985 },
986 NodeIDs: []string{
987 firstNode.ID,
988 },
989
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100990 nodesDone: done,
991 nodeOpts: nodeOpts,
992 launchDir: ld,
993 socketDir: sd,
994 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200995
Lorenz Brun276a7462023-07-12 21:28:54 +0200996 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200997
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200998 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200999 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001000
1001 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +02001002 }
1003
1004 // Now start the rest of the nodes and register them into the cluster.
1005
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001006 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001007 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +02001008 if err != nil {
1009 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001010 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001011 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001012 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001013
1014 // Retrieve register ticket to register further nodes.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001015 logf("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001016 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
1017 if err != nil {
1018 ctxC()
1019 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
1020 }
1021 ticket := resT.Ticket
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001022 logf("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +02001023
1024 // Retrieve cluster info (for directory and ca public key) to register further
1025 // nodes.
1026 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
1027 if err != nil {
1028 ctxC()
1029 return nil, fmt.Errorf("GetClusterInfo: %w", err)
1030 }
Serge Bazanski54e212a2023-06-14 13:45:11 +02001031 caCert, err := x509.ParseCertificate(resI.CaCertificate)
1032 if err != nil {
1033 ctxC()
1034 return nil, fmt.Errorf("ParseCertificate: %w", err)
1035 }
1036 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +02001037
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001038 // Use the retrieved information to configure the rest of the node options.
1039 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +02001040 nodeOpts[i].NodeParameters = &apb.NodeParameters{
1041 Cluster: &apb.NodeParameters_ClusterRegister_{
1042 ClusterRegister: &apb.NodeParameters_ClusterRegister{
1043 RegisterTicket: ticket,
1044 ClusterDirectory: resI.ClusterDirectory,
1045 CaCertificate: resI.CaCertificate,
1046 Labels: &cpb.NodeLabels{
1047 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +00001048 {Key: NodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +02001049 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001050 },
1051 },
1052 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001053 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001054 }
1055
1056 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001057 for i := 1; i < opts.NumNodes; i++ {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001058 logf("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001059 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001060 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001061 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001062 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001063 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001064
Serge Bazanski53458ba2024-06-18 09:56:46 +00001065 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001066 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001067 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001068 nodeNumberToID := make(map[int]string)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001069 logf("Cluster: waiting for nodes to appear as NEW...")
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001070 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001071 for {
1072 nodes, err := getNodes(ctx, mgmt)
1073 if err != nil {
1074 ctxC()
1075 return nil, fmt.Errorf("could not get nodes: %w", err)
1076 }
1077 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001078 if n.State != cpb.NodeState_NODE_STATE_NEW {
1079 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001080 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001081 if seenNodes[n.Id] {
1082 continue
1083 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001084 seenNodes[n.Id] = true
1085 cluster.Nodes[n.Id] = &NodeInCluster{
1086 ID: n.Id,
1087 Pubkey: n.Pubkey,
1088 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001089
Serge Bazanski20498dd2024-09-30 17:07:08 +00001090 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, NodeNumberKey))
Serge Bazanski53458ba2024-06-18 09:56:46 +00001091 if err != nil {
1092 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1093 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001094 logf("Cluster: Node %d is %s", num, n.Id)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001095 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001096 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001097
1098 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001099 break
1100 }
1101 time.Sleep(1 * time.Second)
1102 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001103 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001104 logf("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001105
Serge Bazanski53458ba2024-06-18 09:56:46 +00001106 // Build the rest of NodeIDs from map.
1107 for i := 1; i < opts.NumNodes; i++ {
1108 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1109 }
1110
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001111 approvedNodes := make(map[string]bool)
1112 upNodes := make(map[string]bool)
1113 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001114 for {
1115 nodes, err := getNodes(ctx, mgmt)
1116 if err != nil {
1117 ctxC()
1118 return nil, fmt.Errorf("could not get nodes: %w", err)
1119 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001120 for _, node := range nodes {
1121 if !seenNodes[node.Id] {
1122 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001123 continue
1124 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001125
1126 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001127 logf("Cluster: node %s is up", node.Id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001128 upNodes[node.Id] = true
1129 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001130 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001131 if upNodes[node.Id] {
1132 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001133 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001134
1135 if !approvedNodes[node.Id] {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001136 logf("Cluster: approving node %s", node.Id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001137 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1138 Pubkey: node.Pubkey,
1139 })
1140 if err != nil {
1141 ctxC()
1142 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1143 }
1144 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001145 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001146 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001147
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001148 logf("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001149 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001150 break
1151 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001152 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001153 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001154 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001155
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001156 logf("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001157 for i, nodeID := range cluster.NodeIDs {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001158 logf("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001159 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001160 logf("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001161
Serge Bazanskibe742842022-04-04 13:18:50 +02001162 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001163}
1164
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001165// RebootNode reboots the cluster member node matching the given index, and
1166// waits for it to rejoin the cluster. It will use the given context ctx to run
1167// cluster API requests, whereas the resulting QEMU process will be created
1168// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1169func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1170 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001171 return fmt.Errorf("index out of bounds")
1172 }
1173 if c.nodeOpts[idx].Runtime == nil {
1174 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001175 }
1176 id := c.NodeIDs[idx]
1177
1178 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001179 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001180 if err != nil {
1181 return err
1182 }
1183 mgmt := apb.NewManagementClient(curC)
1184
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001185 // Cancel the node's context. This will shut down QEMU.
1186 c.nodeOpts[idx].Runtime.CtxC()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001187 logf("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001188 err = <-c.nodesDone[idx]
1189 if err != nil {
1190 return fmt.Errorf("while restarting node: %w", err)
1191 }
1192
1193 // Start QEMU again.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001194 logf("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001195 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, c.tpmFactory, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001196 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1197 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001198
Serge Bazanskibc969572024-03-21 11:56:13 +01001199 start := time.Now()
1200
1201 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001202 for {
1203 cs, err := getNode(ctx, mgmt, id)
1204 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001205 logf("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001206 return err
1207 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001208 logf("Cluster: node health: %+v", cs.Health)
Serge Bazanskibc969572024-03-21 11:56:13 +01001209
1210 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001211 if lhb.After(start) && cs.Health == apb.Node_HEALTH_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001212 break
1213 }
1214 time.Sleep(time.Second)
1215 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001216 logf("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001217 return nil
1218}
1219
Serge Bazanski500f6e02024-04-03 12:06:40 +02001220// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1221// given by idx. If the node is already shut down, this is a no-op.
1222func (c *Cluster) ShutdownNode(idx int) error {
1223 if idx < 0 || idx >= len(c.NodeIDs) {
1224 return fmt.Errorf("index out of bounds")
1225 }
1226 // Return if node is already stopped.
1227 select {
1228 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1229 return nil
1230 default:
1231 }
1232 id := c.NodeIDs[idx]
1233
1234 // Cancel the node's context. This will shut down QEMU.
1235 c.nodeOpts[idx].Runtime.CtxC()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001236 logf("Cluster: waiting for node %d (%s) to stop.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001237 err := <-c.nodesDone[idx]
1238 if err != nil {
1239 return fmt.Errorf("while shutting down node: %w", err)
1240 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001241 logf("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001242 return nil
1243}
1244
1245// StartNode performs a power on of the node given by idx. If the node is already
1246// running, this is a no-op.
1247func (c *Cluster) StartNode(idx int) error {
1248 if idx < 0 || idx >= len(c.NodeIDs) {
1249 return fmt.Errorf("index out of bounds")
1250 }
1251 id := c.NodeIDs[idx]
1252 // Return if node is already running.
1253 select {
1254 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1255 default:
1256 return nil
1257 }
1258
1259 // Start QEMU again.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001260 logf("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001261 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, c.tpmFactory, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
Serge Bazanski500f6e02024-04-03 12:06:40 +02001262 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1263 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001264 logf("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001265 return nil
1266}
1267
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001268// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001269// nodes to stop. It returns an error if stopping the nodes failed, or one of
1270// the nodes failed to fully start in the first place.
1271func (c *Cluster) Close() error {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001272 logf("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001273 if c.authClient != nil {
1274 c.authClient.Close()
1275 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001276 c.ctxC()
1277
Leopold20a036e2023-01-15 00:17:19 +01001278 var errs []error
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001279 logf("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001280 for _, c := range c.nodesDone {
1281 err := <-c
1282 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001283 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001284 }
1285 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001286 logf("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001287 os.RemoveAll(c.launchDir)
1288 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001289 os.RemoveAll(c.metroctlDir)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001290 logf("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001291 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001292}
Serge Bazanskibe742842022-04-04 13:18:50 +02001293
1294// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1295// their ID. This is performed by connecting to the cluster nanoswitch via its
1296// SOCKS proxy, and using the cluster node list for name resolution.
1297//
1298// For example:
1299//
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +01001300// grpc.NewClient("passthrough:///metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001301func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1302 host, port, err := net.SplitHostPort(addr)
1303 if err != nil {
1304 return nil, fmt.Errorf("invalid host:port: %w", err)
1305 }
1306 // Already an IP address?
1307 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001308 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001309 }
1310
1311 // Otherwise, expect a node name.
1312 node, ok := c.Nodes[host]
1313 if !ok {
1314 return nil, fmt.Errorf("unknown node %q", host)
1315 }
1316 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001317 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001318}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001319
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001320// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1321// Kubernetes authenticating proxy using the cluster owner identity.
1322// It currently has access to everything (i.e. the cluster-admin role)
1323// via the owner-admin binding.
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001324func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, *rest.Config, error) {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001325 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1326 if err != nil {
1327 // We explicitly pass an Ed25519 private key in, so this can't happen
1328 panic(err)
1329 }
1330
1331 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001332 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001333 Host: host,
1334 TLSClientConfig: rest.TLSClientConfig{
1335 // TODO(q3k): use CA certificate
1336 Insecure: true,
1337 ServerName: "kubernetes.default.svc",
1338 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1339 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1340 },
1341 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1342 return c.DialNode(ctx, address)
1343 },
1344 }
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001345 clientSet, err := kubernetes.NewForConfig(&clientConfig)
1346 if err != nil {
1347 return nil, nil, err
1348 }
1349 return clientSet, &clientConfig, nil
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001350}
1351
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001352// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1353// which are currently Kubernetes controllers, ie. run an apiserver. This list
1354// might be empty if no node is currently configured with the
1355// 'KubernetesController' node.
1356func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1357 curC, err := c.CuratorClient()
1358 if err != nil {
1359 return nil, err
1360 }
1361 mgmt := apb.NewManagementClient(curC)
1362 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1363 Filter: "has(node.roles.kubernetes_controller)",
1364 })
1365 if err != nil {
1366 return nil, err
1367 }
1368 defer srv.CloseSend()
1369 var res []string
1370 for {
1371 n, err := srv.Recv()
1372 if err == io.EOF {
1373 break
1374 }
1375 if err != nil {
1376 return nil, err
1377 }
1378 if n.Status == nil || n.Status.ExternalAddress == "" {
1379 continue
1380 }
1381 res = append(res, n.Status.ExternalAddress)
1382 }
1383 return res, nil
1384}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001385
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001386// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1387// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001388func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1389 // Get an authenticated owner client within the cluster.
1390 curC, err := c.CuratorClient()
1391 if err != nil {
1392 return err
1393 }
1394 mgmt := apb.NewManagementClient(curC)
1395 nodes, err := getNodes(ctx, mgmt)
1396 if err != nil {
1397 return err
1398 }
1399
1400 var unhealthy []string
1401 for _, node := range nodes {
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001402 if node.Health == apb.Node_HEALTH_HEALTHY {
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001403 continue
1404 }
1405 unhealthy = append(unhealthy, node.Id)
1406 }
1407 if len(unhealthy) == 0 {
1408 return nil
1409 }
1410 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1411}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001412
1413// ApproveNode approves a node by ID, waiting for it to become UP.
1414func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1415 curC, err := c.CuratorClient()
1416 if err != nil {
1417 return err
1418 }
1419 mgmt := apb.NewManagementClient(curC)
1420
1421 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1422 Pubkey: c.Nodes[id].Pubkey,
1423 })
1424 if err != nil {
1425 return fmt.Errorf("ApproveNode: %w", err)
1426 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001427 logf("Cluster: %s: approved, waiting for UP", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001428 for {
1429 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1430 if err != nil {
1431 return fmt.Errorf("GetNodes: %w", err)
1432 }
1433 found := false
1434 for {
1435 node, err := nodes.Recv()
1436 if errors.Is(err, io.EOF) {
1437 break
1438 }
1439 if err != nil {
1440 return fmt.Errorf("Nodes.Recv: %w", err)
1441 }
1442 if node.Id != id {
1443 continue
1444 }
1445 if node.State != cpb.NodeState_NODE_STATE_UP {
1446 continue
1447 }
1448 found = true
1449 break
1450 }
1451 nodes.CloseSend()
1452
1453 if found {
1454 break
1455 }
1456 time.Sleep(time.Second)
1457 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001458 logf("Cluster: %s: UP", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001459 return nil
1460}
1461
1462// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1463func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1464 curC, err := c.CuratorClient()
1465 if err != nil {
1466 return err
1467 }
1468 mgmt := apb.NewManagementClient(curC)
1469
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001470 logf("Cluster: %s: adding KubernetesWorker", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001471 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1472 Node: &apb.UpdateNodeRolesRequest_Id{
1473 Id: id,
1474 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001475 KubernetesWorker: ptr.To(true),
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001476 })
1477 return err
1478}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001479
Jan Schära9b060b2024-08-07 10:42:29 +02001480// MakeKubernetesController adds the KubernetesController role to a node by ID.
1481func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1482 curC, err := c.CuratorClient()
1483 if err != nil {
1484 return err
1485 }
1486 mgmt := apb.NewManagementClient(curC)
1487
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001488 logf("Cluster: %s: adding KubernetesController", id)
Jan Schära9b060b2024-08-07 10:42:29 +02001489 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1490 Node: &apb.UpdateNodeRolesRequest_Id{
1491 Id: id,
1492 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001493 KubernetesController: ptr.To(true),
Jan Schära9b060b2024-08-07 10:42:29 +02001494 })
1495 return err
1496}
1497
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001498// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1499func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1500 curC, err := c.CuratorClient()
1501 if err != nil {
1502 return err
1503 }
1504 mgmt := apb.NewManagementClient(curC)
1505 cur := ipb.NewCuratorClient(curC)
1506
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001507 logf("Cluster: %s: adding ConsensusMember", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001508 bo := backoff.NewExponentialBackOff()
1509 bo.MaxElapsedTime = 10 * time.Second
1510
1511 backoff.Retry(func() error {
1512 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1513 Node: &apb.UpdateNodeRolesRequest_Id{
1514 Id: id,
1515 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001516 ConsensusMember: ptr.To(true),
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001517 })
1518 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001519 logf("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001520 }
1521 return err
1522 }, backoff.WithContext(bo, ctx))
1523 if err != nil {
1524 return err
1525 }
1526
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001527 logf("Cluster: %s: waiting for learner/full members...", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001528
1529 learner := false
1530 for {
1531 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1532 if err != nil {
1533 return fmt.Errorf("GetConsensusStatus: %w", err)
1534 }
1535 for _, member := range res.EtcdMember {
1536 if member.Id != id {
1537 continue
1538 }
1539 switch member.Status {
1540 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1541 if !learner {
1542 learner = true
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001543 logf("Cluster: %s: became a learner, waiting for full member...", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001544 }
1545 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001546 logf("Cluster: %s: became a full member", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001547 return nil
1548 }
1549 }
1550 time.Sleep(100 * time.Millisecond)
1551 }
1552}